py.lib

Yohn Y. 2022-08-05 Child:84b54a8a6d4c

31:4186c3b229fa Go to Latest

py.lib/webapp/jwt_util.py

+ Модуль работы с датаклассами и их наполнения из ORM + Утилиты Bottle + Утилиты JWT + Помошник в парсинге конфигурационных файлов

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