完成全部后端和管理系统
This commit is contained in:
40
server/middleware/auth/auth.go
Normal file
40
server/middleware/auth/auth.go
Normal file
@@ -0,0 +1,40 @@
|
||||
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()
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package middleware
|
||||
package cors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -47,7 +47,7 @@ func CorsMiddleware(serverConfig *config.ServerConfig) gin.HandlerFunc {
|
||||
// 允许的方法(包含上传需要的POST)
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
|
||||
// 允许的头(包含上传可能用到的Content-Type)
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization, X-Requested-With")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization, X-Requested-With,session_id")
|
||||
// 允许携带凭证(如果前端需要)
|
||||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
// 预检请求缓存时间(24小时)
|
||||
Reference in New Issue
Block a user