1 Star 0 Fork 0

ichub / go-factroy2024

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
AuthMiddleware.go 1.05 KB
一键复制 编辑 原始数据 按行查看 历史
leijmdas 提交于 2024-02-01 12:27 . add
package middleware
import (
"github.com/gin-gonic/gin"
"gitee.com/ichub/go-factroy2024/common/dbcontent"
model2 "gitee.com/ichub/go-factroy2024/common/user/model"
"net/http"
"strings"
)
func AuthMiddleware() gin.HandlerFunc {
return func(ctx *gin.Context) {
tokenString := ctx.GetHeader("Authorization")
if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
ctx.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"})
ctx.Abort()
return
}
tokenString = tokenString[7:]
token, claims, err := dbcontent.ParseToken(tokenString)
if err != nil || !token.Valid {
ctx.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"})
ctx.Abort()
return
}
userId := claims.UserId
println("userID:", userId)
DB := dbcontent.GetDB()
var user model2.CmsUser
DB.First(&user, userId)
if user.ID == 0 {
ctx.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"})
ctx.Abort()
return
}
//用户存在将用户写入上下文
ctx.Set("shop-code", user)
ctx.Next()
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/ichub/go-factroy2024.git
git@gitee.com:ichub/go-factroy2024.git
ichub
go-factroy2024
go-factroy2024
v1.1.0

搜索帮助

344bd9b3 5694891 D2dac590 5694891