package middlewares import ( "fmt" "github.com/gin-gonic/gin" "hospital-admin-api/consts" "hospital-admin-api/global" "hospital-admin-api/utils" "net/http" "strconv" "strings" ) // Jwt jwt认证 func Jwt() gin.HandlerFunc { return func(c *gin.Context) { authorization := c.Request.Header.Get("Authorization") if authorization == "" || !strings.HasPrefix(authorization, "Bearer ") { c.JSON(http.StatusUnauthorized, gin.H{ "message": "请求未授权", "code": consts.TokenError, "data": "", }) c.Abort() return } // 去除Bearer authorization = authorization[7:] // 截取字符 // 检测是否存在黑名单 res, _ := global.Redis.Get(c, "jwt_black_"+authorization).Result() fmt.Println(res) if res != "" { c.JSON(http.StatusOK, gin.H{ "message": "token错误/过期", "code": consts.TokenError, "data": "", }) c.Abort() return } // 解析jwt t, err := utils.ParseJwt(authorization) if err != nil { c.JSON(http.StatusOK, gin.H{ "message": "token错误/过期", "code": consts.TokenError, "data": "", }) c.Abort() return } // 转换类型 userId, err := strconv.ParseInt(t.UserId, 10, 64) if err != nil { c.JSON(http.StatusOK, gin.H{ "message": "token错误", "code": consts.TokenError, "data": "", }) c.Abort() return } roleId, err := strconv.ParseInt(t.RoleId, 10, 64) if err != nil { c.JSON(http.StatusOK, gin.H{ "message": "token错误", "code": consts.TokenError, "data": "", }) c.Abort() return } deptId, err := strconv.ParseInt(t.DeptId, 10, 64) if err != nil { c.JSON(http.StatusOK, gin.H{ "message": "token错误", "code": consts.TokenError, "data": "", }) c.Abort() return } postId, err := strconv.ParseInt(t.PostId, 10, 64) if err != nil { c.JSON(http.StatusOK, gin.H{ "message": "token错误", "code": consts.TokenError, "data": "", }) c.Abort() return } c.Set("UserId", userId) // 用户id c.Set("RoleId", roleId) // 角色id c.Set("DeptId", deptId) // 部门id c.Set("PostId", postId) // 岗位id c.Next() } }