2018-04-25 20:52:36 +00:00
|
|
|
"""Identity policy for storing info in the jwt token.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2020-12-18 17:58:38 +00:00
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
from aiohttp import web
|
|
|
|
|
2018-04-25 20:52:36 +00:00
|
|
|
from .abc import AbstractIdentityPolicy
|
2018-05-21 19:07:14 +00:00
|
|
|
|
2018-04-25 20:52:36 +00:00
|
|
|
try:
|
|
|
|
import jwt
|
2020-12-18 17:58:38 +00:00
|
|
|
HAS_JWT = True
|
2018-04-25 20:52:36 +00:00
|
|
|
except ImportError: # pragma: no cover
|
2020-12-18 17:58:38 +00:00
|
|
|
HAS_JWT = False
|
2018-04-25 20:52:36 +00:00
|
|
|
|
|
|
|
|
|
|
|
AUTH_HEADER_NAME = 'Authorization'
|
2018-05-21 19:07:14 +00:00
|
|
|
AUTH_SCHEME = 'Bearer '
|
2018-04-25 20:52:36 +00:00
|
|
|
|
|
|
|
|
|
|
|
class JWTIdentityPolicy(AbstractIdentityPolicy):
|
2020-12-18 17:58:38 +00:00
|
|
|
def __init__(self, secret: str, algorithm: str = 'HS256'):
|
|
|
|
if not HAS_JWT:
|
2018-05-21 19:07:14 +00:00
|
|
|
raise RuntimeError('Please install `PyJWT`')
|
2018-04-25 20:52:36 +00:00
|
|
|
self.secret = secret
|
2018-05-21 19:07:14 +00:00
|
|
|
self.algorithm = algorithm
|
2018-04-25 20:52:36 +00:00
|
|
|
|
2020-12-18 17:58:38 +00:00
|
|
|
async def identify(self, request: web.Request) -> Optional[str]:
|
2018-04-25 20:52:36 +00:00
|
|
|
header_identity = request.headers.get(AUTH_HEADER_NAME)
|
2018-05-21 19:07:14 +00:00
|
|
|
|
|
|
|
if header_identity is None:
|
2020-12-18 17:58:38 +00:00
|
|
|
return None
|
2018-05-21 19:07:14 +00:00
|
|
|
|
|
|
|
if not header_identity.startswith(AUTH_SCHEME):
|
|
|
|
raise ValueError('Invalid authorization scheme. ' +
|
2020-12-18 17:58:38 +00:00
|
|
|
'Should be `{}<token>`'.format(AUTH_SCHEME))
|
2018-05-21 19:07:14 +00:00
|
|
|
|
|
|
|
token = header_identity.split(' ')[1].strip()
|
|
|
|
|
|
|
|
identity = jwt.decode(token,
|
2018-04-25 20:52:36 +00:00
|
|
|
self.secret,
|
2018-09-06 10:06:55 +00:00
|
|
|
algorithms=[self.algorithm])
|
2018-05-21 19:07:14 +00:00
|
|
|
return identity
|
2018-04-25 20:52:36 +00:00
|
|
|
|
2020-12-18 17:58:38 +00:00
|
|
|
async def remember(self, request: web.Request, response: web.StreamResponse,
|
|
|
|
identity: str, **kwargs: None) -> None:
|
2018-04-25 20:52:36 +00:00
|
|
|
pass
|
|
|
|
|
2020-12-18 17:58:38 +00:00
|
|
|
async def forget(self, request: web.Request, response: web.StreamResponse) -> None:
|
2018-04-25 20:52:36 +00:00
|
|
|
pass
|