make functions more universal
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
@@ -9,41 +10,38 @@ import (
|
||||
|
||||
type Service struct {
|
||||
signer Signer
|
||||
expiry time.Duration
|
||||
}
|
||||
|
||||
func NewService(signer Signer, exp time.Duration) *Service {
|
||||
func NewService(signer Signer) *Service {
|
||||
return &Service{
|
||||
signer: signer,
|
||||
expiry: exp,
|
||||
}
|
||||
}
|
||||
|
||||
// Generate creates a new JWT token for a given user ID and
|
||||
// returns the token string along with its JTI(JWT IDentifier).
|
||||
func (s *Service) Generate(userID int) (string, string, error) {
|
||||
func (s *Service) Generate(ttl time.Duration, extraClaims jwt.MapClaims) (string, string, error) {
|
||||
jti := uuid.NewString()
|
||||
|
||||
claims := jwt.MapClaims{
|
||||
"sub": userID,
|
||||
"jti": jti,
|
||||
"exp": time.Now().Add(s.expiry).Unix(),
|
||||
"exp": time.Now().Add(ttl).Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
}
|
||||
maps.Copy(claims, extraClaims)
|
||||
|
||||
token, err := s.signer.Sign(claims)
|
||||
return token, jti, err
|
||||
}
|
||||
|
||||
// Validate verifies the JWT token and extracts the user ID and JTI(JWT IDentifier).
|
||||
func (s *Service) Validate(token string) (int, string, error) {
|
||||
// Validate verifies the JWT token and extracts the claims and JTI(JWT IDentifier).
|
||||
func (s *Service) Validate(token string) (jwt.MapClaims, string, error) {
|
||||
claims, err := s.signer.Verify(token)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
sub := int(claims.(jwt.MapClaims)["sub"].(float64))
|
||||
jti := claims.(jwt.MapClaims)["jti"].(string)
|
||||
|
||||
return sub, jti, nil
|
||||
return claims.(jwt.MapClaims), jti, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user