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-02-19 08:49:38 +00:00
|
|
|
from passbook.policies.expression.evaluator import Evaluator
|
2020-05-16 16:07:00 +00: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):
|
|
|
|
"""Jinja2-based Expression policy that allows Admins to write their own logic"""
|
|
|
|
|
|
|
|
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-01 13:25:38 +00:00
|
|
|
evaluator = Evaluator()
|
|
|
|
evaluator.set_policy_request(request)
|
|
|
|
return evaluator.evaluate(self.expression)
|
2020-02-18 14:12:22 +00:00
|
|
|
|
|
|
|
def save(self, *args, **kwargs):
|
2020-02-19 08:49:38 +00:00
|
|
|
Evaluator().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")
|