-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.py
37 lines (29 loc) · 1.37 KB
/
jwt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from datetime import datetime, timedelta, timezone
from uuid import UUID
from jose import JWTError, jwt
from msgspec import to_builtins
from app.domain.auth.schemas import Token, TokenResponse
from app.lib.settings import get_settings
from litestar.exceptions import NotAuthorizedException
settings = get_settings()
def decode_jwt_token(encoded_token: str) -> Token:
"""Decode JWT token and return ``sub`` value.
If the token is invalid or expired (i.e. the value stored under the exp key is in the past)
an exception is raised.
"""
try:
payload = jwt.decode(token=encoded_token, key=settings.JWT_SECRET, algorithms=[settings.ALGORITHM])
return Token(**payload)
except JWTError as e:
raise NotAuthorizedException("Invalid token") from e
def encode_jwt_token(user_id: UUID, login: str, expiration: int = settings.DEFAULT_TOKEN_TTL_SECONDS) -> TokenResponse:
"""Encode JWT token with expiration and a given user_id."""
expires_at = datetime.now(tz=timezone.utc) + timedelta(seconds=expiration)
token = Token(
exp=expires_at,
iat=datetime.now(tz=timezone.utc),
sub=user_id,
login=login,
)
token_encoded_str = jwt.encode(to_builtins(token), settings.JWT_SECRET, algorithm=settings.ALGORITHM)
return TokenResponse(access_token=token_encoded_str, expires_in=expiration, expires_at=expires_at)