leaf-library-3/internal/api/http/middleware/auth.go

91 lines
1.9 KiB
Go
Raw Permalink Normal View History

2024-12-05 17:44:29 +00:00
package middleware
import (
2024-12-10 10:22:14 +00:00
"leafdev.top/Leaf/leaf-library-3/internal/pkg/response"
2024-12-05 17:44:29 +00:00
"net/http"
"slices"
"strings"
2024-12-10 10:22:14 +00:00
"leafdev.top/Leaf/leaf-library-3/internal/constants"
authType "leafdev.top/Leaf/leaf-library-3/internal/dto/user"
"leafdev.top/Leaf/leaf-library-3/internal/errs"
2024-12-06 15:38:22 +00:00
"github.com/gofiber/fiber/v2"
2024-12-10 10:22:14 +00:00
"leafdev.top/Leaf/leaf-library-3/internal/base/conf"
authService "leafdev.top/Leaf/leaf-library-3/internal/services/auth"
2024-12-05 17:44:29 +00:00
)
type Auth struct {
config *conf.Config
2024-12-06 15:38:22 +00:00
authService *authService.Service
2024-12-05 17:44:29 +00:00
}
var audienceLength int
2024-12-06 15:38:22 +00:00
func NewAuth(config *conf.Config, authService *authService.Service) *Auth {
2024-12-05 17:44:29 +00:00
audienceLength = len(config.App.AllowedAudiences)
return &Auth{
config,
authService,
}
}
func (a *Auth) Handler() fiber.Handler {
return func(c *fiber.Ctx) error {
2024-12-10 10:22:14 +00:00
var r = response.Ctx(c)
2024-12-05 17:44:29 +00:00
var err error
2024-12-06 15:38:22 +00:00
var token = new(authType.User)
2024-12-05 17:44:29 +00:00
if a.config.Debug.Enabled {
2024-12-06 15:38:22 +00:00
token, err = a.authService.AuthFromToken(constants.JwtTokenTypeAccessToken, "")
2024-12-05 17:44:29 +00:00
if err != nil {
return r.Error(err).Send()
}
2024-12-06 15:38:22 +00:00
c.Locals(constants.AuthMiddlewareKey, token)
2024-12-05 17:44:29 +00:00
return c.Next()
}
2024-12-06 15:38:22 +00:00
authorization := c.Get(constants.AuthHeader)
2024-12-05 17:44:29 +00:00
2024-12-10 10:45:46 +00:00
r.Status(http.StatusUnauthorized)
2024-12-05 17:44:29 +00:00
if authorization == "" {
2024-12-06 15:38:22 +00:00
return r.Error(errs.JWTFormatError).Send()
2024-12-05 17:44:29 +00:00
}
authSplit := strings.Split(authorization, " ")
if len(authSplit) != 2 {
2024-12-06 15:38:22 +00:00
return r.Error(errs.JWTFormatError).Send()
2024-12-05 17:44:29 +00:00
}
2024-12-06 15:38:22 +00:00
if authSplit[0] != constants.AuthPrefix {
return r.Error(errs.NotBearerType).Send()
2024-12-05 17:44:29 +00:00
}
2024-12-06 15:38:22 +00:00
token, err = a.authService.AuthFromToken(constants.JwtTokenTypeIDToken, authSplit[1])
2024-12-05 17:44:29 +00:00
if err != nil {
2024-12-10 10:45:46 +00:00
return r.Error(err).Send()
2024-12-05 17:44:29 +00:00
}
if token == nil {
2024-12-10 10:45:46 +00:00
return r.Error(err).Send()
2024-12-05 17:44:29 +00:00
}
if audienceLength > 0 {
// 检测 aud
if !slices.Contains(a.config.App.AllowedAudiences, token.Token.Aud) {
2024-12-06 15:38:22 +00:00
return r.Error(errs.NotValidToken).Send()
2024-12-05 17:44:29 +00:00
}
}
2024-12-06 15:38:22 +00:00
c.Locals(constants.AuthMiddlewareKey, token)
2024-12-05 17:44:29 +00:00
return c.Next()
}
}