authentik.policies.models

Policy base models

  1"""Policy base models"""
  2
  3from uuid import uuid4
  4
  5from django.db import models
  6from django.utils.translation import gettext_lazy as _
  7from model_utils.managers import InheritanceManager
  8from rest_framework.serializers import BaseSerializer
  9
 10from authentik.lib.models import (
 11    CreatedUpdatedModel,
 12    ExpiringManager,
 13    ExpiringModel,
 14    InheritanceAutoManager,
 15    InheritanceForeignKey,
 16    SerializerModel,
 17)
 18from authentik.policies.exceptions import PolicyException
 19from authentik.policies.types import PolicyRequest, PolicyResult
 20
 21
 22class PolicyEngineMode(models.TextChoices):
 23    """Decide how results of multiple policies should be combined."""
 24
 25    MODE_ALL = "all", _("all, all policies must pass")  # type: "PolicyEngineMode"
 26    MODE_ANY = "any", _("any, any policy must pass")  # type: "PolicyEngineMode"
 27
 28
 29class PolicyBindingModel(models.Model):
 30    """Base Model for objects that have policies applied to them."""
 31
 32    pbm_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
 33
 34    policies = models.ManyToManyField(
 35        "Policy", through="PolicyBinding", related_name="bindings", blank=True
 36    )
 37
 38    policy_engine_mode = models.TextField(
 39        choices=PolicyEngineMode.choices,
 40        default=PolicyEngineMode.MODE_ANY,
 41    )
 42
 43    objects = InheritanceManager()
 44
 45    class Meta:
 46        verbose_name = _("Policy Binding Model")
 47        verbose_name_plural = _("Policy Binding Models")
 48
 49    def __str__(self) -> str:
 50        return f"PolicyBindingModel {self.pbm_uuid}"
 51
 52    def supported_policy_binding_targets(self):
 53        """Return the list of objects that can be bound to this object."""
 54        return ["policy", "user", "group"]
 55
 56
 57class BoundPolicyQuerySet(models.QuerySet):
 58    """QuerySet for filtering enabled bindings for a Policy type"""
 59
 60    def for_policy(self, policy: Policy):
 61        return self.filter(policy__in=policy._default_manager.all()).filter(enabled=True)
 62
 63
 64class PolicyBinding(ExpiringModel, SerializerModel):
 65    """Relationship between a Policy and a PolicyBindingModel."""
 66
 67    policy_binding_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
 68
 69    enabled = models.BooleanField(default=True)
 70    dry_run = models.BooleanField(
 71        default=False,
 72        help_text=_("Execute the policy but ignore its result."),
 73    )
 74    # Shadow's field from ExpiringModel, as we don't want to default expire
 75    expiring = models.BooleanField(default=False)
 76
 77    policy = InheritanceForeignKey(
 78        "Policy",
 79        on_delete=models.CASCADE,
 80        related_name="+",
 81        default=None,
 82        null=True,
 83        blank=True,
 84    )
 85    group = models.ForeignKey(
 86        # This is quite an ugly hack to prevent pylint from trying
 87        # to resolve authentik_core.models.Group
 88        # as python import path
 89        "authentik_core.Group",
 90        on_delete=models.CASCADE,
 91        default=None,
 92        null=True,
 93        blank=True,
 94    )
 95    user = models.ForeignKey(
 96        "authentik_core.User",
 97        on_delete=models.CASCADE,
 98        default=None,
 99        null=True,
100        blank=True,
101    )
102
103    target = InheritanceForeignKey(
104        PolicyBindingModel, on_delete=models.CASCADE, related_name="bindings"
105    )
106    negate = models.BooleanField(
107        default=False,
108        help_text=_("Negates the outcome of the policy. Messages are unaffected."),
109    )
110    timeout = models.PositiveIntegerField(
111        default=30, help_text=_("Timeout after which Policy execution is terminated.")
112    )
113    failure_result = models.BooleanField(
114        default=False, help_text=_("Result if the Policy execution fails.")
115    )
116
117    order = models.IntegerField()
118
119    def passes(self, request: PolicyRequest) -> PolicyResult:
120        """Check if request passes this PolicyBinding, check policy, group or user"""
121        if self.is_expired:
122            return PolicyResult(False)
123        if self.policy:
124            self.policy: Policy
125            return self.policy.passes(request)
126        if self.group:
127            return PolicyResult(self.group.is_member(request.user))
128        if self.user:
129            return PolicyResult(request.user == self.user)
130        return PolicyResult(False)
131
132    @property
133    def serializer(self) -> type[BaseSerializer]:
134        from authentik.policies.api.bindings import PolicyBindingSerializer
135
136        return PolicyBindingSerializer
137
138    @property
139    def target_type(self) -> str:
140        """Get the target type this binding is applied to"""
141        if self.policy:
142            return "policy"
143        if self.group:
144            return "group"
145        if self.user:
146            return "user"
147        return "invalid"
148
149    @property
150    def target_name(self) -> str:
151        """Get the target name this binding is applied to"""
152        if self.policy:
153            return self.policy.name
154        if self.group:
155            return self.group.name
156        if self.user:
157            return self.user.name
158        return "invalid"
159
160    def __str__(self) -> str:
161        suffix = f"{self.target_type.title()} {self.target_name}"
162        try:
163            return f"Binding from {self.target} #{self.order} to {suffix}"
164        except PolicyBinding.target.RelatedObjectDoesNotExist:
165            return f"Binding - #{self.order} to {suffix}"
166        return ""
167
168    objects = ExpiringManager()
169    in_use = BoundPolicyQuerySet.as_manager()
170
171    class Meta:
172        verbose_name = _("Policy Binding")
173        verbose_name_plural = _("Policy Bindings")
174        unique_together = ("policy", "target", "order")
175        indexes = ExpiringModel.Meta.indexes + [
176            models.Index(fields=["policy"]),
177            models.Index(fields=["group"]),
178            models.Index(fields=["user"]),
179            models.Index(fields=["target"]),
180        ]
181
182
183class Policy(SerializerModel, CreatedUpdatedModel):
184    """Policies which specify if a user is authorized to use an Application. Can be overridden by
185    other types to add other fields, more logic, etc."""
186
187    policy_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
188
189    name = models.TextField(unique=True)
190
191    execution_logging = models.BooleanField(
192        default=False,
193        help_text=_(
194            "When this option is enabled, all executions of this policy will be logged. "
195            "By default, only execution errors are logged."
196        ),
197    )
198
199    objects = InheritanceAutoManager()
200
201    @property
202    def component(self) -> str:
203        """Return component used to edit this object"""
204        raise NotImplementedError
205
206    def __str__(self):
207        return str(self.name)
208
209    def passes(self, request: PolicyRequest) -> PolicyResult:  # pragma: no cover
210        """Check if request passes this policy"""
211        raise PolicyException()
212
213    class Meta:
214        base_manager_name = "objects"
215
216        verbose_name = _("Policy")
217        verbose_name_plural = _("Policies")
218
219        permissions = [
220            ("view_policy_cache", _("View Policy's cache metrics")),
221            ("clear_policy_cache", _("Clear Policy's cache metrics")),
222        ]
223
224    class PolicyMeta:
225        """Base class for the Meta class for all policies"""
226
227        indexes = [
228            models.Index(fields=["policy_ptr_id"]),
229        ]
230
231
232class RequestableModel:
233    """Mixin for models which access can be requested to"""
234
235    def requestable_child_model_types(self) -> list[type[RequestableChildModel]]:
236        return []
237
238    @property
239    def requestable_label(self) -> str:
240        return str(self)
241
242    @property
243    def requestable_parent(self) -> RequestableModel | None:
244        return None
245
246
247class RequestableChildModel:
248    """Mixin for models which are related of models that access can be requested too
249    and should be equally offered"""
250
251    @property
252    def requestable_label(self) -> str:
253        return str(self)
254
255    @property
256    def requestable_parent(self) -> RequestableModel:
257        raise NotImplementedError
class PolicyEngineMode(django.db.models.enums.TextChoices):
23class PolicyEngineMode(models.TextChoices):
24    """Decide how results of multiple policies should be combined."""
25
26    MODE_ALL = "all", _("all, all policies must pass")  # type: "PolicyEngineMode"
27    MODE_ANY = "any", _("any, any policy must pass")  # type: "PolicyEngineMode"

Decide how results of multiple policies should be combined.

class PolicyBindingModel(django.db.models.base.Model):
30class PolicyBindingModel(models.Model):
31    """Base Model for objects that have policies applied to them."""
32
33    pbm_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
34
35    policies = models.ManyToManyField(
36        "Policy", through="PolicyBinding", related_name="bindings", blank=True
37    )
38
39    policy_engine_mode = models.TextField(
40        choices=PolicyEngineMode.choices,
41        default=PolicyEngineMode.MODE_ANY,
42    )
43
44    objects = InheritanceManager()
45
46    class Meta:
47        verbose_name = _("Policy Binding Model")
48        verbose_name_plural = _("Policy Binding Models")
49
50    def __str__(self) -> str:
51        return f"PolicyBindingModel {self.pbm_uuid}"
52
53    def supported_policy_binding_targets(self):
54        """Return the list of objects that can be bound to this object."""
55        return ["policy", "user", "group"]

Base Model for objects that have policies applied to them.

def pbm_uuid(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

policies

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

def policy_engine_mode(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def objects(unknown):

The type of the None singleton.

def supported_policy_binding_targets(self):
53    def supported_policy_binding_targets(self):
54        """Return the list of objects that can be bound to this object."""
55        return ["policy", "user", "group"]

Return the list of objects that can be bound to this object.

def get_policy_engine_mode_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

bindings

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

application

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

applicationentitlement

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

source

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

flow

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

flowstagebinding

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

notificationrule

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

device

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

deviceaccessgroup

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

oauth2dynamicclientregistration

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

userexpirationrule

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

request_rule_bindings

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

request_rule_child_bindings

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

requestrulebinding

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

request_rules

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

requestrule

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

grantrequest_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

grantrequesttarget_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class PolicyBindingModel.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class PolicyBindingModel.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class BoundPolicyQuerySet(django.db.models.query.QuerySet):
58class BoundPolicyQuerySet(models.QuerySet):
59    """QuerySet for filtering enabled bindings for a Policy type"""
60
61    def for_policy(self, policy: Policy):
62        return self.filter(policy__in=policy._default_manager.all()).filter(enabled=True)

QuerySet for filtering enabled bindings for a Policy type

def for_policy(self, policy: Policy):
61    def for_policy(self, policy: Policy):
62        return self.filter(policy__in=policy._default_manager.all()).filter(enabled=True)
 65class PolicyBinding(ExpiringModel, SerializerModel):
 66    """Relationship between a Policy and a PolicyBindingModel."""
 67
 68    policy_binding_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
 69
 70    enabled = models.BooleanField(default=True)
 71    dry_run = models.BooleanField(
 72        default=False,
 73        help_text=_("Execute the policy but ignore its result."),
 74    )
 75    # Shadow's field from ExpiringModel, as we don't want to default expire
 76    expiring = models.BooleanField(default=False)
 77
 78    policy = InheritanceForeignKey(
 79        "Policy",
 80        on_delete=models.CASCADE,
 81        related_name="+",
 82        default=None,
 83        null=True,
 84        blank=True,
 85    )
 86    group = models.ForeignKey(
 87        # This is quite an ugly hack to prevent pylint from trying
 88        # to resolve authentik_core.models.Group
 89        # as python import path
 90        "authentik_core.Group",
 91        on_delete=models.CASCADE,
 92        default=None,
 93        null=True,
 94        blank=True,
 95    )
 96    user = models.ForeignKey(
 97        "authentik_core.User",
 98        on_delete=models.CASCADE,
 99        default=None,
100        null=True,
101        blank=True,
102    )
103
104    target = InheritanceForeignKey(
105        PolicyBindingModel, on_delete=models.CASCADE, related_name="bindings"
106    )
107    negate = models.BooleanField(
108        default=False,
109        help_text=_("Negates the outcome of the policy. Messages are unaffected."),
110    )
111    timeout = models.PositiveIntegerField(
112        default=30, help_text=_("Timeout after which Policy execution is terminated.")
113    )
114    failure_result = models.BooleanField(
115        default=False, help_text=_("Result if the Policy execution fails.")
116    )
117
118    order = models.IntegerField()
119
120    def passes(self, request: PolicyRequest) -> PolicyResult:
121        """Check if request passes this PolicyBinding, check policy, group or user"""
122        if self.is_expired:
123            return PolicyResult(False)
124        if self.policy:
125            self.policy: Policy
126            return self.policy.passes(request)
127        if self.group:
128            return PolicyResult(self.group.is_member(request.user))
129        if self.user:
130            return PolicyResult(request.user == self.user)
131        return PolicyResult(False)
132
133    @property
134    def serializer(self) -> type[BaseSerializer]:
135        from authentik.policies.api.bindings import PolicyBindingSerializer
136
137        return PolicyBindingSerializer
138
139    @property
140    def target_type(self) -> str:
141        """Get the target type this binding is applied to"""
142        if self.policy:
143            return "policy"
144        if self.group:
145            return "group"
146        if self.user:
147            return "user"
148        return "invalid"
149
150    @property
151    def target_name(self) -> str:
152        """Get the target name this binding is applied to"""
153        if self.policy:
154            return self.policy.name
155        if self.group:
156            return self.group.name
157        if self.user:
158            return self.user.name
159        return "invalid"
160
161    def __str__(self) -> str:
162        suffix = f"{self.target_type.title()} {self.target_name}"
163        try:
164            return f"Binding from {self.target} #{self.order} to {suffix}"
165        except PolicyBinding.target.RelatedObjectDoesNotExist:
166            return f"Binding - #{self.order} to {suffix}"
167        return ""
168
169    objects = ExpiringManager()
170    in_use = BoundPolicyQuerySet.as_manager()
171
172    class Meta:
173        verbose_name = _("Policy Binding")
174        verbose_name_plural = _("Policy Bindings")
175        unique_together = ("policy", "target", "order")
176        indexes = ExpiringModel.Meta.indexes + [
177            models.Index(fields=["policy"]),
178            models.Index(fields=["group"]),
179            models.Index(fields=["user"]),
180            models.Index(fields=["target"]),
181        ]

Relationship between a Policy and a PolicyBindingModel.

def policy_binding_uuid(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def enabled(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def dry_run(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def expiring(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

policy

Forward ManyToOne Descriptor that selects subclass. Requires InheritanceAutoManager.

group

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

user

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

target

Forward ManyToOne Descriptor that selects subclass. Requires InheritanceAutoManager.

def negate(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def timeout(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def failure_result(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def order(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

120    def passes(self, request: PolicyRequest) -> PolicyResult:
121        """Check if request passes this PolicyBinding, check policy, group or user"""
122        if self.is_expired:
123            return PolicyResult(False)
124        if self.policy:
125            self.policy: Policy
126            return self.policy.passes(request)
127        if self.group:
128            return PolicyResult(self.group.is_member(request.user))
129        if self.user:
130            return PolicyResult(request.user == self.user)
131        return PolicyResult(False)

Check if request passes this PolicyBinding, check policy, group or user

serializer: type[rest_framework.serializers.BaseSerializer]
133    @property
134    def serializer(self) -> type[BaseSerializer]:
135        from authentik.policies.api.bindings import PolicyBindingSerializer
136
137        return PolicyBindingSerializer

Get serializer for this model

target_type: str
139    @property
140    def target_type(self) -> str:
141        """Get the target type this binding is applied to"""
142        if self.policy:
143            return "policy"
144        if self.group:
145            return "group"
146        if self.user:
147            return "user"
148        return "invalid"

Get the target type this binding is applied to

target_name: str
150    @property
151    def target_name(self) -> str:
152        """Get the target name this binding is applied to"""
153        if self.policy:
154            return self.policy.name
155        if self.group:
156            return self.group.name
157        if self.user:
158            return self.user.name
159        return "invalid"

Get the target name this binding is applied to

def objects(unknown):

The type of the None singleton.

def in_use(unknown):

The type of the None singleton.

def expires(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

policy_id
group_id
user_id
target_id
deviceuserbinding

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

grantrequesttarget_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class PolicyBinding.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class PolicyBinding.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

184class Policy(SerializerModel, CreatedUpdatedModel):
185    """Policies which specify if a user is authorized to use an Application. Can be overridden by
186    other types to add other fields, more logic, etc."""
187
188    policy_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
189
190    name = models.TextField(unique=True)
191
192    execution_logging = models.BooleanField(
193        default=False,
194        help_text=_(
195            "When this option is enabled, all executions of this policy will be logged. "
196            "By default, only execution errors are logged."
197        ),
198    )
199
200    objects = InheritanceAutoManager()
201
202    @property
203    def component(self) -> str:
204        """Return component used to edit this object"""
205        raise NotImplementedError
206
207    def __str__(self):
208        return str(self.name)
209
210    def passes(self, request: PolicyRequest) -> PolicyResult:  # pragma: no cover
211        """Check if request passes this policy"""
212        raise PolicyException()
213
214    class Meta:
215        base_manager_name = "objects"
216
217        verbose_name = _("Policy")
218        verbose_name_plural = _("Policies")
219
220        permissions = [
221            ("view_policy_cache", _("View Policy's cache metrics")),
222            ("clear_policy_cache", _("Clear Policy's cache metrics")),
223        ]
224
225    class PolicyMeta:
226        """Base class for the Meta class for all policies"""
227
228        indexes = [
229            models.Index(fields=["policy_ptr_id"]),
230        ]

Policies which specify if a user is authorized to use an Application. Can be overridden by other types to add other fields, more logic, etc.

def policy_uuid(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def name(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def execution_logging(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def objects(unknown):

The type of the None singleton.

component: str
202    @property
203    def component(self) -> str:
204        """Return component used to edit this object"""
205        raise NotImplementedError

Return component used to edit this object

210    def passes(self, request: PolicyRequest) -> PolicyResult:  # pragma: no cover
211        """Check if request passes this policy"""
212        raise PolicyException()

Check if request passes this policy

def created(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def last_updated(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def get_next_by_created(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_created(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_next_by_last_updated(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_last_updated(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

bindings

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

dummypolicy

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

eventmatcherpolicy

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

passwordexpirypolicy

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

reputationpolicy

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

expressionpolicy

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

geoippolicy

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

promptstage_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

promptstagevalidationpolicy_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

passwordpolicy

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

uniquepasswordpolicy

Accessor to the related object on the reverse side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

class Policy.PolicyMeta:
225    class PolicyMeta:
226        """Base class for the Meta class for all policies"""
227
228        indexes = [
229            models.Index(fields=["policy_ptr_id"]),
230        ]

Base class for the Meta class for all policies

indexes = [<Index: fields=['policy_ptr_id']>]
class Policy.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class Policy.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class RequestableModel:
233class RequestableModel:
234    """Mixin for models which access can be requested to"""
235
236    def requestable_child_model_types(self) -> list[type[RequestableChildModel]]:
237        return []
238
239    @property
240    def requestable_label(self) -> str:
241        return str(self)
242
243    @property
244    def requestable_parent(self) -> RequestableModel | None:
245        return None

Mixin for models which access can be requested to

def requestable_child_model_types(self) -> list[type[RequestableChildModel]]:
236    def requestable_child_model_types(self) -> list[type[RequestableChildModel]]:
237        return []
requestable_label: str
239    @property
240    def requestable_label(self) -> str:
241        return str(self)
requestable_parent: RequestableModel | None
243    @property
244    def requestable_parent(self) -> RequestableModel | None:
245        return None
class RequestableChildModel:
248class RequestableChildModel:
249    """Mixin for models which are related of models that access can be requested too
250    and should be equally offered"""
251
252    @property
253    def requestable_label(self) -> str:
254        return str(self)
255
256    @property
257    def requestable_parent(self) -> RequestableModel:
258        raise NotImplementedError

Mixin for models which are related of models that access can be requested too and should be equally offered

requestable_label: str
252    @property
253    def requestable_label(self) -> str:
254        return str(self)
requestable_parent: RequestableModel
256    @property
257    def requestable_parent(self) -> RequestableModel:
258        raise NotImplementedError