Files
login-api/app/middlewares/auth.go
2026-01-16 16:11:46 +01:00

76 lines
2.9 KiB
Go

package middlewares
import (
"encoding/base64"
"slices"
"strings"
"git.secnex.io/secnex/auth-api/config"
"git.secnex.io/secnex/auth-api/repositories"
"git.secnex.io/secnex/auth-api/utils"
"git.secnex.io/secnex/masterlog"
"github.com/gofiber/fiber/v2"
)
func AuthMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
if slices.Contains(config.CONFIG.UNPROTECTED_ENDPOINTS, c.Path()) {
masterlog.Debug("Unprotected endpoint", map[string]interface{}{"path": c.Path()})
return c.Next()
}
token := c.Get("Authorization")
if token == "" {
masterlog.Debug("No token provided", map[string]interface{}{"path": c.Path(), "authorization": c.Get("Authorization")})
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
tokenParts := strings.Split(token, " ")
if len(tokenParts) != 2 {
masterlog.Debug("Invalid token parts", map[string]interface{}{"token_parts": tokenParts})
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
tokenPartType, tokenPartValue := tokenParts[0], tokenParts[1]
if tokenPartType != "Bearer" {
masterlog.Debug("Invalid token type", map[string]interface{}{"token_type": tokenPartType})
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
tokenValue, err := base64.StdEncoding.DecodeString(tokenPartValue)
if err != nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
tokenValueString := string(tokenValue)
tokenValueParts := strings.Split(tokenValueString, ":")
if len(tokenValueParts) != 2 {
masterlog.Debug("Invalid API key format", map[string]interface{}{"token_value": tokenValueString})
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
keyId, keyValue := tokenValueParts[0], tokenValueParts[1]
apiKey, err := repositories.GetApiKey(keyId)
if err != nil {
masterlog.Debug("Error getting API key", map[string]interface{}{"error": err.Error(), "key_id": keyId})
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
if apiKey == nil {
masterlog.Debug("API key not found", map[string]interface{}{"key_id": keyId})
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
valid, err := utils.Verify(keyValue, apiKey.Key)
if err != nil {
masterlog.Debug("Error verifying API key", map[string]interface{}{"error": err.Error(), "key_id": keyId})
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
if !valid {
masterlog.Debug("Invalid API key", map[string]interface{}{"key_id": keyId})
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
c.Locals("key", keyId)
masterlog.Debug("API key verified successfully", map[string]interface{}{"key_id": keyId})
return c.Next()
}
}