2020-02-18 14:12:22 +00:00
|
|
|
|
"""passbook expression Policy Models"""
|
2020-07-20 13:58:48 +00:00
|
|
|
|
from typing import Type
|
|
|
|
|
|
2020-02-18 14:12:22 +00:00
|
|
|
|
from django.db import models
|
2020-07-20 13:58:48 +00:00
|
|
|
|
from django.forms import ModelForm
|
2020-02-18 14:12:22 +00:00
|
|
|
|
from django.utils.translation import gettext as _
|
|
|
|
|
|
2020-06-05 10:00:27 +00:00
|
|
|
|
from passbook.policies.expression.evaluator import PolicyEvaluator
|
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):
|
2020-07-01 16:40:52 +00:00
|
|
|
|
"""Execute arbitrary Python code to implement custom checks and validation."""
|
2020-02-18 14:12:22 +00:00
|
|
|
|
|
|
|
|
|
expression = models.TextField()
|
|
|
|
|
|
2020-07-20 13:58:48 +00:00
|
|
|
|
def form(self) -> Type[ModelForm]:
|
|
|
|
|
from passbook.policies.expression.forms import ExpressionPolicyForm
|
|
|
|
|
|
|
|
|
|
return ExpressionPolicyForm
|
2020-02-18 14:12:22 +00:00
|
|
|
|
|
|
|
|
|
def passes(self, request: PolicyRequest) -> PolicyResult:
|
|
|
|
|
"""Evaluate and render expression. Returns PolicyResult(false) on error."""
|
2020-06-05 10:00:27 +00:00
|
|
|
|
evaluator = PolicyEvaluator(self.name)
|
2020-06-01 13:25:38 +00: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 10:00:27 +00: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")
|