2018-11-25 19:39:09 +00:00
|
|
|
"""passbook access helper classes"""
|
2019-10-04 14:09:35 +00:00
|
|
|
from typing import List, Tuple
|
|
|
|
|
2019-02-26 08:10:37 +00:00
|
|
|
from django.contrib import messages
|
2019-10-04 14:09:35 +00:00
|
|
|
from django.http import HttpRequest
|
2019-02-26 08:10:37 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2019-10-01 08:24:10 +00:00
|
|
|
from structlog import get_logger
|
2018-12-09 20:07:38 +00:00
|
|
|
|
2019-10-04 14:09:35 +00:00
|
|
|
from passbook.core.models import Application, Provider, User
|
2019-10-01 08:17:39 +00:00
|
|
|
from passbook.policy.engine import PolicyEngine
|
2018-12-09 20:07:38 +00:00
|
|
|
|
2019-10-04 08:08:53 +00:00
|
|
|
LOGGER = get_logger()
|
2018-11-25 19:39:09 +00:00
|
|
|
|
|
|
|
class AccessMixin:
|
|
|
|
"""Mixin class for usage in Authorization views.
|
|
|
|
Provider functions to check application access, etc"""
|
|
|
|
|
2019-02-26 08:10:37 +00:00
|
|
|
# request is set by view but since this Mixin has no base class
|
2019-10-04 14:09:35 +00:00
|
|
|
request: HttpRequest = None
|
2019-02-26 08:10:37 +00:00
|
|
|
|
2019-10-04 14:09:35 +00:00
|
|
|
def provider_to_application(self, provider: Provider) -> Application:
|
2018-11-25 19:39:09 +00:00
|
|
|
"""Lookup application assigned to provider, throw error if no application assigned"""
|
2018-12-09 20:07:38 +00:00
|
|
|
try:
|
|
|
|
return provider.application
|
|
|
|
except Application.DoesNotExist as exc:
|
2019-02-26 08:10:37 +00:00
|
|
|
messages.error(self.request, _('Provider "%(name)s" has no application assigned' % {
|
|
|
|
'name': provider
|
|
|
|
}))
|
|
|
|
raise exc
|
2018-11-25 19:39:09 +00:00
|
|
|
|
2019-10-04 14:09:35 +00:00
|
|
|
def user_has_access(self, application: Application, user: User) -> Tuple[bool, List[str]]:
|
2018-11-25 19:39:09 +00:00
|
|
|
"""Check if user has access to application."""
|
2019-10-04 14:09:35 +00:00
|
|
|
LOGGER.debug("Checking permissions", user=user, application=application)
|
2019-03-12 09:56:01 +00:00
|
|
|
policy_engine = PolicyEngine(application.policies.all())
|
|
|
|
policy_engine.for_user(user).with_request(self.request).build()
|
|
|
|
return policy_engine.result
|