service_man/api/infrastructure/auth/jwt_processor.py

44 lines
1.7 KiB
Python
Raw Normal View History

2024-04-02 22:33:15 +03:00
from datetime import timedelta
from uuid import UUID
from jose import JWTError
from jose.jwt import decode, encode
from api.application.protocols.date_time import DateTimeProvider
from api.application.protocols.jwt import JwtTokenProcessor
2024-04-08 17:32:50 +03:00
from api.domain.user.error import UserInvalidCredentialsError
2024-04-10 00:33:31 +03:00
from api.domain.user.model import UserEmail, UserId
2024-04-02 22:33:15 +03:00
from api.infrastructure.auth.jwt_settings import JwtSettings
class JoseJwtTokenProcessor(JwtTokenProcessor):
2024-04-08 23:55:30 +03:00
def __init__(self, jwt_options: JwtSettings, date_time_provider: DateTimeProvider) -> None:
2024-04-02 22:33:15 +03:00
self.jwt_options = jwt_options
self.date_time_provider = date_time_provider
2024-04-10 00:33:31 +03:00
def generate_token(self, user_id: UserId, user_email: UserEmail) -> str:
2024-04-02 22:33:15 +03:00
issued_at = self.date_time_provider.get_current_time()
2024-04-08 00:31:15 +03:00
expiration_time = issued_at + timedelta(minutes=self.jwt_options.expires_in)
2024-04-02 22:33:15 +03:00
claims = {
"iat": issued_at,
"exp": expiration_time,
"sub": str(user_id.value),
2024-04-10 00:33:31 +03:00
"email": user_email.value,
2024-04-02 22:33:15 +03:00
}
return encode(claims, self.jwt_options.secret, self.jwt_options.algorithm)
2024-04-10 00:33:31 +03:00
def validate_token(self, token: str) -> tuple[UserId, UserEmail] | None:
2024-04-02 22:33:15 +03:00
try:
2024-04-08 23:55:30 +03:00
payload = decode(token, self.jwt_options.secret, [self.jwt_options.algorithm])
2024-04-10 00:33:31 +03:00
return UserId(UUID(payload["sub"])), UserEmail(payload["email"])
2024-04-02 22:33:15 +03:00
except (JWTError, ValueError, KeyError):
return None
2024-04-08 00:31:15 +03:00
def refresh_token(self, token: str) -> str:
2024-04-10 00:33:31 +03:00
token_data = self.validate_token(token)
if token_data is None:
2024-04-08 17:32:50 +03:00
raise UserInvalidCredentialsError("invalid token")
2024-04-10 00:33:31 +03:00
return self.generate_token(token_data[0], token_data[1])