2024-02-01 15:26:17 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2024-03-20 12:57:21 +00:00
|
|
|
"git.solsynth.dev/hydrogen/interactive/pkg/services"
|
2024-02-01 15:26:17 +00:00
|
|
|
"github.com/gofiber/fiber/v2"
|
2024-02-21 14:58:51 +00:00
|
|
|
"strings"
|
2024-02-01 15:26:17 +00:00
|
|
|
)
|
|
|
|
|
2024-02-21 14:58:51 +00:00
|
|
|
func authMiddleware(c *fiber.Ctx) error {
|
|
|
|
var token string
|
2024-05-04 14:22:58 +00:00
|
|
|
if cookie := c.Cookies(services.CookieAccessKey); len(cookie) > 0 {
|
2024-02-21 14:58:51 +00:00
|
|
|
token = cookie
|
|
|
|
}
|
|
|
|
if header := c.Get(fiber.HeaderAuthorization); len(header) > 0 {
|
|
|
|
tk := strings.Replace(header, "Bearer", "", 1)
|
|
|
|
token = strings.TrimSpace(tk)
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Locals("token", token)
|
|
|
|
|
|
|
|
if err := authFunc(c); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-02-01 15:26:17 +00:00
|
|
|
|
2024-02-21 14:58:51 +00:00
|
|
|
return c.Next()
|
|
|
|
}
|
2024-02-01 15:26:17 +00:00
|
|
|
|
2024-02-21 14:58:51 +00:00
|
|
|
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-02-01 15:26:17 +00:00
|
|
|
}
|
2024-02-21 14:58:51 +00:00
|
|
|
}
|
2024-02-01 15:26:17 +00:00
|
|
|
|
2024-05-04 14:22:58 +00:00
|
|
|
rtk := c.Cookies(services.CookieRefreshKey)
|
2024-02-21 14:58:51 +00:00
|
|
|
if user, atk, rtk, err := services.Authenticate(token, rtk); err == nil {
|
|
|
|
if atk != token {
|
2024-05-04 14:22:58 +00:00
|
|
|
services.SetJwtCookieSet(c, atk, rtk)
|
2024-02-21 14:58:51 +00:00
|
|
|
}
|
2024-02-01 15:26:17 +00:00
|
|
|
c.Locals("principal", user)
|
2024-02-21 14:58:51 +00:00
|
|
|
return nil
|
|
|
|
} else {
|
2024-03-17 15:13:44 +00:00
|
|
|
return fiber.NewError(fiber.StatusUnauthorized, err.Error())
|
2024-02-21 14:58:51 +00:00
|
|
|
}
|
|
|
|
}
|