项目初始化

This commit is contained in:
2026-01-13 17:00:49 +08:00
commit d2352318f4
27 changed files with 4343 additions and 0 deletions

View File

@@ -0,0 +1,76 @@
package middleware
import (
"FileRelay/internal/auth"
"FileRelay/internal/config"
"FileRelay/internal/model"
"FileRelay/internal/service"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func AdminAuth() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Authorization header required"))
c.Abort()
return
}
parts := strings.SplitN(authHeader, " ", 2)
if !(len(parts) == 2 && parts[0] == "Bearer") {
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Invalid authorization format"))
c.Abort()
return
}
claims, err := auth.ParseToken(parts[1])
if err != nil {
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Invalid or expired token"))
c.Abort()
return
}
c.Set("admin_id", claims.AdminID)
c.Next()
}
}
func APITokenAuth(requiredScope string) gin.HandlerFunc {
tokenService := service.NewTokenService()
return func(c *gin.Context) {
if !config.GlobalConfig.APIToken.Enabled {
c.JSON(http.StatusForbidden, model.ErrorResponse(model.CodeForbidden, "API Token is disabled"))
c.Abort()
return
}
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Authorization header required"))
c.Abort()
return
}
parts := strings.SplitN(authHeader, " ", 2)
if !(len(parts) == 2 && parts[0] == "Bearer") {
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Invalid authorization format"))
c.Abort()
return
}
token, err := tokenService.ValidateToken(parts[1], requiredScope)
if err != nil {
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, err.Error()))
c.Abort()
return
}
c.Set("token_id", token.ID)
c.Set("token_scope", token.Scope)
c.Next()
}
}