GoTest/internal/middleware/auth.go
2025-11-29 03:27:19 +08:00

126 lines
2.6 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"
"yinli-api/pkg/auth"
"github.com/gin-gonic/gin"
)
// AuthMiddleware JWT认证中间件
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"code": 401,
"message": "缺少授权头",
})
c.Abort()
return
}
token, err := auth.ExtractTokenFromHeader(authHeader)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{
"code": 401,
"message": "无效的授权头格式",
})
c.Abort()
return
}
claims, err := auth.ValidateToken(token)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{
"code": 401,
"message": "无效的令牌: " + err.Error(),
})
c.Abort()
return
}
// 将用户信息存储到上下文中
c.Set("user_id", claims.UserID)
c.Set("username", claims.Username)
c.Set("token", token)
c.Next()
}
}
// OptionalAuthMiddleware 可选的JWT认证中间件
func OptionalAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader != "" {
token, err := auth.ExtractTokenFromHeader(authHeader)
if err == nil {
claims, err := auth.ValidateToken(token)
if err == nil {
c.Set("user_id", claims.UserID)
c.Set("username", claims.Username)
c.Set("token", token)
}
}
}
c.Next()
}
}
// GetUserID 从上下文中获取用户ID
func GetUserID(c *gin.Context) (uint, bool) {
userID, exists := c.Get("user_id")
if !exists {
return 0, false
}
return userID.(uint), true
}
// GetUsername 从上下文中获取用户名
func GetUsername(c *gin.Context) (string, bool) {
username, exists := c.Get("username")
if !exists {
return "", false
}
return username.(string), true
}
// GetToken 从上下文中获取令牌
func GetToken(c *gin.Context) (string, bool) {
token, exists := c.Get("token")
if !exists {
return "", false
}
return token.(string), true
}
// AdminMiddleware 管理员权限中间件
func AdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
userID, exists := GetUserID(c)
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{
"code": 401,
"message": "未认证",
})
c.Abort()
return
}
// 这里可以添加管理员权限检查逻辑
// 例如检查用户角色或权限表
if userID != 1 { // 简单示例只有ID为1的用户是管理员
c.JSON(http.StatusForbidden, gin.H{
"code": 403,
"message": "权限不足",
})
c.Abort()
return
}
c.Next()
}
}