GoScrobble/internal/goscrobble/jwt.go

63 lines
1.3 KiB
Go
Raw Normal View History

2021-03-25 05:15:01 +00:00
package goscrobble
import (
2021-03-25 23:21:28 +00:00
"time"
2021-03-25 05:15:01 +00:00
"github.com/dgrijalva/jwt-go"
)
// JwtToken - Store token from .env
var JwtToken []byte
2021-03-25 23:21:28 +00:00
// JwtExpiry - Expiry in seconds
var JwtExpiry time.Duration
type CustomClaims struct {
Username string `json:"username"`
Email string `json:"email"`
2021-03-25 05:15:01 +00:00
jwt.StandardClaims
}
func generateJWTToken(user User) (string, error) {
atClaims := jwt.MapClaims{}
atClaims["sub"] = user.UUID
atClaims["username"] = user.Username
atClaims["email"] = user.Email
atClaims["iat"] = time.Now().Unix()
atClaims["exp"] = time.Now().Add(JwtExpiry).Unix()
at := jwt.NewWithClaims(jwt.SigningMethodHS512, atClaims)
token, err := at.SignedString(JwtToken)
if err != nil {
return "", err
}
return token, nil
}
2021-03-25 05:15:01 +00:00
// verifyToken - Verifies the JWT is valid
func verifyJWTToken(token string) (CustomClaims, error) {
2021-03-25 05:15:01 +00:00
// Initialize a new instance of `Claims`
claims := CustomClaims{}
_, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) {
2021-03-25 05:15:01 +00:00
return JwtToken, nil
})
// Verify Signature
2021-03-25 05:15:01 +00:00
if err != nil {
return claims, err
2021-03-25 05:15:01 +00:00
}
// Verify expiry
err = claims.Valid()
if err != nil {
return claims, err
2021-03-25 05:15:01 +00:00
}
return claims, err
}
func getClaims(token *jwt.Token) CustomClaims {
claims, _ := token.Claims.(CustomClaims)
return claims
2021-03-25 05:15:01 +00:00
}