向宁 b5df6445e5 refactor: commit all pending file_system changes
- 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
2026-05-17 22:20:02 +08:00

81 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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()
}
}