Files
core/auth/jwtcodec.py

61 lines
1.8 KiB
Python
Raw Normal View History

2023-10-26 22:38:31 +02:00
from datetime import datetime, timezone
2023-10-30 22:00:55 +01:00
2023-10-26 22:38:31 +02:00
import jwt
2024-11-01 15:06:21 +03:00
from pydantic import BaseModel
2023-10-30 22:00:55 +01:00
2024-11-01 15:06:21 +03:00
from auth.exceptions import ExpiredToken, InvalidToken
2023-10-27 00:07:35 +03:00
from settings import JWT_ALGORITHM, JWT_SECRET_KEY
2024-11-01 15:06:21 +03:00
class TokenPayload(BaseModel):
user_id: str
username: str
exp: datetime
iat: datetime
iss: str
2023-10-26 22:38:31 +02:00
class JWTCodec:
2022-09-03 13:50:14 +03:00
@staticmethod
2024-11-01 15:06:21 +03:00
def encode(user, exp: datetime) -> str:
2022-09-03 13:50:14 +03:00
payload = {
2022-11-01 00:25:25 +03:00
"user_id": user.id,
"username": user.email or user.phone,
2022-11-23 17:09:35 +03:00
"exp": exp,
2022-11-24 17:31:52 +03:00
"iat": datetime.now(tz=timezone.utc),
2023-10-30 22:00:55 +01:00
"iss": "discours",
2022-09-03 13:50:14 +03:00
}
2022-10-23 12:33:28 +03:00
try:
2022-10-31 21:38:41 +03:00
return jwt.encode(payload, JWT_SECRET_KEY, JWT_ALGORITHM)
2022-10-23 12:33:28 +03:00
except Exception as e:
2023-10-30 22:00:55 +01:00
print("[auth.jwtcodec] JWT encode error %r" % e)
2022-09-03 13:50:14 +03:00
@staticmethod
2024-11-01 15:06:21 +03:00
def decode(token: str, verify_exp: bool = True):
2023-01-31 09:57:35 +03:00
r = None
2023-02-20 19:09:55 +03:00
payload = None
2022-10-23 12:33:28 +03:00
try:
payload = jwt.decode(
token,
key=JWT_SECRET_KEY,
2022-10-31 22:53:48 +03:00
options={
"verify_exp": verify_exp,
2022-11-01 00:05:10 +03:00
# "verify_signature": False
2022-10-31 22:53:48 +03:00
},
2022-10-23 12:33:28 +03:00
algorithms=[JWT_ALGORITHM],
2023-10-30 22:00:55 +01:00
issuer="discours",
2022-10-23 12:33:28 +03:00
)
2022-10-31 21:38:41 +03:00
r = TokenPayload(**payload)
# print('[auth.jwtcodec] debug token %r' % r)
2022-10-31 21:38:41 +03:00
return r
2022-11-14 00:38:06 +01:00
except jwt.InvalidIssuedAtError:
2023-10-30 22:00:55 +01:00
print("[auth.jwtcodec] invalid issued at: %r" % payload)
raise ExpiredToken("check token issued time")
2022-11-01 00:05:10 +03:00
except jwt.ExpiredSignatureError:
2023-10-30 22:00:55 +01:00
print("[auth.jwtcodec] expired signature %r" % payload)
raise ExpiredToken("check token lifetime")
2022-11-01 00:17:00 +03:00
except jwt.InvalidTokenError:
2023-10-30 22:00:55 +01:00
raise InvalidToken("token is not valid")
2022-11-01 00:17:00 +03:00
except jwt.InvalidSignatureError:
2023-10-30 22:00:55 +01:00
raise InvalidToken("token is not valid")