Files
TaskPool/internal/middleware/auth.go
T
2025-12-20 13:30:08 +08:00

54 lines
1.3 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 (
"baihu/internal/constant"
"baihu/internal/services"
"baihu/internal/utils"
"github.com/gin-gonic/gin"
)
// AuthRequired 认证中间件
func AuthRequired(settingsService *services.SettingsService) gin.HandlerFunc {
return func(c *gin.Context) {
token, err := c.Cookie(constant.CookieName)
if err != nil || token == "" {
utils.Unauthorized(c, "请先登录")
c.Abort()
return
}
// 获取 JWT Secret
jwtSecret := settingsService.Get(constant.SectionSystem, constant.KeyJWTSecret)
if jwtSecret == "" {
utils.Unauthorized(c, "系统配置错误")
c.Abort()
return
}
// 验证 token
userID, username, err := utils.ParseToken(token, jwtSecret)
if err != nil {
utils.Unauthorized(c, "登录已过期,请重新登录")
c.Abort()
return
}
// 将用户信息存入上下文
c.Set("userID", userID)
c.Set("username", username)
c.Next()
}
}
// SetAuthCookie 设置认证 CookieexpireDays 为过期天数
func SetAuthCookie(c *gin.Context, token string, expireDays int) {
maxAge := 86400 * expireDays
c.SetCookie(constant.CookieName, token, maxAge, "/", "", false, true)
}
// ClearAuthCookie 清除认证 Cookie
func ClearAuthCookie(c *gin.Context) {
c.SetCookie(constant.CookieName, "", -1, "/", "", false, true)
}