2024-02-18 07:51:27 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
2024-03-20 12:56:43 +00:00
|
|
|
|
2024-04-13 05:48:19 +00:00
|
|
|
"git.solsynth.dev/hydrogen/passport/pkg/services"
|
2024-03-20 12:56:43 +00:00
|
|
|
"github.com/gofiber/fiber/v2"
|
2024-02-18 07:51:27 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func authMiddleware(c *fiber.Ctx) error {
|
|
|
|
var token string
|
2024-04-20 11:04:33 +00:00
|
|
|
if cookie := c.Cookies(services.CookieAccessKey); len(cookie) > 0 {
|
2024-02-18 07:51:27 +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-31 05:04:48 +00:00
|
|
|
if query := c.Query("tk"); len(query) > 0 {
|
|
|
|
token = strings.TrimSpace(query)
|
|
|
|
}
|
2024-02-18 07:51:27 +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-04-20 11:04:33 +00:00
|
|
|
rtk := c.Cookies(services.CookieRefreshKey)
|
2024-05-17 12:14:20 +00:00
|
|
|
if ctx, perms, atk, rtk, err := services.Authenticate(token, rtk, 0); err == nil {
|
2024-02-20 13:46:15 +00:00
|
|
|
if atk != token {
|
2024-04-20 11:04:33 +00:00
|
|
|
services.SetJwtCookieSet(c, atk, rtk)
|
2024-02-18 07:51:27 +00:00
|
|
|
}
|
2024-05-17 09:13:11 +00:00
|
|
|
c.Locals("permissions", perms)
|
2024-05-17 12:14:20 +00:00
|
|
|
c.Locals("principal", ctx.Account)
|
2024-02-20 13:46:15 +00:00
|
|
|
return nil
|
|
|
|
} else {
|
|
|
|
return err
|
2024-02-18 07:51:27 +00:00
|
|
|
}
|
|
|
|
}
|