Files
ai_dianshang/server/internal/middleware/auth.go
2025-11-17 14:11:46 +08:00

99 lines
2.0 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 (
"dianshang/pkg/jwt"
"dianshang/pkg/response"
"strings"
"github.com/gin-gonic/gin"
)
// AuthMiddleware JWT认证中间件
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" {
response.Unauthorized(c)
return
}
// 移除 "Bearer " 前缀
if strings.HasPrefix(token, "Bearer ") {
token = token[7:]
}
claims, err := jwt.ParseToken(token)
if err != nil {
response.Unauthorized(c)
return
}
// 将用户信息存储到上下文中
c.Set("user_id", claims.UserID)
c.Set("user_type", claims.UserType)
c.Next()
}
}
// AdminAuthMiddleware 管理员认证中间件
func AdminAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" {
response.Unauthorized(c)
return
}
// 移除 "Bearer " 前缀
if strings.HasPrefix(token, "Bearer ") {
token = token[7:]
}
// 开发环境支持模拟token
if strings.HasPrefix(token, "mock_admin_token_") {
// 模拟管理员用户信息
c.Set("user_id", uint(1))
c.Set("user_type", "admin")
c.Next()
return
}
claims, err := jwt.ParseToken(token)
if err != nil {
response.Unauthorized(c)
return
}
// 检查用户类型是否为管理员
if claims.UserType != "admin" {
response.Forbidden(c)
return
}
// 将用户信息存储到上下文中
c.Set("user_id", claims.UserID)
c.Set("user_type", claims.UserType)
c.Next()
}
}
// OptionalAuthMiddleware 可选认证中间件(不强制要求登录)
func OptionalAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token != "" {
// 移除 "Bearer " 前缀
if strings.HasPrefix(token, "Bearer ") {
token = token[7:]
}
claims, err := jwt.ParseToken(token)
if err == nil {
// 将用户信息存储到上下文中
c.Set("user_id", claims.UserID)
c.Set("user_type", claims.UserType)
}
}
c.Next()
}
}