- Replace `interface{}` with `any` type alias across all packages
- Use built-in `min()`/`max()` for parameter clamping
- Use `slices.SortFunc`, `slices.Min`, `slices.Max` for cleaner code
- Use `strings.Cut()` for simpler string parsing in auth middleware
- Use `errors.Is()` for proper error comparison in handlers
- Update dependencies: golang.org/x/image 0.37.0 -> 0.38.0
- Add Wire code generation guidelines to ARCHITECTURE.md
- Disable Go cache in CI build workflow
77 lines
1.5 KiB
Go
77 lines
1.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"carrot_bbs/internal/pkg/response"
|
|
"carrot_bbs/internal/service"
|
|
)
|
|
|
|
// Auth 认证中间件
|
|
func Auth(jwtService *service.JWTService) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
|
|
if authHeader == "" {
|
|
response.Unauthorized(c, "authorization header is required")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// 提取Token
|
|
prefix, token, found := strings.Cut(authHeader, " ")
|
|
if !found || prefix != "Bearer" {
|
|
response.Unauthorized(c, "invalid authorization header format")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// 验证Token
|
|
claims, err := jwtService.ParseToken(token)
|
|
if err != nil {
|
|
response.Unauthorized(c, "invalid token")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// 将用户信息存入上下文
|
|
c.Set("user_id", claims.UserID)
|
|
c.Set("username", claims.Username)
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// OptionalAuth 可选认证中间件
|
|
func OptionalAuth(jwtService *service.JWTService) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
// 提取Token
|
|
prefix, token, found := strings.Cut(authHeader, " ")
|
|
if !found || prefix != "Bearer" {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
// 验证Token
|
|
claims, err := jwtService.ParseToken(token)
|
|
if err != nil {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
// 将用户信息存入上下文
|
|
c.Set("user_id", claims.UserID)
|
|
c.Set("username", claims.Username)
|
|
|
|
c.Next()
|
|
}
|
|
}
|