Last active
June 24, 2021 12:31
-
-
Save dipeshhkc/1316b7670d13a35a4ce96fd3348d60c2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//AuthorizeJWT -> to authorize JWT Token | |
func AuthorizeJWT() gin.HandlerFunc { | |
return func(ctx *gin.Context) { | |
const BearerSchema string = "Bearer " | |
authHeader := ctx.GetHeader("Authorization") | |
if authHeader == "" { | |
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ | |
"error": "No Authorization header found"}) | |
} | |
tokenString := authHeader[len(BearerSchema):] | |
if token, err := utils.ValidateToken(tokenString); err != nil { | |
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ | |
"error": "Not Valid Token"}) | |
} else { | |
if claims, ok := token.Claims.(jwt.MapClaims); !ok { | |
ctx.AbortWithStatus(http.StatusUnauthorized) | |
} else { | |
if token.Valid { | |
ctx.Set("userID", claims["userID"]) | |
} else { | |
ctx.AbortWithStatus(http.StatusUnauthorized) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment