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.
This commit is contained in:
zenfun
2025-12-05 00:16:47 +08:00
parent 5360cc6f1a
commit 8645b22b83
16 changed files with 618 additions and 229 deletions

View File

@@ -0,0 +1,63 @@
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()
}
}