core/auth/jwtcodec.py

53 lines
1.8 KiB
Python
Raw Normal View History

from datetime import datetime
2022-10-31 21:05:10 +00:00
import time
import jwt
2022-10-31 21:17:00 +00:00
from base.exceptions import ExpiredToken, InvalidToken
2022-10-31 18:38:41 +00:00
from validations.auth import TokenPayload
from settings import JWT_ALGORITHM, JWT_SECRET_KEY
class JWTCodec:
2022-09-03 10:50:14 +00:00
@staticmethod
2022-10-31 18:38:41 +00:00
def encode(user_id: int, exp: datetime) -> str:
2022-10-31 21:17:00 +00:00
issued = int(time.mktime(datetime.now().timetuple()))
print('[jwtcodec] issued at %r' % issued)
expires = time.mktime(exp.timetuple())
print('[jwtcodec] expires at %r' % expires)
2022-09-03 10:50:14 +00:00
payload = {
2022-10-31 18:38:41 +00:00
"user_id": user_id,
# "user_email": user.email, # less secure
# "device": device, # no use cases
2022-10-31 21:17:00 +00:00
"exp": expires,
"iat": issued,
2022-10-31 21:05:10 +00:00
"iss": "discours"
2022-09-03 10:50:14 +00:00
}
2022-10-23 09:33:28 +00:00
try:
2022-10-31 18:38:41 +00:00
return jwt.encode(payload, JWT_SECRET_KEY, JWT_ALGORITHM)
2022-10-23 09:33:28 +00:00
except Exception as e:
print('[jwtcodec] JWT encode error %r' % e)
2022-09-03 10:50:14 +00:00
@staticmethod
def decode(token: str, verify_exp: bool = True) -> TokenPayload:
2022-10-23 09:33:28 +00:00
try:
payload = jwt.decode(
token,
key=JWT_SECRET_KEY,
2022-10-31 19:53:48 +00:00
options={
"verify_exp": verify_exp,
2022-10-31 21:05:10 +00:00
# "verify_signature": False
2022-10-31 19:53:48 +00:00
},
2022-10-23 09:33:28 +00:00
algorithms=[JWT_ALGORITHM],
2022-10-31 21:05:10 +00:00
issuer="discours"
2022-10-23 09:33:28 +00:00
)
2022-10-31 18:38:41 +00:00
r = TokenPayload(**payload)
print('[jwtcodec] debug payload %r' % r)
return r
2022-10-31 21:05:10 +00:00
except jwt.ExpiredSignatureError:
2022-10-31 21:17:00 +00:00
raise ExpiredToken('check token lifetime')
except jwt.InvalidTokenError:
raise InvalidToken('token is not valid')
except jwt.InvalidSignatureError:
raise InvalidToken('token is not valid')
except jwt.InvalidIssuedAtError:
raise ExpiredToken('check token issued time')