feat(auth): Add login, register, session_info and api creation

This commit is contained in:
Björn Benouarets
2026-01-15 20:25:17 +01:00
commit 13d908420a
31 changed files with 1421 additions and 0 deletions

66
app/middlewares/auth.go Normal file
View File

@@ -0,0 +1,66 @@
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"
"github.com/gofiber/fiber/v2"
)
func AuthMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
// check if the endpoint is in the unprotected endpoints
if slices.Contains(config.CONFIG.UNPROTECTED_ENDPOINTS, c.Path()) {
return c.Next()
}
token := c.Get("Authorization")
if token == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
tokenParts := strings.Split(token, " ")
if len(tokenParts) != 2 {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
tokenPartType, tokenPartValue := tokenParts[0], tokenParts[1]
if tokenPartType != "Bearer" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
// Decode the token from base64 to string
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 {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
keyId, keyValue := tokenValueParts[0], tokenValueParts[1]
apiKey, err := repositories.GetApiKey(keyId)
if err != nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
if apiKey == nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
valid, err := utils.Verify(keyValue, apiKey.Key)
if err != nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
if !valid {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Unauthorized"})
}
c.Locals("key", keyId)
return c.Next()
}
}