py.lib.aw_web_tools

Yohn Y. 2024-11-09 Parent:b9fd029be707

10:74f5377d83ab Go to Latest

py.lib.aw_web_tools/src/aw_web_tools/jwt_helper.py

. Исправление опечаток и неточностей

History
1 # coding: utf-8
3 import jwt
4 from datetime import datetime, timedelta
5 from typing import Optional
7 from . import Error
9 JWT_HASH_ALGO = 'HS512'
12 class JWTError(Error):
13 pass
16 class JWTAuthError(JWTError):
17 """\
18 Провалена проверка токена на допустимость по подписи, времени действия или прочее
19 """
22 class JWTHelper(object):
23 def __init__(self, key: str):
24 self.key = key
26 def encode(self, data: dict, timeout: Optional[int] = None) -> str:
27 if timeout is not None:
28 data['exp'] = datetime.utcnow() + timedelta(seconds=timeout)
30 return jwt.encode(data, key=self.key, algorithm=JWT_HASH_ALGO)
32 def decode(self, token: str, check_timeout: bool = False) -> dict:
33 opts = {
34 'algorithms': [JWT_HASH_ALGO, ]
35 }
37 if check_timeout:
38 opts['options'] = {'require': {'exp'}}
40 if token is None:
41 raise JWTAuthError('Ключ отсутствует')
42 else:
43 token = token.encode('utf-8')
45 try:
46 return jwt.decode(jwt=token, key=self.key, **opts)
48 except (jwt.InvalidIssuerError, jwt.InvalidSignatureError, jwt.ExpiredSignatureError) as e:
49 raise JWTAuthError(str(e))
51 except jwt.PyJWTError as e:
52 raise JWTError(f'{type(e).__name__}: {e}')
54 @classmethod
55 def make_fabric(cls, key: str):
56 def f():
57 return cls(key=key)
59 return f