41 lines
993 B
Go
41 lines
993 B
Go
package auth
|
||
|
||
import (
|
||
"net/http"
|
||
|
||
"github.com/JACKYMYPERSON/hldrCenter/util/auth"
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
func AuthMiddleware() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
sessionID := c.GetHeader("session_id")
|
||
if sessionID == "" { // 检查头是否为空
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"code": 401,
|
||
"msg": "未登录,请先登录",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
// 2. 验证会话有效性(调用你的ValidateSession函数)
|
||
session, err := auth.ValidateSession(sessionID) // 假设该函数已存在,返回*Session和error
|
||
if err != nil {
|
||
// 会话无效(过期/已注销等),返回401
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"code": 401,
|
||
"msg": "会话无效或已过期,请重新登录",
|
||
})
|
||
c.Abort()
|
||
return
|
||
}
|
||
|
||
// 3. 会话有效,将用户ID存入Gin上下文(供后续处理器使用)
|
||
// 后续handler可通过 c.Get("user_id") 获取
|
||
c.Set("user_id", session.UserID)
|
||
c.Next()
|
||
|
||
}
|
||
}
|