72 lines
2.7 KiB
Go
72 lines
2.7 KiB
Go
package middlewares
|
|
|
|
import (
|
|
"slices"
|
|
"strings"
|
|
|
|
"git.secnex.io/secnex/masterlog"
|
|
"git.secnex.io/secnex/oauth2-api/config"
|
|
"git.secnex.io/secnex/oauth2-api/repositories"
|
|
"git.secnex.io/secnex/oauth2-api/utils"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func AuthMiddleware() fiber.Handler {
|
|
return func(c *fiber.Ctx) error {
|
|
tokenEndpoint := "/token"
|
|
if slices.Contains(config.CONFIG.UnprotectedEndpoints, c.Path()) || c.Path() == tokenEndpoint {
|
|
masterlog.Debug("Unprotected endpoint", map[string]interface{}{"path": c.Path()})
|
|
return c.Next()
|
|
}
|
|
|
|
authHeader := c.Get("Authorization")
|
|
if authHeader == "" {
|
|
masterlog.Debug("No token provided", map[string]interface{}{"path": c.Path(), "authorization": c.Get("Authorization")})
|
|
return utils.NewHTTPResponse(fiber.StatusUnauthorized, &fiber.Map{"message": "Unauthorized"}, "", nil, nil).Send(c)
|
|
}
|
|
|
|
tokenParts := strings.Split(authHeader, " ")
|
|
if len(tokenParts) != 2 {
|
|
masterlog.Debug("Invalid token parts", map[string]interface{}{"token_parts": tokenParts})
|
|
return utils.NewHTTPResponse(fiber.StatusUnauthorized, &fiber.Map{"message": "Unauthorized"}, "", nil, nil).Send(c)
|
|
}
|
|
|
|
tokenPartType := tokenParts[0]
|
|
tokenString := tokenParts[1]
|
|
|
|
if tokenPartType != "Bearer" {
|
|
masterlog.Debug("Invalid token type", map[string]interface{}{"token_type": tokenPartType})
|
|
return utils.NewHTTPResponse(fiber.StatusUnauthorized, &fiber.Map{"message": "Unauthorized"}, "", nil, nil).Send(c)
|
|
}
|
|
|
|
if tokenString == "" {
|
|
masterlog.Debug("Empty token string", map[string]interface{}{})
|
|
return utils.NewHTTPResponse(fiber.StatusUnauthorized, &fiber.Map{"message": "Unauthorized"}, "", nil, nil).Send(c)
|
|
}
|
|
|
|
masterlog.Debug("Token string", map[string]interface{}{"token_string": tokenString})
|
|
|
|
// Validate jwt token and get claims
|
|
claims, err := jwt.ParseWithClaims(tokenString, &jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(config.CONFIG.JwtSecret), nil
|
|
})
|
|
if err != nil {
|
|
masterlog.Debug("Invalid token", map[string]interface{}{"error": err.Error(), "token_string": tokenString})
|
|
return utils.NewHTTPResponse(fiber.StatusUnauthorized, &fiber.Map{"message": "Unauthorized"}, "", nil, nil).Send(c)
|
|
}
|
|
|
|
claimsMap := claims.Claims.(*jwt.MapClaims)
|
|
sessionID := (*claimsMap)["sub"].(string)
|
|
|
|
session := repositories.GetSessionCache(sessionID)
|
|
if session == nil {
|
|
masterlog.Debug("Session not found", map[string]interface{}{"session_id": sessionID})
|
|
return utils.NewHTTPResponse(fiber.StatusUnauthorized, &fiber.Map{"message": "Unauthorized"}, "", nil, nil).Send(c)
|
|
}
|
|
|
|
c.Locals("user", session.UserID.String())
|
|
return c.Next()
|
|
}
|
|
}
|