Initial backend repository commit.
Set up project files and add .gitignore to exclude local build/runtime artifacts. Made-with: Cursor
This commit is contained in:
95
internal/middleware/auth.go
Normal file
95
internal/middleware/auth.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"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")
|
||||
fmt.Printf("[DEBUG] Auth middleware: Authorization header = %q\n", authHeader)
|
||||
|
||||
if authHeader == "" {
|
||||
fmt.Printf("[DEBUG] Auth middleware: no Authorization header, returning 401\n")
|
||||
response.Unauthorized(c, "authorization header is required")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 提取Token
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
fmt.Printf("[DEBUG] Auth middleware: invalid Authorization header format\n")
|
||||
response.Unauthorized(c, "invalid authorization header format")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
token := parts[1]
|
||||
fmt.Printf("[DEBUG] Auth middleware: token = %q\n", token[:min(20, len(token))]+"...")
|
||||
|
||||
// 验证Token
|
||||
claims, err := jwtService.ParseToken(token)
|
||||
if err != nil {
|
||||
fmt.Printf("[DEBUG] Auth middleware: failed to parse token: %v\n", err)
|
||||
response.Unauthorized(c, "invalid token")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("[DEBUG] Auth middleware: parsed claims, user_id = %q, username = %q\n", claims.UserID, claims.Username)
|
||||
|
||||
// 将用户信息存入上下文
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("username", claims.Username)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// OptionalAuth 可选认证中间件
|
||||
func OptionalAuth(jwtService *service.JWTService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// 提取Token
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
token := parts[1]
|
||||
|
||||
// 验证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()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user