2020-02-18 14:12:22 +00:00
|
|
|
"""passbook expression Policy Models"""
|
|
|
|
from django.db import models
|
|
|
|
from django.utils.translation import gettext as _
|
|
|
|
|
2020-06-05 11:00:27 +01:00
|
|
|
from passbook.policies.expression.evaluator import PolicyEvaluator
|
2020-05-16 17:07:00 +01:00
|
|
|
from passbook.policies.models import Policy
|
2020-02-20 12:52:05 +00:00
|
|
|
from passbook.policies.types import PolicyRequest, PolicyResult
|
2020-02-18 14:12:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ExpressionPolicy(Policy):
|
2020-06-05 11:00:27 +01:00
|
|
|
"""Implement custom logic using python."""
|
2020-02-18 14:12:22 +00:00
|
|
|
|
|
|
|
expression = models.TextField()
|
|
|
|
|
|
|
|
form = "passbook.policies.expression.forms.ExpressionPolicyForm"
|
|
|
|
|
|
|
|
def passes(self, request: PolicyRequest) -> PolicyResult:
|
|
|
|
"""Evaluate and render expression. Returns PolicyResult(false) on error."""
|
2020-06-05 11:00:27 +01:00
|
|
|
evaluator = PolicyEvaluator(self.name)
|
2020-06-01 14:25:38 +01:00
|
|
|
evaluator.set_policy_request(request)
|
|
|
|
return evaluator.evaluate(self.expression)
|
2020-02-18 14:12:22 +00:00
|
|
|
|
|
|
|
def save(self, *args, **kwargs):
|
2020-06-05 11:00:27 +01:00
|
|
|
PolicyEvaluator(self.name).validate(self.expression)
|
2020-02-18 14:12:22 +00:00
|
|
|
return super().save(*args, **kwargs)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
|
|
|
verbose_name = _("Expression Policy")
|
|
|
|
verbose_name_plural = _("Expression Policies")
|