Files
ez-api/internal/middleware/auth.go
zenfun 8645b22b83 feat(auth): implement master key authentication system with child key issuance
Add admin and master authentication layers with JWT support. Replace direct
key creation with hierarchical master/child key system. Update database
schema to support master accounts with configurable limits and epoch-based
key revocation. Add health check endpoint with system status monitoring.

BREAKING CHANGE: Removed direct POST /keys endpoint in favor of master-based
key issuance through /v1/tokens. Database migration requires dropping old User
table and creating Master table with new relationships.
2025-12-05 00:16:47 +08:00

64 lines
1.5 KiB
Go

package middleware
import (
"net/http"
"strings"
"github.com/ez-api/ez-api/internal/service"
"github.com/gin-gonic/gin"
)
func AdminAuthMiddleware(adminService *service.AdminService) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "authorization header required"})
c.Abort()
return
}
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header format"})
c.Abort()
return
}
if !adminService.ValidateToken(parts[1]) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid admin token"})
c.Abort()
return
}
c.Next()
}
}
func MasterAuthMiddleware(masterService *service.MasterService) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "authorization header required"})
c.Abort()
return
}
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header format"})
c.Abort()
return
}
master, err := masterService.ValidateMasterKey(parts[1])
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid master key"})
c.Abort()
return
}
c.Set("master", master)
c.Next()
}
}