Skip to content

Commit

Permalink
used ParseWithClaims
Browse files Browse the repository at this point in the history
  • Loading branch information
iamitprakash committed Oct 4, 2024
1 parent 5f592d4 commit 2eda15f
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions utils/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,24 +34,28 @@ func GenerateToken(user *models.User) (string, error) {
func VerifyToken(tokenString string) (jwt.MapClaims, error) {
key := []byte(config.JwtSecret)

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Parsing the token

token, err := jwt.ParseWithClaims(tokenString, jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {

//validatint the algo
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, ErrUnexpectedSigningMethod
}
return key, nil
})

if err != nil {
if errors.Is(err, jwt.ErrTokenExpired) {
if errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet) {
return nil, ErrTokenExpired
}
return nil, err
}

claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
return nil, ErrInvalidToken
// Validating the token and casting the claims :P
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, nil
}

return claims, nil
}
return nil, ErrInvalidToken
}

0 comments on commit 2eda15f

Please sign in to comment.