This repository has been archived on 2024-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
authentik/passbook/policies/mixins.py

57 lines
1.8 KiB
Python
Raw Normal View History

"""passbook access helper classes"""
from typing import Optional
from django.contrib import messages
from django.http import HttpRequest
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
from passbook.core.models import Application, Provider, User
2019-10-07 14:33:48 +00:00
from passbook.policies.engine import PolicyEngine
from passbook.policies.types import PolicyResult
2018-12-09 20:07:38 +00:00
LOGGER = get_logger()
2019-12-31 11:51:16 +00:00
class BaseMixin:
"""Base Mixin class, used to annotate View Member variables"""
request: HttpRequest
class PolicyAccessMixin(BaseMixin):
"""Mixin class for usage in Authorization views.
Provider functions to check application access, etc"""
def provider_to_application(self, provider: Provider) -> Application:
"""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-12-31 11:51:16 +00:00
messages.error(
self.request,
_(
'Provider "%(name)s" has no application assigned'
% {"name": provider}
),
)
raise exc
def user_has_access(
self, application: Application, user: Optional[User] = None
) -> PolicyResult:
"""Check if user has access to application."""
user = user or self.request.user
policy_engine = PolicyEngine(
application, user or self.request.user, self.request
)
policy_engine.build()
result = policy_engine.result
LOGGER.debug(
"AccessMixin user_has_access", user=user, app=application, result=result,
)
if not result.passing:
for message in result.messages:
messages.error(self.request, _(message))
return result