Messaging/pkg/server/auth.go

55 lines
1.2 KiB
Go
Raw Normal View History

2024-03-26 15:05:13 +00:00
package server
import (
"strings"
"git.solsynth.dev/hydrogen/messaging/pkg/services"
"github.com/gofiber/fiber/v2"
)
func authMiddleware(c *fiber.Ctx) error {
var token string
2024-05-04 16:39:59 +00:00
if cookie := c.Cookies(services.CookieAccessKey); len(cookie) > 0 {
2024-03-26 15:05:13 +00:00
token = cookie
}
if header := c.Get(fiber.HeaderAuthorization); len(header) > 0 {
tk := strings.Replace(header, "Bearer", "", 1)
token = strings.TrimSpace(tk)
}
2024-03-30 13:59:05 +00:00
if query := c.Query("tk"); len(query) > 0 {
token = strings.TrimSpace(query)
}
2024-03-26 15:05:13 +00:00
c.Locals("token", token)
if err := authFunc(c); err != nil {
return err
}
return c.Next()
}
func authFunc(c *fiber.Ctx, overrides ...string) error {
var token string
if len(overrides) > 0 {
token = overrides[0]
} else {
if tk, ok := c.Locals("token").(string); !ok {
return fiber.NewError(fiber.StatusUnauthorized)
} else {
token = tk
}
}
2024-05-04 16:39:59 +00:00
rtk := c.Cookies(services.CookieRefreshKey)
2024-03-26 15:05:13 +00:00
if user, atk, rtk, err := services.Authenticate(token, rtk); err == nil {
if atk != token {
2024-05-04 16:39:59 +00:00
services.SetJwtCookieSet(c, atk, rtk)
2024-03-26 15:05:13 +00:00
}
c.Locals("principal", user)
return nil
} else {
return fiber.NewError(fiber.StatusUnauthorized, err.Error())
}
}