This commit is contained in:
mubai
2023-12-23 22:32:52 +08:00
parent d85dbe915c
commit b48e53a637
151 changed files with 12451 additions and 1382 deletions

View File

@@ -0,0 +1,42 @@
package middleware
import (
"github.com/gin-gonic/gin"
"log"
"net/http"
)
// Cors 开启跨域请求
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin") //请求头部
if origin != "" {
//接收客户端发送的origin (重要!)
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
//服务器支持的所有跨域请求的方法
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
//允许跨域设置可以返回其他子段,可以自定义字段
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session, Content-Type")
// 允许浏览器(客户端)可以解析的头部 (重要)
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
//设置缓存时间
c.Header("Access-Control-Max-Age", "172800")
//允许客户端传递校验信息比如 cookie (重要)
c.Header("Access-Control-Allow-Credentials", "true")
}
//允许类型校验
if method == "OPTIONS" {
c.JSON(http.StatusOK, "ok!")
}
defer func() {
if err := recover(); err != nil {
log.Printf("Panic info is: %v\n", err)
}
}()
c.Next()
}
}

View File

@@ -0,0 +1,64 @@
package middleware
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"net/http"
"server/config"
"server/model/system"
)
/*
*/
// AuthToken 用户登录Token拦截
func AuthToken() gin.HandlerFunc {
return func(c *gin.Context) {
// 从请求头中获取token
authToken := c.Request.Header.Get("auth-token")
// 如果没有登录信息则直接清退
if authToken == "" {
c.JSON(http.StatusUnauthorized, gin.H{"status": "ok", "message": "用户未授权,请先登录."})
c.Abort()
return
}
// 解析token中的信息
uc, err := system.ParseToken(authToken)
// 从Redis中获取对应的token是否存在, 如果存在则刷新token
t := system.GetUserTokenById(uc.UserID)
// 如果 redis中获取的token为空则登录已过期需重新登录
if len(t) <= 0 {
c.JSON(http.StatusUnauthorized, gin.H{
"status": "ok",
"message": "身份验证信息已过期,请重新登录!!!",
})
c.Abort()
return
}
// 如果redis中存在对应token, 校验authToken是否与redis中的一致
if t != authToken {
// 如果不一致则证明authToken已经失效或在其他地方登录, 则需要重新登录
c.JSON(http.StatusUnauthorized, gin.H{
"status": "ok",
"message": "账号在其它设备登录,身份验证信息失效,请重新登录!!!",
})
c.Abort()
return
} else if err != nil && errors.Is(err, jwt.ErrTokenExpired) {
// 如果token已经过期,且redis中的token与authToken 相同则更新 token
// 生成新token
newToken, _ := system.GenToken(uc.UserID, uc.UserName)
// 将新token同步到redis中
_ = system.SaveUserToken(newToken, uc.UserID)
// 解析出新的 UserClaims
uc, _ = system.ParseToken(newToken)
c.Header("new-token", newToken)
}
// 将UserClaims存放到context中
c.Set(config.AuthUserClaims, uc)
c.Next()
}
}

View File

@@ -0,0 +1,15 @@
package middleware
import (
"encoding/xml"
"github.com/gin-gonic/gin"
)
func AddXmlHeader() gin.HandlerFunc {
return func(c *gin.Context) {
if c.NegotiateFormat(gin.MIMEXML, gin.MIMEJSON) == gin.MIMEXML {
_, _ = c.Writer.Write([]byte(xml.Header))
}
c.Next()
}
}