2025-12-20 09:30:16 +08:00
|
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"baihu/internal/constant"
|
|
|
|
|
|
"baihu/internal/utils"
|
|
|
|
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// AuthRequired 认证中间件
|
2025-12-21 10:23:25 +08:00
|
|
|
|
func AuthRequired() gin.HandlerFunc {
|
2025-12-20 09:30:16 +08:00
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
|
|
token, err := c.Cookie(constant.CookieName)
|
|
|
|
|
|
if err != nil || token == "" {
|
|
|
|
|
|
utils.Unauthorized(c, "请先登录")
|
|
|
|
|
|
c.Abort()
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 验证 token
|
2025-12-21 10:23:25 +08:00
|
|
|
|
userID, username, err := utils.ParseToken(token, constant.Secret)
|
2025-12-20 09:30:16 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
utils.Unauthorized(c, "登录已过期,请重新登录")
|
|
|
|
|
|
c.Abort()
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 将用户信息存入上下文
|
|
|
|
|
|
c.Set("userID", userID)
|
|
|
|
|
|
c.Set("username", username)
|
|
|
|
|
|
c.Next()
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-20 13:30:08 +08:00
|
|
|
|
// SetAuthCookie 设置认证 Cookie,expireDays 为过期天数
|
|
|
|
|
|
func SetAuthCookie(c *gin.Context, token string, expireDays int) {
|
|
|
|
|
|
maxAge := 86400 * expireDays
|
|
|
|
|
|
c.SetCookie(constant.CookieName, token, maxAge, "/", "", false, true)
|
2025-12-20 09:30:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// ClearAuthCookie 清除认证 Cookie
|
|
|
|
|
|
func ClearAuthCookie(c *gin.Context) {
|
|
|
|
|
|
c.SetCookie(constant.CookieName, "", -1, "/", "", false, true)
|
|
|
|
|
|
}
|