aiohttp-security/demo/dictionary_auth/authz.py

40 lines
1.3 KiB
Python
Raw Normal View History

2020-12-18 17:58:38 +00:00
from enum import Enum
from typing import Dict, Optional, Union
from aiohttp_security.abc import AbstractAuthorizationPolicy
2020-12-18 17:58:38 +00:00
from .users import User
class DictionaryAuthorizationPolicy(AbstractAuthorizationPolicy):
2020-12-18 17:58:38 +00:00
def __init__(self, user_map: Dict[str, User]):
super().__init__()
self.user_map = user_map
2020-12-18 17:58:38 +00:00
async def authorized_userid(self, identity: str) -> Optional[str]:
"""Retrieve authorized user id.
Return the user_id of the user identified by the identity
or 'None' if no user exists related to the identity.
"""
2020-12-18 17:58:38 +00:00
return identity if identity in self.user_map else None
2020-12-18 17:58:38 +00:00
async def permits(self, identity: str, permission: Union[str, Enum],
context: None = None) -> bool:
"""Check user permissions.
Return True if the identity is allowed the permission in the
current context, else return False.
"""
# pylint: disable=unused-argument
user = self.user_map.get(identity)
if not user:
return False
return permission in user.permissions
2020-12-18 17:58:38 +00:00
async def check_credentials(user_map: Dict[str, User], username: str, password: str) -> bool:
user = user_map.get(username)
if not user:
return False
return user.password == password