py.lib

Yohn Y. 2022-08-27 Parent:84b54a8a6d4c

41:483727ff89c4 Go to Latest

py.lib/webapp/jwt_util.py

+ Возможность удалить cookie при формировании штатного ответа.

History
1 # coding: utf-8
3 import jwt
4 from datetime import datetime, timedelta
5 from typing import Optional
7 JWT_HASH_ALGO = 'HS512'
10 class JWTError(Exception):
11 pass
14 class JWTAuthError(JWTError):
15 """\
16 Провалена проверка токена на допустимость по подписи времени или прочее
17 """
20 class JWTHelper(object):
21 def __init__(self, key: str):
22 self.key = key
24 def encode(self, data: dict, timeout: Optional[int] = None) -> str:
25 if timeout is not None:
26 data['exp'] = datetime.utcnow() + timedelta(seconds=timeout)
28 return jwt.encode(data, key=self.key, algorithm=JWT_HASH_ALGO)
30 def decode(self, token: str, check_timeout: bool = False) -> dict:
31 opts = {
32 'algorithms': [JWT_HASH_ALGO, ]
33 }
35 if check_timeout:
36 opts['options'] = {'require': {'exp'}}
38 if token is None:
39 raise JWTAuthError('Ключ отсутствует')
40 else:
41 token = token.encode('utf-8')
43 try:
44 return jwt.decode(jwt=token, key=self.key, **opts)
46 except (jwt.InvalidIssuerError, jwt.InvalidSignatureError, jwt.ExpiredSignatureError) as e:
47 raise JWTAuthError(str(e))
49 except jwt.PyJWTError as e:
50 raise JWTError(f'{type(e).__name__}: {e}')
52 @classmethod
53 def make_cls_fabric(cls, key: str):
54 def f():
55 return cls(key=key)
57 return f