From de0b137b1e7c7d2693680d581b6b6ea3d3cf18c6 Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Wed, 2 Oct 2019 22:28:39 +0200 Subject: [PATCH] policy(minor): improve error handling --- passbook/core/models.py | 3 ++- passbook/policy/exceptions.py | 4 ++++ passbook/policy/task.py | 9 +++++++-- 3 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 passbook/policy/exceptions.py diff --git a/passbook/core/models.py b/passbook/core/models.py index 96266fe88..3317f5c97 100644 --- a/passbook/core/models.py +++ b/passbook/core/models.py @@ -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 diff --git a/passbook/policy/exceptions.py b/passbook/policy/exceptions.py new file mode 100644 index 000000000..edf8d6372 --- /dev/null +++ b/passbook/policy/exceptions.py @@ -0,0 +1,4 @@ +"""policy exceptions""" + +class PolicyException(Exception): + """Exception that should be raised during Policy Evaluation, and can be recovered from.""" diff --git a/passbook/policy/task.py b/passbook/policy/task.py index da8312407..bf9beafb1 100644 --- a/passbook/policy/task.py +++ b/passbook/policy/task.py @@ -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