lavkach3
1from datetime import datetime, timedelta, UTC
2
3import jwt
4
5from core.db_config import config
6from core.exceptions import DecodeTokenException, ExpiredTokenException
7
8
9class TokenHelper:
10@staticmethod
11def encode(payload: dict, expire_period: int = 36000) -> str:
12token = jwt.encode(
13payload={
14**payload,
15"exp": datetime.now(UTC) + timedelta(seconds=expire_period),
16},
17key=config.JWT_SECRET_KEY,
18algorithm=config.JWT_ALGORITHM,
19)#.decode("utf8")
20return token
21
22@staticmethod
23def decode(token: str) -> dict:
24try:
25return jwt.decode(
26token,
27config.JWT_SECRET_KEY,
28config.JWT_ALGORITHM,
29)
30except jwt.exceptions.DecodeError:
31raise DecodeTokenException
32except jwt.exceptions.ExpiredSignatureError:
33raise ExpiredTokenException
34
35@staticmethod
36def decode_expired_token(token: str) -> dict:
37try:
38return jwt.decode(
39token,
40config.JWT_SECRET_KEY,
41config.JWT_ALGORITHM,
42options={"verify_exp": False},
43)
44except jwt.exceptions.DecodeError:
45raise DecodeTokenException
46