package middlewares import ( "errors" "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt" "github.com/han-joker/moo-layout/api/moo/confm" "github.com/han-joker/moo-layout/api/moo/dbm" "github.com/han-joker/moo-layout/api/moo/logm" "github.com/han-joker/moo-layout/api/panel/models" "github.com/han-joker/moo-layout/api/tables" "net/http" "strconv" "strings" ) func JwtToken(c *gin.Context) { // before request header := models.UserJwtTokenHeader{} if err := c.ShouldBindHeader(&header); err != nil { logm.Get().Info(err.Error()) c.JSON(http.StatusForbidden, gin.H{ "error": err.Error(), }) c.Abort() return } tokenString := strings.Replace(header.Authorization, "Bearer ", "", 1) token, err := jwt.ParseWithClaims(tokenString, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) { return []byte(confm.Get().String("app.signingKey")), nil }) if err != nil { logm.Get().Info(err.Error()) c.JSON(http.StatusForbidden, gin.H{ "error": err.Error(), }) c.Abort() return } claims, ok := token.Claims.(*jwt.StandardClaims) if !ok { err := errors.New("token claim type error") logm.Get().Info(err.Error()) c.JSON(http.StatusForbidden, gin.H{ "error": err.Error(), }) c.Abort() return } if !token.Valid { err := errors.New("token valid error") logm.Get().Info(err.Error()) c.JSON(http.StatusForbidden, gin.H{ "error": err.Error(), }) c.Abort() return } id, err := strconv.ParseUint(claims.Audience, 10, 0) if err != nil { logm.Get().Info(err.Error()) c.JSON(http.StatusForbidden, gin.H{ "error": err.Error(), }) c.Abort() return } user := tables.User{} if err := dbm.Get().Where("id=?", id).First(&user).Error; err != nil { logm.Get().Info(err.Error()) c.JSON(http.StatusForbidden, gin.H{ "error": err.Error(), }) c.Abort() return } if user.JWTToken != tokenString { err := errors.New("token error") logm.Get().Info(err.Error()) c.JSON(http.StatusForbidden, gin.H{ "error": err.Error(), }) c.Abort() return } c.Set("user", user) c.Next() }