- Restructure handlers into file_commands/file_queries/file_handlers - Add gRPC auth client, JWT middleware, rate limiting, request ID - Add common utilities: logger, sanitizer, s3_errors - Add unit tests for config, mediator, auth, request_id, sanitize - Add proto definitions and generated code - Remove old web UI pages - Add .dockerignore and .env.example
81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
package middleware
|
||
|
||
import (
|
||
"net/http"
|
||
"rag/file-system/internal/infrastructure/grpc"
|
||
"strings"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
const (
|
||
HeaderAuthorization = "Authorization"
|
||
BearerPrefix = "Bearer "
|
||
|
||
ContextKeyUserID = "user_id"
|
||
ContextKeyUsername = "username"
|
||
ContextKeyEmail = "email"
|
||
ContextKeyRoles = "roles"
|
||
ContextKeyPermissions = "permissions"
|
||
)
|
||
|
||
func JWTAuthMiddleware(authClient *grpc.AuthClient) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
authHeader := c.GetHeader(HeaderAuthorization)
|
||
if authHeader == "" {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"code": http.StatusUnauthorized,
|
||
"message": "未授权:请提供 Bearer Token",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
if !strings.HasPrefix(authHeader, BearerPrefix) {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"code": http.StatusUnauthorized,
|
||
"message": "未授权:Token 格式错误,需要 Bearer <token>",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
token := strings.TrimPrefix(authHeader, BearerPrefix)
|
||
if token == "" {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"code": http.StatusUnauthorized,
|
||
"message": "未授权:Token 不能为空",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
info, err := authClient.ValidateToken(c.Request.Context(), token)
|
||
if err != nil {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"code": http.StatusUnauthorized,
|
||
"message": "Token 验证失败",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
if !info.Valid {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"code": http.StatusUnauthorized,
|
||
"message": "Token 无效或已过期",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
c.Set(ContextKeyUserID, info.UserId)
|
||
c.Set(ContextKeyUsername, info.Username)
|
||
c.Set(ContextKeyEmail, info.Email)
|
||
c.Set(ContextKeyRoles, info.Roles)
|
||
c.Set(ContextKeyPermissions, info.Permissions)
|
||
|
||
c.Next()
|
||
}
|
||
}
|