add jwt creating and parsing

This commit is contained in:
2025-12-18 10:48:27 +02:00
parent 3b74f5c43d
commit 597000f222
4 changed files with 105 additions and 0 deletions

49
internal/jwt/service.go Normal file
View File

@@ -0,0 +1,49 @@
package jwt
import (
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
type Service struct {
signer Signer
expiry time.Duration
}
func NewService(signer Signer, exp time.Duration) *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) {
jti := uuid.NewString()
claims := jwt.MapClaims{
"sub": userID,
"jti": jti,
"exp": time.Now().Add(s.expiry).Unix(),
"iat": time.Now().Unix(),
}
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) {
claims, err := s.signer.Verify(token)
if err != nil {
return 0, "", err
}
sub := int(claims.(jwt.MapClaims)["sub"].(float64))
jti := claims.(jwt.MapClaims)["jti"].(string)
return sub, jti, nil
}