policy(minor): improve error handling
This commit is contained in:
parent
d44ac6e2a3
commit
de0b137b1e
|
@ -15,6 +15,7 @@ from django.utils.translation import gettext as _
|
|||
from model_utils.managers import InheritanceManager
|
||||
from structlog import get_logger
|
||||
|
||||
from passbook.policy.exceptions import PolicyException
|
||||
from passbook.core.signals import password_changed
|
||||
from passbook.lib.models import CreatedUpdatedModel, UUIDModel
|
||||
|
||||
|
@ -245,7 +246,7 @@ class Policy(UUIDModel, CreatedUpdatedModel):
|
|||
|
||||
def passes(self, user: User) -> PolicyResult:
|
||||
"""Check if user instance passes this policy"""
|
||||
raise NotImplementedError()
|
||||
raise PolicyException()
|
||||
|
||||
class FieldMatcherPolicy(Policy):
|
||||
"""Policy which checks if a field of the User model matches/doesn't match a
|
||||
|
|
4
passbook/policy/exceptions.py
Normal file
4
passbook/policy/exceptions.py
Normal file
|
@ -0,0 +1,4 @@
|
|||
"""policy exceptions"""
|
||||
|
||||
class PolicyException(Exception):
|
||||
"""Exception that should be raised during Policy Evaluation, and can be recovered from."""
|
|
@ -5,7 +5,8 @@ from typing import Any, Dict
|
|||
|
||||
from structlog import get_logger
|
||||
|
||||
from passbook.core.models import Policy, User
|
||||
from passbook.core.models import Policy, User, PolicyResult
|
||||
from passbook.policy.exceptions import PolicyException
|
||||
|
||||
LOGGER = get_logger(__name__)
|
||||
|
||||
|
@ -27,7 +28,11 @@ class PolicyTask(Process):
|
|||
setattr(self.user, key, value)
|
||||
LOGGER.debug("Running policy `%s`#%s for user %s...", self.policy.name,
|
||||
self.policy.pk.hex, self.user)
|
||||
policy_result = self.policy.passes(self.user)
|
||||
try:
|
||||
policy_result = self.policy.passes(self.user)
|
||||
except PolicyException as exc:
|
||||
LOGGER.debug(exc)
|
||||
policy_result = PolicyResult(False, str(exc))
|
||||
# Invert result if policy.negate is set
|
||||
if self.policy.negate:
|
||||
policy_result = not policy_result
|
||||
|
|
Reference in a new issue