Files
core/auth/jwtcodec.py

52 lines
1.8 KiB
Python
Raw Normal View History

from datetime import datetime
import jwt
2022-11-01 00:17:00 +03:00
from base.exceptions import ExpiredToken, InvalidToken
2022-11-01 00:25:25 +03:00
from validations.auth import TokenPayload, AuthInput
from settings import JWT_ALGORITHM, JWT_SECRET_KEY
class JWTCodec:
2022-09-03 13:50:14 +03:00
@staticmethod
2022-11-01 00:25:25 +03:00
def encode(user: AuthInput, exp: datetime) -> str:
2022-11-01 00:27:31 +03:00
issued = int(datetime.now().timestamp())
2022-11-01 00:17:00 +03:00
print('[jwtcodec] issued at %r' % issued)
2022-11-01 00:27:31 +03:00
expires = int(exp.timestamp())
2022-11-01 00:17:00 +03:00
print('[jwtcodec] expires at %r' % expires)
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,
# "device": device, # no use cases
2022-11-01 00:17:00 +03:00
"exp": expires,
"iat": issued,
2022-11-01 00:05:10 +03: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:
print('[jwtcodec] JWT encode error %r' % e)
2022-09-03 13:50:14 +03:00
@staticmethod
def decode(token: str, verify_exp: bool = True) -> TokenPayload:
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],
2022-11-01 00:05:10 +03:00
issuer="discours"
2022-10-23 12:33:28 +03:00
)
2022-10-31 21:38:41 +03:00
r = TokenPayload(**payload)
print('[jwtcodec] debug payload %r' % r)
return r
2022-11-14 00:38:06 +01:00
except jwt.InvalidIssuedAtError:
raise ExpiredToken('check token issued time')
2022-11-01 00:05:10 +03:00
except jwt.ExpiredSignatureError:
2022-11-01 00:17:00 +03:00
raise ExpiredToken('check token lifetime')
except jwt.InvalidTokenError:
raise InvalidToken('token is not valid')
except jwt.InvalidSignatureError:
raise InvalidToken('token is not valid')