make functions more universal

This commit is contained in:
2025-12-18 11:24:34 +02:00
parent 6f4657caff
commit 16b6b292c6

View File

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