Last active
May 22, 2021 10:32
-
-
Save dipeshhkc/7e3e5c62974b25421f6410e7c4181d7b 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
package middleware | |
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 := handler.ValidateToken(tokenString); err != nil { | |
fmt.Println("token", tokenString, err.Error()) | |
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"]) | |
fmt.Println("during authorization", 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