add jwt creating and parsing
This commit is contained in:
49
internal/jwt/service.go
Normal file
49
internal/jwt/service.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user