authentik.core.models
authentik core models
1"""authentik core models""" 2 3import re 4import traceback 5from collections.abc import Callable 6from datetime import datetime, timedelta 7from enum import StrEnum 8from hashlib import sha256 9from typing import Any, Self 10from uuid import uuid4 11 12import pgtrigger 13from asgiref.sync import sync_to_async 14from deepmerge import always_merger 15from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX 16from django.contrib.auth.models import AbstractUser, Permission 17from django.contrib.auth.models import UserManager as DjangoUserManager 18from django.contrib.contenttypes.models import ContentType 19from django.contrib.sessions.base_session import AbstractBaseSession 20from django.core.validators import validate_slug 21from django.db import models 22from django.db.models import Prefetch, Q, QuerySet, options 23from django.db.models.functions import Upper 24from django.http import HttpRequest 25from django.utils.encoding import iri_to_uri 26from django.utils.functional import cached_property 27from django.utils.timezone import now 28from django.utils.translation import gettext_lazy as _ 29from guardian.conf import settings 30from guardian.models import RoleModelPermission, RoleObjectPermission 31from model_utils.managers import InheritanceManager 32from psqlextra.expressions import ExcludedCol 33from psqlextra.indexes import UniqueIndex 34from psqlextra.models import PostgresMaterializedViewModel 35from psqlextra.query import ConflictAction 36from psqlextra.util import postgres_manager 37from rest_framework.exceptions import ValidationError 38from rest_framework.fields import BooleanField, CharField, IntegerField, ListField 39from rest_framework.serializers import Serializer 40from structlog.stdlib import get_logger 41 42from authentik.admin.files.backends.static import static_url_name 43from authentik.admin.files.fields import FileField 44from authentik.admin.files.manager import get_file_manager 45from authentik.admin.files.usage import FileUsage 46from authentik.admin.models import DEFAULT_TOKEN_DURATION, DEFAULT_TOKEN_LENGTH 47from authentik.admin.utils import get_system_settings 48from authentik.blueprints.models import ManagedModel 49from authentik.core.expression.exceptions import PropertyMappingExpressionException 50from authentik.core.types import UILoginButton, UserSettingSerializer 51from authentik.lib.avatars import get_avatar 52from authentik.lib.expression.exceptions import ControlFlowException 53from authentik.lib.generators import generate_id 54from authentik.lib.merge import MERGE_LIST_UNIQUE 55from authentik.lib.models import ( 56 CreatedUpdatedModel, 57 DomainlessFormattedURLValidator, 58 ExpiringModel, 59 SerializerModel, 60 SimpleThroughModel, 61) 62from authentik.lib.utils.inheritance import get_deepest_child 63from authentik.lib.utils.time import timedelta_from_string 64from authentik.policies.models import PolicyBindingModel, RequestableChildModel, RequestableModel 65from authentik.rbac.models import Role 66from authentik.root.install_id import get_install_id 67 68LOGGER = get_logger() 69USERNAME_MAX_LENGTH = 150 70USER_ACTIVITY_INTERVAL = timedelta(minutes=5) 71USER_PATH_SYSTEM_PREFIX = "goauthentik.io" 72_USER_ATTR_PREFIX = f"{USER_PATH_SYSTEM_PREFIX}/user" 73USER_ATTRIBUTE_DEBUG = f"{_USER_ATTR_PREFIX}/debug" 74USER_ATTRIBUTE_GENERATED = f"{_USER_ATTR_PREFIX}/generated" 75USER_ATTRIBUTE_EXPIRES = f"{_USER_ATTR_PREFIX}/expires" 76USER_ATTRIBUTE_DELETE_ON_LOGOUT = f"{_USER_ATTR_PREFIX}/delete-on-logout" 77USER_ATTRIBUTE_SOURCES = f"{_USER_ATTR_PREFIX}/sources" 78USER_ATTRIBUTE_TOKEN_EXPIRING = f"{_USER_ATTR_PREFIX}/token-expires" # nosec 79USER_ATTRIBUTE_TOKEN_MAXIMUM_LIFETIME = f"{_USER_ATTR_PREFIX}/token-maximum-lifetime" # nosec 80USER_ATTRIBUTE_CHANGE_USERNAME = f"{_USER_ATTR_PREFIX}/can-change-username" 81USER_ATTRIBUTE_CHANGE_NAME = f"{_USER_ATTR_PREFIX}/can-change-name" 82USER_ATTRIBUTE_CHANGE_EMAIL = f"{_USER_ATTR_PREFIX}/can-change-email" 83USER_PATH_SERVICE_ACCOUNT = f"{USER_PATH_SYSTEM_PREFIX}/service-accounts" 84 85options.DEFAULT_NAMES = options.DEFAULT_NAMES + ( 86 # used_by API that allows models to specify if they shadow an object 87 # for example the proxy provider which is built on top of an oauth provider 88 "authentik_used_by_shadows", 89) 90 91GROUP_RECURSION_LIMIT = 20 92 93MANAGED_ROLE_PREFIX_USER = "ak-managed-role--user" 94MANAGED_ROLE_PREFIX_GROUP = "ak-managed-role--group" 95 96 97def managed_role_name(user_or_group: models.Model): 98 if isinstance(user_or_group, User): 99 return f"{MANAGED_ROLE_PREFIX_USER}-{user_or_group.pk}" 100 if isinstance(user_or_group, Group): 101 return f"{MANAGED_ROLE_PREFIX_GROUP}-{user_or_group.pk}" 102 raise TypeError("Managed roles are only available for User or Group.") 103 104 105def default_token_duration() -> datetime: 106 """Default duration a Token is valid""" 107 settings = get_system_settings() 108 token_duration = ( 109 settings.default_token_duration 110 if hasattr(settings, "default_token_duration") 111 else DEFAULT_TOKEN_DURATION 112 ) 113 return now() + timedelta_from_string(token_duration) 114 115 116def default_token_key() -> str: 117 """Default token key""" 118 settings = get_system_settings() 119 token_length = ( 120 settings.default_token_length 121 if hasattr(settings, "default_token_length") 122 else DEFAULT_TOKEN_LENGTH 123 ) 124 # We use generate_id since the chars in the key should be easy 125 # to use in Emails (for verification) and URLs (for recovery) 126 return generate_id(token_length) 127 128 129class UserTypes(models.TextChoices): 130 """User types, both for grouping, licensing and permissions in the case 131 of the internal_service_account""" 132 133 INTERNAL = "internal" 134 EXTERNAL = "external" 135 136 # User-created service accounts 137 SERVICE_ACCOUNT = "service_account" 138 139 # Special user type for internally managed and created service 140 # accounts, such as outpost users 141 INTERNAL_SERVICE_ACCOUNT = "internal_service_account" 142 143 144SERVICE_ACCOUNT_TYPES = (UserTypes.SERVICE_ACCOUNT, UserTypes.INTERNAL_SERVICE_ACCOUNT) 145 146 147class AttributesMixin(models.Model): 148 """Adds an attributes property to a model""" 149 150 attributes = models.JSONField(default=dict, blank=True) 151 152 class Meta: 153 abstract = True 154 155 def update_attributes(self, properties: dict[str, Any]): 156 """Update fields and attributes, but correctly by merging dicts""" 157 needs_update = False 158 for key, value in properties.items(): 159 if key == "attributes": 160 continue 161 if getattr(self, key, None) != value: 162 setattr(self, key, value) 163 needs_update = True 164 final_attributes = {} 165 MERGE_LIST_UNIQUE.merge(final_attributes, self.attributes) 166 MERGE_LIST_UNIQUE.merge(final_attributes, properties.get("attributes", {})) 167 if self.attributes != final_attributes: 168 self.attributes = final_attributes 169 needs_update = True 170 if needs_update: 171 self.save() 172 173 @classmethod 174 def update_or_create_attributes( 175 cls, query: dict[str, Any], properties: dict[str, Any] 176 ) -> tuple[Self, bool]: 177 """Same as django's update_or_create but correctly updates attributes by merging dicts""" 178 instance = cls.objects.filter(**query).first() 179 if not instance: 180 return cls.objects.create(**properties), True 181 instance.update_attributes(properties) 182 return instance, False 183 184 185class GroupQuerySet(QuerySet): 186 def with_descendants(self): 187 pks = self.values_list("pk", flat=True) 188 return Group.objects.filter(Q(pk__in=pks) | Q(ancestor_nodes__ancestor__in=pks)).distinct() 189 190 def with_ancestors(self): 191 pks = self.values_list("pk", flat=True) 192 return Group.objects.filter( 193 Q(pk__in=pks) | Q(descendant_nodes__descendant__in=pks) 194 ).distinct() 195 196 197class Group(SerializerModel, AttributesMixin): 198 """Group model which supports a hierarchy and has attributes""" 199 200 group_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 201 202 name = models.TextField(verbose_name=_("name"), unique=True) 203 is_superuser = models.BooleanField( 204 default=False, help_text=_("Users added to this group will be superusers.") 205 ) 206 207 roles = models.ManyToManyField( 208 "authentik_rbac.Role", related_name="groups", blank=True, through="GroupRole" 209 ) 210 211 parents = models.ManyToManyField( 212 "Group", 213 blank=True, 214 symmetrical=False, 215 through="GroupParentageNode", 216 related_name="children", 217 ) 218 219 objects = GroupQuerySet.as_manager() 220 221 class Meta: 222 indexes = ( 223 models.Index(fields=["name"]), 224 models.Index(fields=["is_superuser"]), 225 ) 226 verbose_name = _("Group") 227 verbose_name_plural = _("Groups") 228 permissions = [ 229 ("add_user_to_group", _("Add user to group")), 230 ("remove_user_from_group", _("Remove user from group")), 231 ("enable_group_superuser", _("Enable superuser status")), 232 ("disable_group_superuser", _("Disable superuser status")), 233 ] 234 235 def __str__(self): 236 return f"Group {self.name}" 237 238 @property 239 def serializer(self) -> Serializer: 240 from authentik.core.api.groups import GroupSerializer 241 242 return GroupSerializer 243 244 @property 245 def num_pk(self) -> int: 246 """Get a numerical, int32 ID for the group""" 247 # int max is 2147483647 (10 digits) so 9 is the max usable 248 # in the LDAP Outpost we use the last 5 chars so match here 249 return int(str(self.pk.int)[:5]) 250 251 def is_member(self, user: User) -> bool: 252 """Recursively check if `user` is member of us, or any parent.""" 253 return user.all_groups().filter(group_uuid=self.group_uuid).exists() 254 255 def all_roles(self) -> QuerySet[Role]: 256 """Get all roles of this group and all of its ancestors.""" 257 return Role.objects.filter( 258 groups__in=Group.objects.filter(pk=self.pk).with_ancestors() 259 ).distinct() 260 261 def get_managed_role(self, create=False): 262 if create: 263 name = managed_role_name(self) 264 role, created = Role.objects.get_or_create(name=name, managed=name) 265 if created: 266 role.groups.add(self) 267 return role 268 else: 269 return Role.objects.filter(name=managed_role_name(self)).first() 270 271 def assign_perms_to_managed_role( 272 self, 273 perms: str | list[str] | Permission | list[Permission], 274 obj: models.Model | None = None, 275 ): 276 if not perms: 277 return 278 role = self.get_managed_role(create=True) 279 role.assign_perms(perms, obj) 280 281 282class GroupParentageNode(models.Model): 283 uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 284 285 child = models.ForeignKey(Group, related_name="parent_nodes", on_delete=models.CASCADE) 286 parent = models.ForeignKey(Group, related_name="child_nodes", on_delete=models.CASCADE) 287 288 class Meta: 289 verbose_name = _("Group Parentage Node") 290 verbose_name_plural = _("Group Parentage Nodes") 291 292 db_table = "authentik_core_groupparentage" 293 294 triggers = [ 295 pgtrigger.Trigger( 296 name="refresh_groupancestry", 297 operation=pgtrigger.Insert | pgtrigger.Update | pgtrigger.Delete, 298 when=pgtrigger.After, 299 func=""" 300 REFRESH MATERIALIZED VIEW CONCURRENTLY authentik_core_groupancestry; 301 RETURN NULL; 302 """, 303 ), 304 ] 305 306 def __str__(self) -> str: 307 return f"Group Parentage Node from #{self.child_id} to {self.parent_id}" 308 309 310class GroupAncestryNode(PostgresMaterializedViewModel): 311 descendant = models.ForeignKey( 312 Group, related_name="ancestor_nodes", on_delete=models.DO_NOTHING 313 ) 314 ancestor = models.ForeignKey( 315 Group, related_name="descendant_nodes", on_delete=models.DO_NOTHING 316 ) 317 318 class Meta: 319 # This is a transitive closure of authentik_core_groupparentage 320 # See https://en.wikipedia.org/wiki/Transitive_closure#In_graph_theory 321 db_table = "authentik_core_groupancestry" 322 indexes = [ 323 models.Index(fields=["descendant"]), 324 models.Index(fields=["ancestor"]), 325 UniqueIndex(fields=["id"]), 326 ] 327 328 class ViewMeta: 329 query = """ 330 WITH RECURSIVE accumulator AS ( 331 SELECT 332 child_id::text || '-' || parent_id::text as id, 333 child_id AS descendant_id, 334 parent_id AS ancestor_id 335 FROM authentik_core_groupparentage 336 337 UNION 338 339 SELECT 340 accumulator.descendant_id::text || '-' || current.parent_id::text as id, 341 accumulator.descendant_id, 342 current.parent_id AS ancestor_id 343 FROM accumulator 344 JOIN authentik_core_groupparentage current 345 ON accumulator.ancestor_id = current.child_id 346 ) 347 SELECT * FROM accumulator 348 """ 349 350 def __str__(self) -> str: 351 return f"Group Ancestry Node from {self.descendant_id} to {self.ancestor_id}" 352 353 354class UserQuerySet(models.QuerySet): 355 """User queryset""" 356 357 def exclude_anonymous(self): 358 """Exclude anonymous user""" 359 return self.exclude(**{User.USERNAME_FIELD: settings.ANONYMOUS_USER_NAME}) 360 361 def filter_agents(self) -> Self: 362 """Include only agent users.""" 363 from authentik.enterprise.agents.models import AgentUserQuerySet 364 365 return AgentUserQuerySet.filter_agents(self) 366 367 def exclude_agents(self) -> Self: 368 """Exclude agent users.""" 369 from authentik.enterprise.agents.models import AgentUserQuerySet 370 371 return AgentUserQuerySet.exclude_agents(self) 372 373 374class UserManager(DjangoUserManager.from_queryset(UserQuerySet)): 375 """User manager that doesn't assign is_superuser and is_staff""" 376 377 def create_user(self, username, email=None, password=None, **extra_fields): 378 """User manager that doesn't assign is_superuser and is_staff""" 379 from authentik.stages.password.models import PasswordDevice 380 381 user = self.create(username=username, email=self.normalize_email(email), **extra_fields) 382 if password is not None: 383 PasswordDevice.set_password(user, password, signal=False) 384 return user 385 386 def exclude_anonymous(self) -> QuerySet: 387 """Exclude anonymous user""" 388 return self.get_queryset().exclude_anonymous() 389 390 391class User(SerializerModel, AttributesMixin, AbstractUser): 392 """authentik User model, based on django's contrib auth user model.""" 393 394 # Overwriting PermissionsMixin: permissions are handled by roles. 395 # (This knowingly violates the Liskov substitution principle. It is better to fail loudly.) 396 user_permissions = None 397 398 uuid = models.UUIDField(default=uuid4, editable=False, unique=True) 399 name = models.TextField(help_text=_("User's display name.")) 400 path = models.TextField(default="users") 401 type = models.TextField(choices=UserTypes.choices, default=UserTypes.INTERNAL) 402 403 sources = models.ManyToManyField("Source", through="UserSourceConnection") 404 groups = models.ManyToManyField("Group", related_name="users", through="UserGroup") 405 roles = models.ManyToManyField( 406 "authentik_rbac.Role", related_name="users", blank=True, through="UserRole" 407 ) 408 409 last_updated = models.DateTimeField(auto_now=True) 410 411 objects = UserManager() 412 413 class Meta: 414 verbose_name = _("User") 415 verbose_name_plural = _("Users") 416 permissions = [ 417 ("reset_user_password", _("Reset Password")), 418 ("impersonate", _("Can impersonate other users")), 419 ("preview_user", _("Can preview user data sent to providers")), 420 ("view_user_applications", _("View applications the user has access to")), 421 ] 422 indexes = [ 423 models.Index(fields=["last_login"]), 424 models.Index(fields=["uuid"]), 425 models.Index(fields=["path"]), 426 models.Index(fields=["type"]), 427 models.Index(fields=["date_joined"]), 428 models.Index(fields=["last_updated"]), 429 models.Index(fields=["username", "is_active", "type"]), 430 models.Index(Upper("email"), name="%(app_label)s_%(class)s_email_idx"), 431 ] 432 433 def __str__(self): 434 return self.username 435 436 @staticmethod 437 def default_path() -> str: 438 """Get the default user path""" 439 return User._meta.get_field("path").default 440 441 def all_groups(self) -> QuerySet[Group]: 442 """Recursively get all groups this user is a member of.""" 443 return self.groups.all().with_ancestors() 444 445 def all_roles(self) -> QuerySet[Role]: 446 """Get all roles of this user and all of its groups (recursively).""" 447 return Role.objects.filter(Q(users=self) | Q(groups__in=self.all_groups())).distinct() 448 449 def get_managed_role(self, create=False): 450 if create: 451 name = managed_role_name(self) 452 role, created = Role.objects.get_or_create(name=name, managed=name) 453 if created: 454 role.users.add(self) 455 return role 456 else: 457 return Role.objects.filter(name=managed_role_name(self)).first() 458 459 def get_all_model_perms_on_managed_role(self) -> QuerySet[RoleModelPermission]: 460 role = self.get_managed_role() 461 if not role: 462 return RoleModelPermission.objects.none() 463 return RoleModelPermission.objects.filter(role=role) 464 465 def get_all_obj_perms_on_managed_role(self) -> QuerySet[RoleObjectPermission]: 466 role = self.get_managed_role() 467 if not role: 468 return RoleObjectPermission.objects.none() 469 return RoleObjectPermission.objects.filter(role=role) 470 471 def assign_perms_to_managed_role( 472 self, 473 perms: str | list[str] | Permission | list[Permission], 474 obj: models.Model | None = None, 475 ): 476 if not perms: 477 return 478 role = self.get_managed_role(create=True) 479 role.assign_perms(perms, obj) 480 481 def remove_perms_from_managed_role( 482 self, 483 perms: str | list[str] | Permission | list[Permission], 484 obj: models.Model | None = None, 485 ): 486 role = self.get_managed_role() 487 if not role: 488 return None 489 role.remove_perms(perms, obj) 490 491 def remove_all_perms_from_managed_role(self): 492 role = self.get_managed_role() 493 if not role: 494 return None 495 RoleModelPermission.objects.filter(role=role).delete() 496 RoleObjectPermission.objects.filter(role=role).delete() 497 498 def group_attributes(self, request: HttpRequest | None = None) -> dict[str, Any]: 499 """Get a dictionary containing the attributes from all groups the user belongs to, 500 including the users attributes""" 501 final_attributes = {} 502 if request and hasattr(request, "brand"): 503 always_merger.merge(final_attributes, request.brand.attributes) 504 for group in self.all_groups().order_by("name"): 505 always_merger.merge(final_attributes, group.attributes) 506 always_merger.merge(final_attributes, self.attributes) 507 return final_attributes 508 509 def app_entitlements(self, app: Application | None) -> QuerySet[ApplicationEntitlement]: 510 """Get all entitlements this user has for `app`.""" 511 if not app: 512 return ApplicationEntitlement.objects.none() 513 return self.all_app_entitlements().filter(app=app) 514 515 def all_app_entitlements(self) -> QuerySet[ApplicationEntitlement]: 516 """Get all entitlements this user is assigned, regardless of access to the application.""" 517 all_groups = self.all_groups() 518 return ( 519 ApplicationEntitlement.objects.filter( 520 Q( 521 Q(bindings__user=self) | Q(bindings__group__in=all_groups), 522 bindings__negate=False, 523 ) 524 | Q( 525 Q(~Q(bindings__user=self), bindings__user__isnull=False) 526 | Q(~Q(bindings__group__in=all_groups), bindings__group__isnull=False), 527 bindings__negate=True, 528 ), 529 bindings__enabled=True, 530 ) 531 .distinct() 532 .order_by("name") 533 ) 534 535 def app_entitlements_attributes(self, app: Application | None) -> dict: 536 """Get a dictionary containing all merged attributes from app entitlements for `app`.""" 537 final_attributes = {} 538 for attrs in self.app_entitlements(app).values_list("attributes", flat=True): 539 always_merger.merge(final_attributes, attrs) 540 return final_attributes 541 542 @property 543 def serializer(self) -> Serializer: 544 from authentik.core.api.users import UserSerializer 545 546 return UserSerializer 547 548 @cached_property 549 def is_superuser(self) -> bool: 550 """Get supseruser status based on membership in a group with superuser status""" 551 return self.all_groups().filter(is_superuser=True).exists() 552 553 @property 554 def is_staff(self) -> bool: 555 """superuser == staff user""" 556 return self.is_superuser # type: ignore 557 558 # TODO: remove this after 2026. 559 @property 560 def ak_groups(self): 561 """This is a proxy for a renamed, deprecated field.""" 562 from authentik.events.models import Event 563 564 deprecation = "authentik.core.models.User.ak_groups" 565 replacement = "authentik.core.models.User.groups" 566 message_logger = ( 567 f"{deprecation} is deprecated and will be removed in a future version of " 568 f"authentik. Please use {replacement} instead." 569 ) 570 message_event = ( 571 f"{message_logger} This event will not be repeated until it expires (by " 572 "default: in 30 days). See authentik logs for every will invocation of this " 573 "deprecation." 574 ) 575 stacktrace = traceback.format_stack() 576 # The last line is this function, the next-to-last line is its caller 577 cause = stacktrace[-2] if len(stacktrace) > 1 else "Unknown, see stacktrace in logs" 578 if search := re.search(r'"(.*?)"', cause): 579 cause = f"Property mapping or Expression policy named {search.group(1)}" 580 581 LOGGER.warning( 582 "deprecation used", 583 message=message_logger, 584 deprecation=deprecation, 585 replacement=replacement, 586 cause=cause, 587 stacktrace=stacktrace, 588 ) 589 Event.log_deprecation( 590 deprecation, message=message_event, cause=cause, replacement=replacement 591 ) 592 return self.groups 593 594 # Passwords are written through authentik.stages.password.models.PasswordDevice. 595 # These read-only properties keep `user.password` and `user.password_change_date` 596 # working in expressions, Django's session hash and the user API. 597 @property 598 def password(self) -> str: 599 device = getattr(self, "password_device", None) 600 return device.password if device else UNUSABLE_PASSWORD_PREFIX 601 602 @property 603 def password_change_date(self) -> datetime: 604 device = getattr(self, "password_device", None) 605 return device.password_change_date if device else self.date_joined 606 607 def check_password(self, raw_password: str) -> bool: 608 # Django's version writes `password` when it upgrades an outdated hash. 609 device = getattr(self, "password_device", None) 610 return device.check_password(raw_password) if device else False 611 612 async def acheck_password(self, raw_password: str) -> bool: 613 return await sync_to_async(self.check_password)(raw_password) 614 615 # Django's password writes would assign the read-only `password`; fail loudly instead. 616 def set_password(self, raw_password): 617 raise NotImplementedError("Use PasswordDevice.set_password()") 618 619 def set_unusable_password(self): 620 raise NotImplementedError("Use PasswordDevice.set_unusable_password()") 621 622 @property 623 def uid(self) -> str: 624 """Generate a globally unique UID, based on the user ID and the hashed secret key""" 625 return sha256(f"{self.id}-{get_install_id()}".encode("ascii")).hexdigest() 626 627 def locale(self, request: HttpRequest | None = None) -> str: 628 """Get the locale the user has configured""" 629 try: 630 locale = self.attributes.get("settings", {}).get("locale", "") 631 if locale: 632 return locale 633 except Exception as exc: # noqa 634 LOGGER.warning("Failed to get default locale", exc=exc) 635 if request and hasattr(request, "LANGUAGE_CODE"): 636 return request.LANGUAGE_CODE 637 return "" 638 639 @property 640 def avatar(self) -> str: 641 """Get avatar, depending on authentik.avatar setting""" 642 return get_avatar(self) 643 644 645def get_init_anonymous_user(user_model: type[User]) -> User: 646 """Build guardian's anonymous user, which has no password device and so no password. 647 648 guardian's default calls `set_unusable_password()`, which needs a writable `password`.""" 649 return user_model(username=settings.ANONYMOUS_USER_NAME) 650 651 652class Provider(SerializerModel): 653 """Application-independent Provider instance. For example SAML2 Remote, OAuth2 Application""" 654 655 name = models.TextField(unique=True) 656 657 authentication_flow = models.ForeignKey( 658 "authentik_flows.Flow", 659 null=True, 660 on_delete=models.SET_NULL, 661 help_text=_( 662 "Flow used for authentication when the associated application is accessed by an " 663 "un-authenticated user." 664 ), 665 related_name="provider_authentication", 666 ) 667 authorization_flow = models.ForeignKey( 668 "authentik_flows.Flow", 669 # Set to cascade even though null is allowed, since most providers 670 # still require an authorization flow set 671 on_delete=models.CASCADE, 672 null=True, 673 help_text=_("Flow used when authorizing this provider."), 674 related_name="provider_authorization", 675 ) 676 invalidation_flow = models.ForeignKey( 677 "authentik_flows.Flow", 678 on_delete=models.SET_DEFAULT, 679 default=None, 680 null=True, 681 help_text=_("Flow used ending the session from a provider."), 682 related_name="provider_invalidation", 683 ) 684 685 property_mappings = models.ManyToManyField( 686 "PropertyMapping", default=None, blank=True, through="ProviderPropertyMapping" 687 ) 688 689 backchannel_application = models.ForeignKey( 690 "Application", 691 default=None, 692 null=True, 693 on_delete=models.CASCADE, 694 help_text=_( 695 "Accessed from applications; optional backchannel providers for protocols " 696 "like LDAP and SCIM." 697 ), 698 related_name="backchannel_providers", 699 ) 700 701 is_backchannel = models.BooleanField(default=False) 702 703 objects = InheritanceManager() 704 705 @property 706 def launch_url(self) -> str | None: 707 """URL to this provider and initiate authorization for the user. 708 Can return None for providers that are not URL-based""" 709 return None 710 711 @property 712 def icon_url(self) -> str | None: 713 return None 714 715 @property 716 def component(self) -> str: 717 """Return component used to edit this object""" 718 raise NotImplementedError 719 720 @property 721 def serializer(self) -> type[Serializer]: 722 """Get serializer for this model""" 723 raise NotImplementedError 724 725 def __str__(self): 726 return str(self.name) 727 728 729class BackchannelProvider(Provider): 730 """Base class for providers that augment other providers, for example LDAP and SCIM. 731 Multiple of these providers can be configured per application, they may not use the application 732 slug in URLs as an application may have multiple instances of the same 733 type of Backchannel provider 734 735 They can use the application's policies and metadata""" 736 737 @property 738 def component(self) -> str: 739 raise NotImplementedError 740 741 @property 742 def serializer(self) -> type[Serializer]: 743 raise NotImplementedError 744 745 class Meta: 746 abstract = True 747 748 749class ApplicationQuerySet(QuerySet): 750 def with_provider(self) -> QuerySet[Application]: 751 """Load each application's provider as its concrete subclass, so get_provider() needs 752 no query. 753 754 The providers come from a second query rather than a join: selecting every provider 755 subclass, and the applications related to each, through the application query made a 756 statement of about 70 joins that Postgres took over 100ms to plan. 757 758 The provider is prefetched before any other lookup, so lookups through it such as 759 `provider__property_mappings` work on the concrete providers whether they were added 760 before or after, and calling this again adds nothing.""" 761 provider = Prefetch("provider", queryset=Provider.objects.select_subclasses()) 762 # Prefetches are equal when they prefetch to the same attribute 763 lookups = [lookup for lookup in self._prefetch_related_lookups if lookup != provider] 764 return self.prefetch_related(None).prefetch_related(provider, *lookups) 765 766 767class Application(RequestableModel, SerializerModel, PolicyBindingModel): 768 """Every Application which uses authentik for authentication/identification/authorization 769 needs an Application record. Other authentication types can subclass this Model to 770 add custom fields and other properties""" 771 772 name = models.TextField(help_text=_("Application's display Name.")) 773 slug = models.TextField( 774 validators=[validate_slug], 775 help_text=_("Internal application name, used in URLs."), 776 unique=True, 777 ) 778 group = models.TextField(blank=True, default="") 779 780 provider = models.OneToOneField( 781 "Provider", null=True, blank=True, default=None, on_delete=models.SET_DEFAULT 782 ) 783 784 meta_launch_url = models.TextField( 785 default="", blank=True, validators=[DomainlessFormattedURLValidator()] 786 ) 787 788 open_in_new_tab = models.BooleanField( 789 default=False, help_text=_("Open launch URL in a new browser tab or window.") 790 ) 791 792 meta_icon = FileField(default="", blank=True) 793 meta_description = models.TextField(default="", blank=True) 794 meta_publisher = models.TextField(default="", blank=True) 795 meta_hide = models.BooleanField( 796 default=False, help_text=_("Hide this application from the user's My applications page.") 797 ) 798 799 objects = ApplicationQuerySet.as_manager() 800 801 # Reserved slugs that would clash with OAuth2 provider endpoints 802 reserved_slugs = ["authorize", "token", "device", "userinfo", "introspect", "revoke"] 803 804 @property 805 def serializer(self) -> Serializer: 806 from authentik.core.api.applications import ApplicationSerializer 807 808 return ApplicationSerializer 809 810 @property 811 def get_meta_icon(self) -> str | None: 812 """Get the URL to the App Icon image""" 813 if not self.meta_icon: 814 return None 815 816 return get_file_manager(FileUsage.MEDIA).file_url(self.meta_icon) 817 818 @property 819 def get_meta_icon_themed_urls(self) -> dict[str, str] | None: 820 """Get themed URLs for meta_icon if it contains %(theme)s or is a built-in source icon""" 821 if not self.meta_icon: 822 return None 823 824 return get_file_manager(FileUsage.MEDIA).themed_urls(self.meta_icon) 825 826 def get_launch_url( 827 self, user: User | None = None, user_data: Callable[[], dict] | None = None 828 ) -> str | None: 829 """Get launch URL if set, otherwise attempt to get launch URL based on provider. 830 831 Args: 832 user: User whose data fills the URL's `%(name)s` placeholders 833 user_data: Returns `user` serialized, for a caller that formats many URLs for the 834 same user. Called only for a URL with placeholders. 835 """ 836 from authentik.core.api.users import UserSerializer 837 838 url = None 839 if self.meta_launch_url: 840 url = self.meta_launch_url 841 elif provider := self.get_provider(): 842 url = provider.launch_url 843 # Serializing the user queries their groups, roles and avatar, so it happens only for a 844 # URL with placeholders 845 if not user or not url or "%(" not in url: 846 return url 847 # Escape every `%` that is neither a placeholder nor `%%`, such as percent-encoding, so 848 # it is kept as is instead of being filled with the whole user 849 template = re.sub(r"(%%|%\()|%", lambda match: match.group(1) or "%%", url) 850 try: 851 data = user_data() if user_data else UserSerializer(instance=user).data 852 launch_url = template % data 853 except Exception as exc: # noqa 854 LOGGER.warning("Failed to format launch url", exc=exc) 855 return url 856 if url.startswith("/"): 857 launch_url = iri_to_uri(launch_url) 858 # Substitutions must preserve the root-relative URL accepted by the validator. 859 if not DomainlessFormattedURLValidator.relative_re.match(launch_url): 860 return None 861 return launch_url 862 863 def get_provider(self) -> Provider | None: 864 """Get casted provider instance. Needs Application queryset with_provider""" 865 if hasattr(self, "_cached_provider"): 866 return self._cached_provider 867 if not self.provider: 868 self._cached_provider = None 869 return None 870 self._cached_provider = get_deepest_child(self.provider) 871 return self._cached_provider 872 873 def backchannel_provider_for[T: Provider](self, provider_type: type[T], **kwargs) -> T | None: 874 """Get Backchannel provider for a specific type""" 875 provider: BackchannelProvider | None = self.backchannel_providers.filter( 876 **{f"{provider_type._meta.model_name}__isnull": False}, 877 **kwargs, 878 ).first() 879 return getattr(provider, provider_type._meta.model_name) if provider else None 880 881 def __str__(self): 882 return str(self.name) 883 884 def requestable_child_model_types(self): 885 return [ApplicationEntitlement] 886 887 class Meta: 888 verbose_name = _("Application") 889 verbose_name_plural = _("Applications") 890 891 892class ApplicationEntitlement( 893 RequestableChildModel, AttributesMixin, SerializerModel, PolicyBindingModel 894): 895 """Application-scoped entitlement to control authorization in an application""" 896 897 name = models.TextField() 898 899 app = models.ForeignKey(Application, on_delete=models.CASCADE) 900 901 class Meta: 902 verbose_name = _("Application Entitlement") 903 verbose_name_plural = _("Application Entitlements") 904 unique_together = (("app", "name"),) 905 906 def __str__(self): 907 return f"Application Entitlement {self.name} for app {self.app_id}" 908 909 @property 910 def requestable_parent(self) -> Application: 911 return self.app 912 913 @property 914 def requestable_label(self): 915 return self.name 916 917 @property 918 def serializer(self) -> type[Serializer]: 919 from authentik.core.api.application_entitlements import ApplicationEntitlementSerializer 920 921 return ApplicationEntitlementSerializer 922 923 def supported_policy_binding_targets(self): 924 return ["group", "user"] 925 926 927class SourceUserMatchingModes(models.TextChoices): 928 """Different modes a source can handle new/returning users""" 929 930 IDENTIFIER = "identifier", _("Use the source-specific identifier") 931 EMAIL_LINK = ( 932 "email_link", 933 _( 934 "Link to a user with identical email address. Can have security implications " 935 "when a source doesn't validate email addresses." 936 ), 937 ) 938 EMAIL_DENY = ( 939 "email_deny", 940 _( 941 "Use the user's email address, but deny enrollment when the email address already " 942 "exists." 943 ), 944 ) 945 USERNAME_LINK = ( 946 "username_link", 947 _( 948 "Link to a user with identical username. Can have security implications " 949 "when a username is used with another source." 950 ), 951 ) 952 USERNAME_DENY = ( 953 "username_deny", 954 _("Use the user's username, but deny enrollment when the username already exists."), 955 ) 956 957 958class SourceGroupMatchingModes(models.TextChoices): 959 """Different modes a source can handle new/returning groups""" 960 961 IDENTIFIER = "identifier", _("Use the source-specific identifier") 962 NAME_LINK = ( 963 "name_link", 964 _( 965 "Link to a group with identical name. Can have security implications " 966 "when a group name is used with another source." 967 ), 968 ) 969 NAME_DENY = ( 970 "name_deny", 971 _("Use the group name, but deny enrollment when the name already exists."), 972 ) 973 974 975class Source(ManagedModel, SerializerModel, PolicyBindingModel): 976 """Base Authentication source, i.e. an OAuth Provider, SAML Remote or LDAP Server""" 977 978 MANAGED_INBUILT = "goauthentik.io/sources/inbuilt" 979 980 name = models.TextField(help_text=_("Source's display Name.")) 981 slug = models.TextField( 982 validators=[validate_slug], 983 help_text=_("Internal source name, used in URLs."), 984 unique=True, 985 ) 986 987 user_path_template = models.TextField(default="goauthentik.io/sources/%(slug)s") 988 989 enabled = models.BooleanField(default=True) 990 promoted = models.BooleanField( 991 default=False, 992 help_text=_( 993 "When enabled, this source will be displayed as a prominent button on the " 994 "login page, instead of a small icon." 995 ), 996 ) 997 user_property_mappings = models.ManyToManyField( 998 "PropertyMapping", 999 default=None, 1000 blank=True, 1001 related_name="source_userpropertymappings_set", 1002 through="SourceUserPropertyMapping", 1003 ) 1004 group_property_mappings = models.ManyToManyField( 1005 "PropertyMapping", 1006 default=None, 1007 blank=True, 1008 related_name="source_grouppropertymappings_set", 1009 through="SourceGroupPropertyMapping", 1010 ) 1011 1012 icon = FileField(blank=True, default="") 1013 1014 authentication_flow = models.ForeignKey( 1015 "authentik_flows.Flow", 1016 blank=True, 1017 null=True, 1018 default=None, 1019 on_delete=models.SET_NULL, 1020 help_text=_("Flow to use when authenticating existing users."), 1021 related_name="source_authentication", 1022 ) 1023 enrollment_flow = models.ForeignKey( 1024 "authentik_flows.Flow", 1025 blank=True, 1026 null=True, 1027 default=None, 1028 on_delete=models.SET_NULL, 1029 help_text=_("Flow to use when enrolling new users."), 1030 related_name="source_enrollment", 1031 ) 1032 1033 user_matching_mode = models.TextField( 1034 choices=SourceUserMatchingModes.choices, 1035 default=SourceUserMatchingModes.IDENTIFIER, 1036 help_text=_( 1037 "How the source determines if an existing user should be authenticated or " 1038 "a new user enrolled." 1039 ), 1040 ) 1041 group_matching_mode = models.TextField( 1042 choices=SourceGroupMatchingModes.choices, 1043 default=SourceGroupMatchingModes.IDENTIFIER, 1044 help_text=_( 1045 "How the source determines if an existing group should be used or a new group created." 1046 ), 1047 ) 1048 1049 objects = InheritanceManager() 1050 1051 def get_icon_url(self, request=None, use_cache: bool = True) -> str | None: 1052 """Get the URL to the source icon.""" 1053 if not self.icon: 1054 return None 1055 return get_file_manager(FileUsage.MEDIA).file_url(self.icon, request, use_cache=use_cache) 1056 1057 @property 1058 def icon_url(self) -> str | None: 1059 """Get the URL to the source icon""" 1060 return self.get_icon_url() 1061 1062 def get_icon_themed_urls( 1063 self, 1064 request=None, 1065 use_cache: bool = True, 1066 ) -> dict[str, str] | None: 1067 """Get themed URLs for the icon if it contains %(theme)s or is a built-in source icon.""" 1068 if not self.icon: 1069 # Subclasses fall back to a built-in default icon, relative like their icon_url 1070 return get_file_manager(FileUsage.MEDIA).themed_urls(static_url_name(self.icon_url)) 1071 return get_file_manager(FileUsage.MEDIA).themed_urls( 1072 self.icon, 1073 request, 1074 use_cache=use_cache, 1075 ) 1076 1077 @property 1078 def icon_themed_urls(self) -> dict[str, str] | None: 1079 return self.get_icon_themed_urls() 1080 1081 def get_user_path(self) -> str: 1082 """Get user path, fallback to default for formatting errors""" 1083 try: 1084 return self.user_path_template % { 1085 "slug": self.slug, 1086 } 1087 1088 except Exception as exc: # noqa 1089 LOGGER.warning("Failed to template user path", exc=exc, source=self) 1090 return User.default_path() 1091 1092 @property 1093 def component(self) -> str: 1094 """Return component used to edit this object""" 1095 if self.managed == self.MANAGED_INBUILT: 1096 return "" 1097 raise NotImplementedError 1098 1099 @property 1100 def property_mapping_type(self) -> type[PropertyMapping]: 1101 """Return property mapping type used by this object""" 1102 if self.managed == self.MANAGED_INBUILT: 1103 from authentik.core.models import PropertyMapping 1104 1105 return PropertyMapping 1106 raise NotImplementedError 1107 1108 def ui_login_button(self, request: HttpRequest) -> UILoginButton | None: 1109 """If source uses a http-based flow, return UI Information about the login 1110 button. If source doesn't use http-based flow, return None.""" 1111 return None 1112 1113 def ui_user_settings(self) -> UserSettingSerializer | None: 1114 """Entrypoint to integrate with User settings. Can either return None if no 1115 user settings are available, or UserSettingSerializer.""" 1116 return None 1117 1118 def get_base_user_properties(self, **kwargs) -> dict[str, Any | dict[str, Any]]: 1119 """Get base properties for a user to build final properties upon.""" 1120 if self.managed == self.MANAGED_INBUILT: 1121 return {} 1122 raise NotImplementedError 1123 1124 def get_base_group_properties(self, **kwargs) -> dict[str, Any | dict[str, Any]]: 1125 """Get base properties for a group to build final properties upon.""" 1126 if self.managed == self.MANAGED_INBUILT: 1127 return {} 1128 raise NotImplementedError 1129 1130 def __str__(self): 1131 return str(self.name) 1132 1133 class Meta: 1134 indexes = [ 1135 models.Index( 1136 fields=[ 1137 "slug", 1138 ] 1139 ), 1140 models.Index( 1141 fields=[ 1142 "name", 1143 ] 1144 ), 1145 models.Index( 1146 fields=[ 1147 "enabled", 1148 ] 1149 ), 1150 ] 1151 1152 1153class UserSourceConnection(SerializerModel, CreatedUpdatedModel): 1154 """Connection between User and Source.""" 1155 1156 user = models.ForeignKey(User, on_delete=models.CASCADE) 1157 source = models.ForeignKey(Source, on_delete=models.CASCADE) 1158 identifier = models.TextField() 1159 1160 objects = InheritanceManager() 1161 1162 @property 1163 def serializer(self) -> type[Serializer]: 1164 """Get serializer for this model""" 1165 raise NotImplementedError 1166 1167 def __str__(self) -> str: 1168 return f"User-source connection (user={self.user_id}, source={self.source_id})" 1169 1170 class Meta: 1171 unique_together = (("user", "source"),) 1172 indexes = ( 1173 models.Index(fields=("identifier",)), 1174 models.Index(fields=("source", "identifier")), 1175 ) 1176 1177 1178class GroupSourceConnection(SerializerModel, CreatedUpdatedModel): 1179 """Connection between Group and Source.""" 1180 1181 group = models.ForeignKey(Group, on_delete=models.CASCADE) 1182 source = models.ForeignKey(Source, on_delete=models.CASCADE) 1183 identifier = models.TextField() 1184 1185 objects = InheritanceManager() 1186 1187 @property 1188 def serializer(self) -> type[Serializer]: 1189 """Get serializer for this model""" 1190 raise NotImplementedError 1191 1192 def __str__(self) -> str: 1193 return f"Group-source connection (group={self.group_id}, source={self.source_id})" 1194 1195 class Meta: 1196 unique_together = (("group", "source"),) 1197 1198 1199class TokenIntents(models.TextChoices): 1200 """Intents a Token can be created for.""" 1201 1202 # Single use token 1203 INTENT_VERIFICATION = "verification" 1204 1205 # Allow access to API 1206 INTENT_API = "api" 1207 1208 # Recovery use for the recovery app 1209 INTENT_RECOVERY = "recovery" 1210 1211 # App-specific passwords 1212 INTENT_APP_PASSWORD = "app_password" # nosec 1213 1214 1215class Token(SerializerModel, ManagedModel, ExpiringModel): 1216 """Token used to authenticate the User for API Access or confirm another Stage like Email.""" 1217 1218 token_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 1219 identifier = models.SlugField(max_length=255, unique=True) 1220 key = models.TextField(default=default_token_key) 1221 intent = models.TextField( 1222 choices=TokenIntents.choices, default=TokenIntents.INTENT_VERIFICATION 1223 ) 1224 user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="+") 1225 description = models.TextField(default="", blank=True) 1226 1227 class Meta: 1228 verbose_name = _("Token") 1229 verbose_name_plural = _("Tokens") 1230 indexes = ExpiringModel.Meta.indexes + [ 1231 models.Index(fields=["identifier"]), 1232 models.Index(fields=["key"]), 1233 ] 1234 permissions = [ 1235 ("view_token_key", _("View token's key")), 1236 ("set_token_key", _("Set a token's key")), 1237 ] 1238 1239 def __str__(self): 1240 description = f"{self.identifier}" 1241 if self.expiring: 1242 description += f" (expires={self.expires})" 1243 return description 1244 1245 @property 1246 def serializer(self) -> type[Serializer]: 1247 from authentik.core.api.tokens import TokenSerializer 1248 1249 return TokenSerializer 1250 1251 def expire_action(self, *args, **kwargs): 1252 """Handler which is called when this object is expired.""" 1253 from authentik.events.models import Event, EventAction 1254 1255 if ( 1256 self.intent 1257 in [ 1258 TokenIntents.INTENT_RECOVERY, 1259 TokenIntents.INTENT_VERIFICATION, 1260 TokenIntents.INTENT_APP_PASSWORD, 1261 ] 1262 or Actor.objects.filter(pk=self.user_id).exists() 1263 ): 1264 super().expire_action(*args, **kwargs) 1265 return 1266 1267 self.key = default_token_key() 1268 self.expires = default_token_duration() 1269 self.save(*args, **kwargs) 1270 Event.new( 1271 action=EventAction.SECRET_ROTATE, 1272 token=self, 1273 message=f"Token {self.identifier}'s secret was rotated.", 1274 ).save() 1275 1276 1277class PropertyMapping(SerializerModel, ManagedModel): 1278 """User-defined key -> x mapping which can be used by providers to expose extra data.""" 1279 1280 pm_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 1281 name = models.TextField(unique=True) 1282 expression = models.TextField() 1283 1284 objects = InheritanceManager() 1285 1286 # Types the expression may return (besides None); empty allows any type 1287 expression_allowed_types: list[type] = [] 1288 1289 @property 1290 def component(self) -> str: 1291 """Return component used to edit this object""" 1292 raise NotImplementedError 1293 1294 @property 1295 def serializer(self) -> type[Serializer]: 1296 """Get serializer for this model""" 1297 raise NotImplementedError 1298 1299 def evaluate( 1300 self, 1301 user: User | None, 1302 request: HttpRequest | None, 1303 globals: dict[str, Any] | None = None, 1304 **kwargs, 1305 ) -> Any: 1306 """Evaluate `self.expression` using `**kwargs` as Context.""" 1307 from authentik.core.expression.evaluator import PropertyMappingEvaluator 1308 1309 evaluator = PropertyMappingEvaluator(self, user, request, **kwargs) 1310 evaluator.allowed_types = self.expression_allowed_types 1311 if globals: 1312 evaluator._globals.update(globals) 1313 try: 1314 return evaluator.evaluate(self.expression) 1315 except ControlFlowException as exc: 1316 raise exc 1317 except Exception as exc: 1318 raise PropertyMappingExpressionException(exc, self) from exc 1319 1320 def __str__(self): 1321 return f"Property Mapping {self.name}" 1322 1323 class Meta: 1324 verbose_name = _("Property Mapping") 1325 verbose_name_plural = _("Property Mappings") 1326 1327 1328class SourceUserPropertyMapping(SimpleThroughModel): 1329 property_mapping = models.ForeignKey( 1330 PropertyMapping, on_delete=models.CASCADE, db_column="propertymapping_id" 1331 ) 1332 source = models.ForeignKey(Source, on_delete=models.CASCADE) 1333 1334 class Meta: 1335 db_table = "authentik_core_source_user_property_mappings" 1336 unique_together = (("property_mapping", "source"),) 1337 verbose_name = _("Source User Property Mapping") 1338 verbose_name_plural = _("Source User Property Mappings") 1339 1340 def __str__(self): 1341 return ( 1342 f"SourceUserPropertyMapping for Source {self.source_id} " 1343 f"and PropertyMapping {self.property_mapping_id}." 1344 ) 1345 1346 1347class SourceGroupPropertyMapping(SimpleThroughModel): 1348 property_mapping = models.ForeignKey( 1349 PropertyMapping, on_delete=models.CASCADE, db_column="propertymapping_id" 1350 ) 1351 source = models.ForeignKey(Source, on_delete=models.CASCADE) 1352 1353 class Meta: 1354 db_table = "authentik_core_source_group_property_mappings" 1355 unique_together = (("property_mapping", "source"),) 1356 verbose_name = _("Source Group Property Mapping") 1357 verbose_name_plural = _("Source Group Property Mappings") 1358 1359 def __str__(self): 1360 return ( 1361 f"SourceGroupPropertyMapping for Source {self.source_id} " 1362 f"and PropertyMapping {self.property_mapping_id}." 1363 ) 1364 1365 1366class ProviderPropertyMapping(SimpleThroughModel): 1367 property_mapping = models.ForeignKey( 1368 PropertyMapping, on_delete=models.CASCADE, db_column="propertymapping_id" 1369 ) 1370 provider = models.ForeignKey(Provider, on_delete=models.CASCADE) 1371 1372 class Meta: 1373 db_table = "authentik_core_provider_property_mappings" 1374 unique_together = (("property_mapping", "provider"),) 1375 verbose_name = _("Provider Property Mapping") 1376 verbose_name_plural = _("Provider Property Mappings") 1377 1378 def __str__(self): 1379 return ( 1380 f"ProviderPropertyMapping for Provider {self.provider_id} " 1381 f"and PropertyMapping {self.property_mapping_id}." 1382 ) 1383 1384 1385class UserRole(SimpleThroughModel): 1386 user = models.ForeignKey(User, on_delete=models.CASCADE) 1387 role = models.ForeignKey(Role, on_delete=models.CASCADE) 1388 1389 class Meta: 1390 db_table = "authentik_core_user_roles" 1391 unique_together = (("user", "role"),) 1392 verbose_name = _("User Role") 1393 verbose_name_plural = _("User Roles") 1394 1395 def __str__(self): 1396 return f"UserRole for User {self.user_id} and Role {self.role_id}." 1397 1398 1399class GroupRole(SimpleThroughModel): 1400 group = models.ForeignKey(Group, on_delete=models.CASCADE) 1401 role = models.ForeignKey(Role, on_delete=models.CASCADE) 1402 1403 class Meta: 1404 db_table = "authentik_core_group_roles" 1405 unique_together = (("group", "role"),) 1406 verbose_name = _("Group Role") 1407 verbose_name_plural = _("Group Roles") 1408 1409 def __str__(self): 1410 return f"GroupRole for Group {self.group_id} and Role {self.role_id}." 1411 1412 1413class UserGroup(SimpleThroughModel): 1414 user = models.ForeignKey(User, on_delete=models.CASCADE) 1415 group = models.ForeignKey(Group, on_delete=models.CASCADE) 1416 1417 class Meta: 1418 db_table = "authentik_core_user_groups" 1419 unique_together = (("user", "group"),) 1420 verbose_name = _("User Group") 1421 verbose_name_plural = _("User Groups") 1422 1423 def __str__(self): 1424 return f"UserGroup for User {self.user_id} and Group {self.group_id}." 1425 1426 1427class Session(ExpiringModel, AbstractBaseSession): 1428 """User session with extra fields for fast access""" 1429 1430 # Remove upstream field because we're using our own ExpiringModel 1431 expire_date = None 1432 session_data = models.BinaryField(_("session data")) 1433 1434 # Keep in sync with Session.Keys 1435 last_ip = models.GenericIPAddressField() 1436 last_user_agent = models.TextField(blank=True) 1437 last_used = models.DateTimeField(auto_now=True) 1438 1439 class Meta: 1440 verbose_name = _("Session") 1441 verbose_name_plural = _("Sessions") 1442 indexes = ExpiringModel.Meta.indexes + [ 1443 models.Index(fields=["expires", "session_key"]), 1444 ] 1445 default_permissions = [] 1446 1447 def __str__(self): 1448 return self.session_key 1449 1450 class Keys(StrEnum): 1451 """ 1452 Keys to be set with the session interface for the fields above to be updated. 1453 1454 If a field is added here that needs to be initialized when the session is initialized, 1455 it must also be reflected in authentik.root.middleware.SessionMiddleware.process_request 1456 and in authentik.core.sessions.SessionStore.__init__ 1457 """ 1458 1459 LAST_IP = "last_ip" 1460 LAST_USER_AGENT = "last_user_agent" 1461 LAST_USED = "last_used" 1462 1463 @classmethod 1464 def get_session_store_class(cls): 1465 from authentik.core.sessions import SessionStore 1466 1467 return SessionStore 1468 1469 def get_decoded(self): 1470 raise NotImplementedError 1471 1472 1473class UserSwitchingSession(models.Model): 1474 """Sessions grouped by one browser's user-switching cookie.""" 1475 1476 token = models.CharField(max_length=64, primary_key=True) 1477 current_session = models.OneToOneField( 1478 "authentik_core.AuthenticatedSession", 1479 null=True, 1480 on_delete=models.SET_NULL, 1481 related_name="+", 1482 ) 1483 1484 class Meta: 1485 verbose_name = _("User Switching Session") 1486 verbose_name_plural = _("User Switching Sessions") 1487 default_permissions = [] 1488 1489 def __str__(self) -> str: 1490 return f"User Switching Session {self.token[:10]}" 1491 1492 1493class AuthenticatedSession(SerializerModel): 1494 session = models.OneToOneField(Session, on_delete=models.CASCADE, primary_key=True) 1495 # We use the session as primary key, but we need the API to be able to reference 1496 # this object uniquely without exposing the session key 1497 uuid = models.UUIDField(default=uuid4, unique=True) 1498 1499 user = models.ForeignKey(User, on_delete=models.CASCADE) 1500 1501 user_switching_session = models.ForeignKey( 1502 UserSwitchingSession, 1503 null=True, 1504 on_delete=models.SET_NULL, 1505 related_name="authenticated_sessions", 1506 ) 1507 1508 @property 1509 def is_current(self) -> bool: 1510 """Whether this is the current login for its browser.""" 1511 return ( 1512 self.user_switching_session_id is None 1513 or self.user_switching_session.current_session_id == self.session_id 1514 ) 1515 1516 @property 1517 def serializer(self) -> type[Serializer]: 1518 from authentik.core.api.authenticated_sessions import AuthenticatedSessionSerializer 1519 1520 return AuthenticatedSessionSerializer 1521 1522 @classmethod 1523 def from_request(cls, request: HttpRequest, user: User) -> Self | None: 1524 """Return an in-memory authenticated session for the request's session. 1525 1526 This does not touch the database; because ``session`` is the primary key the 1527 returned instance can be used to look up related objects. Callers that want to 1528 persist a login should use ``create_from_request`` instead.""" 1529 if not hasattr(request, "session") or not request.session.exists( 1530 request.session.session_key 1531 ): 1532 return None 1533 return cls( 1534 session=Session.objects.filter(session_key=request.session.session_key).first(), 1535 user=user, 1536 ) 1537 1538 @classmethod 1539 def create_from_request(cls, request: HttpRequest, user: User) -> Self | None: 1540 """Persist the request's session as the current login and bind the switching token.""" 1541 from authentik.core import user_switching 1542 1543 if not hasattr(request, "session") or not request.session.exists( 1544 request.session.session_key 1545 ): 1546 return None 1547 session = Session.objects.filter(session_key=request.session.session_key).first() 1548 if session is None: 1549 return None 1550 authenticated_session, _ = cls.objects.update_or_create( 1551 session=session, 1552 defaults={"user": user}, 1553 ) 1554 token = user_switching.ensure_request_token(request) 1555 if token: 1556 user_switching.activate_session(session.session_key, token) 1557 authenticated_session.user_switching_session_id = token 1558 return authenticated_session 1559 1560 class Meta: 1561 verbose_name = _("Authenticated Session") 1562 verbose_name_plural = _("Authenticated Sessions") 1563 1564 def __str__(self) -> str: 1565 return f"Authenticated Session {str(self.pk)[:10]}" 1566 1567 1568class ObjectAttribute(SerializerModel, ManagedModel, CreatedUpdatedModel): 1569 """User-defined schema for models' `attributes` JSON field.""" 1570 1571 class AttributeType(models.TextChoices): 1572 TEXT = "text" 1573 NUMBER = "number" 1574 BOOLEAN = "boolean" 1575 1576 attribute_id = models.UUIDField(default=uuid4, primary_key=True) 1577 1578 enabled = models.BooleanField(default=True) 1579 1580 object_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) 1581 label = models.TextField() 1582 group = models.TextField(blank=True) 1583 key = models.TextField() 1584 1585 type = models.TextField(choices=AttributeType.choices) 1586 is_unique = models.BooleanField(default=False) 1587 is_required = models.BooleanField(default=False) 1588 regex = models.TextField(blank=True) 1589 # Currently not accessible via API/UI, as there are some challenges UI-wise 1590 # with regards to merging data 1591 # https://github.com/goauthentik/authentik/issues/24250 1592 is_array = models.BooleanField(default=False) 1593 1594 def run_validation(self, value: Any, instance: models.Model | None = None) -> None: 1595 err_key = f"attributes_{self.key}" 1596 1597 if self.is_required and value is None: 1598 raise ValidationError({err_key: _("This field is required")}) 1599 if value is None: 1600 return 1601 1602 field_kwargs = {} 1603 1604 match self.type: 1605 case self.AttributeType.TEXT: 1606 field_cls = CharField 1607 field_kwargs["allow_blank"] = True 1608 case self.AttributeType.NUMBER: 1609 field_cls = IntegerField 1610 case self.AttributeType.BOOLEAN: 1611 field_cls = BooleanField 1612 case _: 1613 raise ValidationError("Invalid field type") 1614 1615 field = field_cls(required=False, **field_kwargs) 1616 if self.is_array: 1617 field = ListField( 1618 child=field, 1619 required=False, 1620 error_messages={"not_a_list": _("Value must be an array.")}, 1621 ) 1622 1623 try: 1624 field.run_validation(value) 1625 except ValidationError as exc: 1626 raise ValidationError({err_key: exc.detail}) from exc 1627 1628 if self.regex != "": 1629 values = value if self.is_array else [value] 1630 if not all(re.fullmatch(self.regex, str(v)) for v in values): 1631 raise ValidationError({err_key: _("Value does not match configured pattern.")}) 1632 1633 if not self.is_array and self.is_unique: 1634 model: type[models.Model] = self.object_type.model_class() 1635 lookup_key = f"attributes__{self.key.replace('.', '__')}" 1636 existing = model.objects.filter(**{lookup_key: value}) 1637 # The row being saved already has this value; uniqueness is against other objects. 1638 if instance is not None and isinstance(instance, model) and instance.pk is not None: 1639 existing = existing.exclude(pk=instance.pk) 1640 if existing.exists(): 1641 raise ValidationError({err_key: _("Value is not unique.")}) 1642 1643 @property 1644 def serializer(self) -> type[Serializer]: 1645 from authentik.core.api.object_attributes import ObjectAttributeSerializer 1646 1647 return ObjectAttributeSerializer 1648 1649 def __str__(self): 1650 return f"Object attribute '{self.key}' for content type {self.object_type_id}" 1651 1652 class Meta: 1653 verbose_name = _("Object Attribute") 1654 verbose_name_plural = _("Object Attributes") 1655 unique_together = (("object_type", "key", "enabled"),) 1656 1657 1658class ActorPolicyInheritance(models.TextChoices): 1659 1660 MIRROR = "mirror", _("Mirror policy engine") 1661 COPY = "copy", _("Copy policy bindings") 1662 NONE = "none", _("Don't inherit any policy bindings") 1663 1664 1665class Actor(ExpiringModel, User): 1666 """Generic actor which can either perform tasks by itself 1667 or on behalf of a parent user.""" 1668 1669 parent = models.ForeignKey( 1670 User, on_delete=models.SET_DEFAULT, default=None, null=True, related_name="actors" 1671 ) 1672 policy_behavior = models.TextField(choices=ActorPolicyInheritance) 1673 1674 class Meta(ExpiringModel.Meta): 1675 verbose_name = _("Actor") 1676 verbose_name_plural = _("Actors") 1677 1678 def save(self, *args, **kwargs): 1679 # policy_behavior determines how the actor derives access and may only be chosen at 1680 # creation time; changing it afterwards is rejected. 1681 if ( 1682 not self._state.adding 1683 and hasattr(self, "_original_policy_behavior") 1684 and self._original_policy_behavior != self.policy_behavior 1685 ): 1686 raise ValidationError( 1687 {"policy_behavior": _("Policy behavior cannot be changed after creation.")} 1688 ) 1689 super().save(*args, **kwargs) 1690 self._original_policy_behavior = self.policy_behavior 1691 1692 @classmethod 1693 def from_db(cls, db, field_names, values): 1694 instance = super().from_db(db, field_names, values) 1695 instance._original_policy_behavior = instance.policy_behavior 1696 return instance 1697 1698 def copy_parent_policy_bindings(self): 1699 """Snapshot the parent's directly-assigned policy bindings onto this actor. 1700 1701 Unlike MIRROR (which defers to the parent live), COPY takes an independent snapshot at 1702 creation: the actor holds its own PolicyBindings, so later changes to the parent don't 1703 affect it. Only bindings that reference the parent as a *user* are copied -- access the 1704 parent derives from group membership is not (use MIRROR, or add the actor to groups). 1705 """ 1706 from authentik.policies.models import PolicyBinding 1707 1708 if not self.parent_id: 1709 return 1710 for binding in PolicyBinding.objects.filter(user_id=self.parent_id): 1711 binding.pk = None 1712 binding.policy_binding_uuid = uuid4() 1713 binding._state.adding = True 1714 binding.user = self 1715 binding.save() 1716 1717 @staticmethod 1718 def for_user(user: User | None, policy_behavior: ActorPolicyInheritance, **kwargs): 1719 prefix = f"{user.username}" if user else "global" 1720 actor = Actor.objects.create( 1721 username=f"{prefix}-{generate_id()}"[:USERNAME_MAX_LENGTH], 1722 parent=user, 1723 policy_behavior=policy_behavior, 1724 type=UserTypes.SERVICE_ACCOUNT, 1725 **kwargs, 1726 ) 1727 return actor 1728 1729 1730class UserActivityManager(models.Manager["UserActivity"]): 1731 """Record successful activity without rewriting frequently active users.""" 1732 1733 def record(self, user_id: Any, at: datetime | None = None) -> None: 1734 if type(user_id) is not int or not 0 < user_id <= 2147483647: # noqa: PLR2004 1735 return 1736 excluded = ExcludedCol(self.model._meta.get_field("last_activity_at")) 1737 with postgres_manager(self.model) as manager: 1738 manager.on_conflict( 1739 ["user_id"], 1740 ConflictAction.UPDATE, 1741 update_condition=Q(last_activity_at__lte=excluded - USER_ACTIVITY_INTERVAL), 1742 update_values={"last_activity_at": excluded}, 1743 ).insert(user_id=user_id, last_activity_at=at or now()) 1744 1745 1746class UserActivity(models.Model): 1747 """Latest sampled successful activity, independent of audit retention.""" 1748 1749 # A late write after user deletion may leave an orphan; expiration joins existing users. 1750 user = models.OneToOneField( 1751 User, 1752 on_delete=models.CASCADE, 1753 primary_key=True, 1754 related_name="activity", 1755 db_constraint=False, 1756 ) 1757 last_activity_at = models.DateTimeField() 1758 objects = UserActivityManager() 1759 1760 def __str__(self): 1761 return f"Activity for user {self.user_id}"
98def managed_role_name(user_or_group: models.Model): 99 if isinstance(user_or_group, User): 100 return f"{MANAGED_ROLE_PREFIX_USER}-{user_or_group.pk}" 101 if isinstance(user_or_group, Group): 102 return f"{MANAGED_ROLE_PREFIX_GROUP}-{user_or_group.pk}" 103 raise TypeError("Managed roles are only available for User or Group.")
106def default_token_duration() -> datetime: 107 """Default duration a Token is valid""" 108 settings = get_system_settings() 109 token_duration = ( 110 settings.default_token_duration 111 if hasattr(settings, "default_token_duration") 112 else DEFAULT_TOKEN_DURATION 113 ) 114 return now() + timedelta_from_string(token_duration)
Default duration a Token is valid
117def default_token_key() -> str: 118 """Default token key""" 119 settings = get_system_settings() 120 token_length = ( 121 settings.default_token_length 122 if hasattr(settings, "default_token_length") 123 else DEFAULT_TOKEN_LENGTH 124 ) 125 # We use generate_id since the chars in the key should be easy 126 # to use in Emails (for verification) and URLs (for recovery) 127 return generate_id(token_length)
Default token key
130class UserTypes(models.TextChoices): 131 """User types, both for grouping, licensing and permissions in the case 132 of the internal_service_account""" 133 134 INTERNAL = "internal" 135 EXTERNAL = "external" 136 137 # User-created service accounts 138 SERVICE_ACCOUNT = "service_account" 139 140 # Special user type for internally managed and created service 141 # accounts, such as outpost users 142 INTERNAL_SERVICE_ACCOUNT = "internal_service_account"
User types, both for grouping, licensing and permissions in the case of the internal_service_account
148class AttributesMixin(models.Model): 149 """Adds an attributes property to a model""" 150 151 attributes = models.JSONField(default=dict, blank=True) 152 153 class Meta: 154 abstract = True 155 156 def update_attributes(self, properties: dict[str, Any]): 157 """Update fields and attributes, but correctly by merging dicts""" 158 needs_update = False 159 for key, value in properties.items(): 160 if key == "attributes": 161 continue 162 if getattr(self, key, None) != value: 163 setattr(self, key, value) 164 needs_update = True 165 final_attributes = {} 166 MERGE_LIST_UNIQUE.merge(final_attributes, self.attributes) 167 MERGE_LIST_UNIQUE.merge(final_attributes, properties.get("attributes", {})) 168 if self.attributes != final_attributes: 169 self.attributes = final_attributes 170 needs_update = True 171 if needs_update: 172 self.save() 173 174 @classmethod 175 def update_or_create_attributes( 176 cls, query: dict[str, Any], properties: dict[str, Any] 177 ) -> tuple[Self, bool]: 178 """Same as django's update_or_create but correctly updates attributes by merging dicts""" 179 instance = cls.objects.filter(**query).first() 180 if not instance: 181 return cls.objects.create(**properties), True 182 instance.update_attributes(properties) 183 return instance, False
Adds an attributes property to a model
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
156 def update_attributes(self, properties: dict[str, Any]): 157 """Update fields and attributes, but correctly by merging dicts""" 158 needs_update = False 159 for key, value in properties.items(): 160 if key == "attributes": 161 continue 162 if getattr(self, key, None) != value: 163 setattr(self, key, value) 164 needs_update = True 165 final_attributes = {} 166 MERGE_LIST_UNIQUE.merge(final_attributes, self.attributes) 167 MERGE_LIST_UNIQUE.merge(final_attributes, properties.get("attributes", {})) 168 if self.attributes != final_attributes: 169 self.attributes = final_attributes 170 needs_update = True 171 if needs_update: 172 self.save()
Update fields and attributes, but correctly by merging dicts
174 @classmethod 175 def update_or_create_attributes( 176 cls, query: dict[str, Any], properties: dict[str, Any] 177 ) -> tuple[Self, bool]: 178 """Same as django's update_or_create but correctly updates attributes by merging dicts""" 179 instance = cls.objects.filter(**query).first() 180 if not instance: 181 return cls.objects.create(**properties), True 182 instance.update_attributes(properties) 183 return instance, False
Same as django's update_or_create but correctly updates attributes by merging dicts
186class GroupQuerySet(QuerySet): 187 def with_descendants(self): 188 pks = self.values_list("pk", flat=True) 189 return Group.objects.filter(Q(pk__in=pks) | Q(ancestor_nodes__ancestor__in=pks)).distinct() 190 191 def with_ancestors(self): 192 pks = self.values_list("pk", flat=True) 193 return Group.objects.filter( 194 Q(pk__in=pks) | Q(descendant_nodes__descendant__in=pks) 195 ).distinct()
Represent a lazy database lookup for a set of objects.
198class Group(SerializerModel, AttributesMixin): 199 """Group model which supports a hierarchy and has attributes""" 200 201 group_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 202 203 name = models.TextField(verbose_name=_("name"), unique=True) 204 is_superuser = models.BooleanField( 205 default=False, help_text=_("Users added to this group will be superusers.") 206 ) 207 208 roles = models.ManyToManyField( 209 "authentik_rbac.Role", related_name="groups", blank=True, through="GroupRole" 210 ) 211 212 parents = models.ManyToManyField( 213 "Group", 214 blank=True, 215 symmetrical=False, 216 through="GroupParentageNode", 217 related_name="children", 218 ) 219 220 objects = GroupQuerySet.as_manager() 221 222 class Meta: 223 indexes = ( 224 models.Index(fields=["name"]), 225 models.Index(fields=["is_superuser"]), 226 ) 227 verbose_name = _("Group") 228 verbose_name_plural = _("Groups") 229 permissions = [ 230 ("add_user_to_group", _("Add user to group")), 231 ("remove_user_from_group", _("Remove user from group")), 232 ("enable_group_superuser", _("Enable superuser status")), 233 ("disable_group_superuser", _("Disable superuser status")), 234 ] 235 236 def __str__(self): 237 return f"Group {self.name}" 238 239 @property 240 def serializer(self) -> Serializer: 241 from authentik.core.api.groups import GroupSerializer 242 243 return GroupSerializer 244 245 @property 246 def num_pk(self) -> int: 247 """Get a numerical, int32 ID for the group""" 248 # int max is 2147483647 (10 digits) so 9 is the max usable 249 # in the LDAP Outpost we use the last 5 chars so match here 250 return int(str(self.pk.int)[:5]) 251 252 def is_member(self, user: User) -> bool: 253 """Recursively check if `user` is member of us, or any parent.""" 254 return user.all_groups().filter(group_uuid=self.group_uuid).exists() 255 256 def all_roles(self) -> QuerySet[Role]: 257 """Get all roles of this group and all of its ancestors.""" 258 return Role.objects.filter( 259 groups__in=Group.objects.filter(pk=self.pk).with_ancestors() 260 ).distinct() 261 262 def get_managed_role(self, create=False): 263 if create: 264 name = managed_role_name(self) 265 role, created = Role.objects.get_or_create(name=name, managed=name) 266 if created: 267 role.groups.add(self) 268 return role 269 else: 270 return Role.objects.filter(name=managed_role_name(self)).first() 271 272 def assign_perms_to_managed_role( 273 self, 274 perms: str | list[str] | Permission | list[Permission], 275 obj: models.Model | None = None, 276 ): 277 if not perms: 278 return 279 role = self.get_managed_role(create=True) 280 role.assign_perms(perms, obj)
Group model which supports a hierarchy and has attributes
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
239 @property 240 def serializer(self) -> Serializer: 241 from authentik.core.api.groups import GroupSerializer 242 243 return GroupSerializer
Get serializer for this model
245 @property 246 def num_pk(self) -> int: 247 """Get a numerical, int32 ID for the group""" 248 # int max is 2147483647 (10 digits) so 9 is the max usable 249 # in the LDAP Outpost we use the last 5 chars so match here 250 return int(str(self.pk.int)[:5])
Get a numerical, int32 ID for the group
252 def is_member(self, user: User) -> bool: 253 """Recursively check if `user` is member of us, or any parent.""" 254 return user.all_groups().filter(group_uuid=self.group_uuid).exists()
Recursively check if user is member of us, or any parent.
256 def all_roles(self) -> QuerySet[Role]: 257 """Get all roles of this group and all of its ancestors.""" 258 return Role.objects.filter( 259 groups__in=Group.objects.filter(pk=self.pk).with_ancestors() 260 ).distinct()
Get all roles of this group and all of its ancestors.
262 def get_managed_role(self, create=False): 263 if create: 264 name = managed_role_name(self) 265 role, created = Role.objects.get_or_create(name=name, managed=name) 266 if created: 267 role.groups.add(self) 268 return role 269 else: 270 return Role.objects.filter(name=managed_role_name(self)).first()
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
The requested object does not exist
The query returned multiple objects when only one was expected.
283class GroupParentageNode(models.Model): 284 uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 285 286 child = models.ForeignKey(Group, related_name="parent_nodes", on_delete=models.CASCADE) 287 parent = models.ForeignKey(Group, related_name="child_nodes", on_delete=models.CASCADE) 288 289 class Meta: 290 verbose_name = _("Group Parentage Node") 291 verbose_name_plural = _("Group Parentage Nodes") 292 293 db_table = "authentik_core_groupparentage" 294 295 triggers = [ 296 pgtrigger.Trigger( 297 name="refresh_groupancestry", 298 operation=pgtrigger.Insert | pgtrigger.Update | pgtrigger.Delete, 299 when=pgtrigger.After, 300 func=""" 301 REFRESH MATERIALIZED VIEW CONCURRENTLY authentik_core_groupancestry; 302 RETURN NULL; 303 """, 304 ), 305 ] 306 307 def __str__(self) -> str: 308 return f"Group Parentage Node from #{self.child_id} to {self.parent_id}"
GroupParentageNode(uuid, child, parent)
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
The requested object does not exist
The query returned multiple objects when only one was expected.
311class GroupAncestryNode(PostgresMaterializedViewModel): 312 descendant = models.ForeignKey( 313 Group, related_name="ancestor_nodes", on_delete=models.DO_NOTHING 314 ) 315 ancestor = models.ForeignKey( 316 Group, related_name="descendant_nodes", on_delete=models.DO_NOTHING 317 ) 318 319 class Meta: 320 # This is a transitive closure of authentik_core_groupparentage 321 # See https://en.wikipedia.org/wiki/Transitive_closure#In_graph_theory 322 db_table = "authentik_core_groupancestry" 323 indexes = [ 324 models.Index(fields=["descendant"]), 325 models.Index(fields=["ancestor"]), 326 UniqueIndex(fields=["id"]), 327 ] 328 329 class ViewMeta: 330 query = """ 331 WITH RECURSIVE accumulator AS ( 332 SELECT 333 child_id::text || '-' || parent_id::text as id, 334 child_id AS descendant_id, 335 parent_id AS ancestor_id 336 FROM authentik_core_groupparentage 337 338 UNION 339 340 SELECT 341 accumulator.descendant_id::text || '-' || current.parent_id::text as id, 342 accumulator.descendant_id, 343 current.parent_id AS ancestor_id 344 FROM accumulator 345 JOIN authentik_core_groupparentage current 346 ON accumulator.ancestor_id = current.child_id 347 ) 348 SELECT * FROM accumulator 349 """ 350 351 def __str__(self) -> str: 352 return f"Group Ancestry Node from {self.descendant_id} to {self.ancestor_id}"
GroupAncestryNode(id, descendant, ancestor)
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.
329 class ViewMeta: 330 query = """ 331 WITH RECURSIVE accumulator AS ( 332 SELECT 333 child_id::text || '-' || parent_id::text as id, 334 child_id AS descendant_id, 335 parent_id AS ancestor_id 336 FROM authentik_core_groupparentage 337 338 UNION 339 340 SELECT 341 accumulator.descendant_id::text || '-' || current.parent_id::text as id, 342 accumulator.descendant_id, 343 current.parent_id AS ancestor_id 344 FROM accumulator 345 JOIN authentik_core_groupparentage current 346 ON accumulator.ancestor_id = current.child_id 347 ) 348 SELECT * FROM accumulator 349 """
The requested object does not exist
The query returned multiple objects when only one was expected.
355class UserQuerySet(models.QuerySet): 356 """User queryset""" 357 358 def exclude_anonymous(self): 359 """Exclude anonymous user""" 360 return self.exclude(**{User.USERNAME_FIELD: settings.ANONYMOUS_USER_NAME}) 361 362 def filter_agents(self) -> Self: 363 """Include only agent users.""" 364 from authentik.enterprise.agents.models import AgentUserQuerySet 365 366 return AgentUserQuerySet.filter_agents(self) 367 368 def exclude_agents(self) -> Self: 369 """Exclude agent users.""" 370 from authentik.enterprise.agents.models import AgentUserQuerySet 371 372 return AgentUserQuerySet.exclude_agents(self)
User queryset
358 def exclude_anonymous(self): 359 """Exclude anonymous user""" 360 return self.exclude(**{User.USERNAME_FIELD: settings.ANONYMOUS_USER_NAME})
Exclude anonymous user
375class UserManager(DjangoUserManager.from_queryset(UserQuerySet)): 376 """User manager that doesn't assign is_superuser and is_staff""" 377 378 def create_user(self, username, email=None, password=None, **extra_fields): 379 """User manager that doesn't assign is_superuser and is_staff""" 380 from authentik.stages.password.models import PasswordDevice 381 382 user = self.create(username=username, email=self.normalize_email(email), **extra_fields) 383 if password is not None: 384 PasswordDevice.set_password(user, password, signal=False) 385 return user 386 387 def exclude_anonymous(self) -> QuerySet: 388 """Exclude anonymous user""" 389 return self.get_queryset().exclude_anonymous()
User manager that doesn't assign is_superuser and is_staff
378 def create_user(self, username, email=None, password=None, **extra_fields): 379 """User manager that doesn't assign is_superuser and is_staff""" 380 from authentik.stages.password.models import PasswordDevice 381 382 user = self.create(username=username, email=self.normalize_email(email), **extra_fields) 383 if password is not None: 384 PasswordDevice.set_password(user, password, signal=False) 385 return user
User manager that doesn't assign is_superuser and is_staff
392class User(SerializerModel, AttributesMixin, AbstractUser): 393 """authentik User model, based on django's contrib auth user model.""" 394 395 # Overwriting PermissionsMixin: permissions are handled by roles. 396 # (This knowingly violates the Liskov substitution principle. It is better to fail loudly.) 397 user_permissions = None 398 399 uuid = models.UUIDField(default=uuid4, editable=False, unique=True) 400 name = models.TextField(help_text=_("User's display name.")) 401 path = models.TextField(default="users") 402 type = models.TextField(choices=UserTypes.choices, default=UserTypes.INTERNAL) 403 404 sources = models.ManyToManyField("Source", through="UserSourceConnection") 405 groups = models.ManyToManyField("Group", related_name="users", through="UserGroup") 406 roles = models.ManyToManyField( 407 "authentik_rbac.Role", related_name="users", blank=True, through="UserRole" 408 ) 409 410 last_updated = models.DateTimeField(auto_now=True) 411 412 objects = UserManager() 413 414 class Meta: 415 verbose_name = _("User") 416 verbose_name_plural = _("Users") 417 permissions = [ 418 ("reset_user_password", _("Reset Password")), 419 ("impersonate", _("Can impersonate other users")), 420 ("preview_user", _("Can preview user data sent to providers")), 421 ("view_user_applications", _("View applications the user has access to")), 422 ] 423 indexes = [ 424 models.Index(fields=["last_login"]), 425 models.Index(fields=["uuid"]), 426 models.Index(fields=["path"]), 427 models.Index(fields=["type"]), 428 models.Index(fields=["date_joined"]), 429 models.Index(fields=["last_updated"]), 430 models.Index(fields=["username", "is_active", "type"]), 431 models.Index(Upper("email"), name="%(app_label)s_%(class)s_email_idx"), 432 ] 433 434 def __str__(self): 435 return self.username 436 437 @staticmethod 438 def default_path() -> str: 439 """Get the default user path""" 440 return User._meta.get_field("path").default 441 442 def all_groups(self) -> QuerySet[Group]: 443 """Recursively get all groups this user is a member of.""" 444 return self.groups.all().with_ancestors() 445 446 def all_roles(self) -> QuerySet[Role]: 447 """Get all roles of this user and all of its groups (recursively).""" 448 return Role.objects.filter(Q(users=self) | Q(groups__in=self.all_groups())).distinct() 449 450 def get_managed_role(self, create=False): 451 if create: 452 name = managed_role_name(self) 453 role, created = Role.objects.get_or_create(name=name, managed=name) 454 if created: 455 role.users.add(self) 456 return role 457 else: 458 return Role.objects.filter(name=managed_role_name(self)).first() 459 460 def get_all_model_perms_on_managed_role(self) -> QuerySet[RoleModelPermission]: 461 role = self.get_managed_role() 462 if not role: 463 return RoleModelPermission.objects.none() 464 return RoleModelPermission.objects.filter(role=role) 465 466 def get_all_obj_perms_on_managed_role(self) -> QuerySet[RoleObjectPermission]: 467 role = self.get_managed_role() 468 if not role: 469 return RoleObjectPermission.objects.none() 470 return RoleObjectPermission.objects.filter(role=role) 471 472 def assign_perms_to_managed_role( 473 self, 474 perms: str | list[str] | Permission | list[Permission], 475 obj: models.Model | None = None, 476 ): 477 if not perms: 478 return 479 role = self.get_managed_role(create=True) 480 role.assign_perms(perms, obj) 481 482 def remove_perms_from_managed_role( 483 self, 484 perms: str | list[str] | Permission | list[Permission], 485 obj: models.Model | None = None, 486 ): 487 role = self.get_managed_role() 488 if not role: 489 return None 490 role.remove_perms(perms, obj) 491 492 def remove_all_perms_from_managed_role(self): 493 role = self.get_managed_role() 494 if not role: 495 return None 496 RoleModelPermission.objects.filter(role=role).delete() 497 RoleObjectPermission.objects.filter(role=role).delete() 498 499 def group_attributes(self, request: HttpRequest | None = None) -> dict[str, Any]: 500 """Get a dictionary containing the attributes from all groups the user belongs to, 501 including the users attributes""" 502 final_attributes = {} 503 if request and hasattr(request, "brand"): 504 always_merger.merge(final_attributes, request.brand.attributes) 505 for group in self.all_groups().order_by("name"): 506 always_merger.merge(final_attributes, group.attributes) 507 always_merger.merge(final_attributes, self.attributes) 508 return final_attributes 509 510 def app_entitlements(self, app: Application | None) -> QuerySet[ApplicationEntitlement]: 511 """Get all entitlements this user has for `app`.""" 512 if not app: 513 return ApplicationEntitlement.objects.none() 514 return self.all_app_entitlements().filter(app=app) 515 516 def all_app_entitlements(self) -> QuerySet[ApplicationEntitlement]: 517 """Get all entitlements this user is assigned, regardless of access to the application.""" 518 all_groups = self.all_groups() 519 return ( 520 ApplicationEntitlement.objects.filter( 521 Q( 522 Q(bindings__user=self) | Q(bindings__group__in=all_groups), 523 bindings__negate=False, 524 ) 525 | Q( 526 Q(~Q(bindings__user=self), bindings__user__isnull=False) 527 | Q(~Q(bindings__group__in=all_groups), bindings__group__isnull=False), 528 bindings__negate=True, 529 ), 530 bindings__enabled=True, 531 ) 532 .distinct() 533 .order_by("name") 534 ) 535 536 def app_entitlements_attributes(self, app: Application | None) -> dict: 537 """Get a dictionary containing all merged attributes from app entitlements for `app`.""" 538 final_attributes = {} 539 for attrs in self.app_entitlements(app).values_list("attributes", flat=True): 540 always_merger.merge(final_attributes, attrs) 541 return final_attributes 542 543 @property 544 def serializer(self) -> Serializer: 545 from authentik.core.api.users import UserSerializer 546 547 return UserSerializer 548 549 @cached_property 550 def is_superuser(self) -> bool: 551 """Get supseruser status based on membership in a group with superuser status""" 552 return self.all_groups().filter(is_superuser=True).exists() 553 554 @property 555 def is_staff(self) -> bool: 556 """superuser == staff user""" 557 return self.is_superuser # type: ignore 558 559 # TODO: remove this after 2026. 560 @property 561 def ak_groups(self): 562 """This is a proxy for a renamed, deprecated field.""" 563 from authentik.events.models import Event 564 565 deprecation = "authentik.core.models.User.ak_groups" 566 replacement = "authentik.core.models.User.groups" 567 message_logger = ( 568 f"{deprecation} is deprecated and will be removed in a future version of " 569 f"authentik. Please use {replacement} instead." 570 ) 571 message_event = ( 572 f"{message_logger} This event will not be repeated until it expires (by " 573 "default: in 30 days). See authentik logs for every will invocation of this " 574 "deprecation." 575 ) 576 stacktrace = traceback.format_stack() 577 # The last line is this function, the next-to-last line is its caller 578 cause = stacktrace[-2] if len(stacktrace) > 1 else "Unknown, see stacktrace in logs" 579 if search := re.search(r'"(.*?)"', cause): 580 cause = f"Property mapping or Expression policy named {search.group(1)}" 581 582 LOGGER.warning( 583 "deprecation used", 584 message=message_logger, 585 deprecation=deprecation, 586 replacement=replacement, 587 cause=cause, 588 stacktrace=stacktrace, 589 ) 590 Event.log_deprecation( 591 deprecation, message=message_event, cause=cause, replacement=replacement 592 ) 593 return self.groups 594 595 # Passwords are written through authentik.stages.password.models.PasswordDevice. 596 # These read-only properties keep `user.password` and `user.password_change_date` 597 # working in expressions, Django's session hash and the user API. 598 @property 599 def password(self) -> str: 600 device = getattr(self, "password_device", None) 601 return device.password if device else UNUSABLE_PASSWORD_PREFIX 602 603 @property 604 def password_change_date(self) -> datetime: 605 device = getattr(self, "password_device", None) 606 return device.password_change_date if device else self.date_joined 607 608 def check_password(self, raw_password: str) -> bool: 609 # Django's version writes `password` when it upgrades an outdated hash. 610 device = getattr(self, "password_device", None) 611 return device.check_password(raw_password) if device else False 612 613 async def acheck_password(self, raw_password: str) -> bool: 614 return await sync_to_async(self.check_password)(raw_password) 615 616 # Django's password writes would assign the read-only `password`; fail loudly instead. 617 def set_password(self, raw_password): 618 raise NotImplementedError("Use PasswordDevice.set_password()") 619 620 def set_unusable_password(self): 621 raise NotImplementedError("Use PasswordDevice.set_unusable_password()") 622 623 @property 624 def uid(self) -> str: 625 """Generate a globally unique UID, based on the user ID and the hashed secret key""" 626 return sha256(f"{self.id}-{get_install_id()}".encode("ascii")).hexdigest() 627 628 def locale(self, request: HttpRequest | None = None) -> str: 629 """Get the locale the user has configured""" 630 try: 631 locale = self.attributes.get("settings", {}).get("locale", "") 632 if locale: 633 return locale 634 except Exception as exc: # noqa 635 LOGGER.warning("Failed to get default locale", exc=exc) 636 if request and hasattr(request, "LANGUAGE_CODE"): 637 return request.LANGUAGE_CODE 638 return "" 639 640 @property 641 def avatar(self) -> str: 642 """Get avatar, depending on authentik.avatar setting""" 643 return get_avatar(self)
authentik User model, based on django's contrib auth user model.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
437 @staticmethod 438 def default_path() -> str: 439 """Get the default user path""" 440 return User._meta.get_field("path").default
Get the default user path
442 def all_groups(self) -> QuerySet[Group]: 443 """Recursively get all groups this user is a member of.""" 444 return self.groups.all().with_ancestors()
Recursively get all groups this user is a member of.
446 def all_roles(self) -> QuerySet[Role]: 447 """Get all roles of this user and all of its groups (recursively).""" 448 return Role.objects.filter(Q(users=self) | Q(groups__in=self.all_groups())).distinct()
Get all roles of this user and all of its groups (recursively).
450 def get_managed_role(self, create=False): 451 if create: 452 name = managed_role_name(self) 453 role, created = Role.objects.get_or_create(name=name, managed=name) 454 if created: 455 role.users.add(self) 456 return role 457 else: 458 return Role.objects.filter(name=managed_role_name(self)).first()
499 def group_attributes(self, request: HttpRequest | None = None) -> dict[str, Any]: 500 """Get a dictionary containing the attributes from all groups the user belongs to, 501 including the users attributes""" 502 final_attributes = {} 503 if request and hasattr(request, "brand"): 504 always_merger.merge(final_attributes, request.brand.attributes) 505 for group in self.all_groups().order_by("name"): 506 always_merger.merge(final_attributes, group.attributes) 507 always_merger.merge(final_attributes, self.attributes) 508 return final_attributes
Get a dictionary containing the attributes from all groups the user belongs to, including the users attributes
510 def app_entitlements(self, app: Application | None) -> QuerySet[ApplicationEntitlement]: 511 """Get all entitlements this user has for `app`.""" 512 if not app: 513 return ApplicationEntitlement.objects.none() 514 return self.all_app_entitlements().filter(app=app)
Get all entitlements this user has for app.
516 def all_app_entitlements(self) -> QuerySet[ApplicationEntitlement]: 517 """Get all entitlements this user is assigned, regardless of access to the application.""" 518 all_groups = self.all_groups() 519 return ( 520 ApplicationEntitlement.objects.filter( 521 Q( 522 Q(bindings__user=self) | Q(bindings__group__in=all_groups), 523 bindings__negate=False, 524 ) 525 | Q( 526 Q(~Q(bindings__user=self), bindings__user__isnull=False) 527 | Q(~Q(bindings__group__in=all_groups), bindings__group__isnull=False), 528 bindings__negate=True, 529 ), 530 bindings__enabled=True, 531 ) 532 .distinct() 533 .order_by("name") 534 )
Get all entitlements this user is assigned, regardless of access to the application.
536 def app_entitlements_attributes(self, app: Application | None) -> dict: 537 """Get a dictionary containing all merged attributes from app entitlements for `app`.""" 538 final_attributes = {} 539 for attrs in self.app_entitlements(app).values_list("attributes", flat=True): 540 always_merger.merge(final_attributes, attrs) 541 return final_attributes
Get a dictionary containing all merged attributes from app entitlements for app.
543 @property 544 def serializer(self) -> Serializer: 545 from authentik.core.api.users import UserSerializer 546 547 return UserSerializer
Get serializer for this model
Get supseruser status based on membership in a group with superuser status
554 @property 555 def is_staff(self) -> bool: 556 """superuser == staff user""" 557 return self.is_superuser # type: ignore
superuser == staff user
560 @property 561 def ak_groups(self): 562 """This is a proxy for a renamed, deprecated field.""" 563 from authentik.events.models import Event 564 565 deprecation = "authentik.core.models.User.ak_groups" 566 replacement = "authentik.core.models.User.groups" 567 message_logger = ( 568 f"{deprecation} is deprecated and will be removed in a future version of " 569 f"authentik. Please use {replacement} instead." 570 ) 571 message_event = ( 572 f"{message_logger} This event will not be repeated until it expires (by " 573 "default: in 30 days). See authentik logs for every will invocation of this " 574 "deprecation." 575 ) 576 stacktrace = traceback.format_stack() 577 # The last line is this function, the next-to-last line is its caller 578 cause = stacktrace[-2] if len(stacktrace) > 1 else "Unknown, see stacktrace in logs" 579 if search := re.search(r'"(.*?)"', cause): 580 cause = f"Property mapping or Expression policy named {search.group(1)}" 581 582 LOGGER.warning( 583 "deprecation used", 584 message=message_logger, 585 deprecation=deprecation, 586 replacement=replacement, 587 cause=cause, 588 stacktrace=stacktrace, 589 ) 590 Event.log_deprecation( 591 deprecation, message=message_event, cause=cause, replacement=replacement 592 ) 593 return self.groups
This is a proxy for a renamed, deprecated field.
598 @property 599 def password(self) -> str: 600 device = getattr(self, "password_device", None) 601 return device.password if device else UNUSABLE_PASSWORD_PREFIX
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
608 def check_password(self, raw_password: str) -> bool: 609 # Django's version writes `password` when it upgrades an outdated hash. 610 device = getattr(self, "password_device", None) 611 return device.check_password(raw_password) if device else False
Return a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes.
613 async def acheck_password(self, raw_password: str) -> bool: 614 return await sync_to_async(self.check_password)(raw_password)
See check_password().
623 @property 624 def uid(self) -> str: 625 """Generate a globally unique UID, based on the user ID and the hashed secret key""" 626 return sha256(f"{self.id}-{get_install_id()}".encode("ascii")).hexdigest()
Generate a globally unique UID, based on the user ID and the hashed secret key
628 def locale(self, request: HttpRequest | None = None) -> str: 629 """Get the locale the user has configured""" 630 try: 631 locale = self.attributes.get("settings", {}).get("locale", "") 632 if locale: 633 return locale 634 except Exception as exc: # noqa 635 LOGGER.warning("Failed to get default locale", exc=exc) 636 if request and hasattr(request, "LANGUAGE_CODE"): 637 return request.LANGUAGE_CODE 638 return ""
Get the locale the user has configured
640 @property 641 def avatar(self) -> str: 642 """Get avatar, depending on authentik.avatar setting""" 643 return get_avatar(self)
Get avatar, depending on authentik.avatar setting
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
The requested object does not exist
The query returned multiple objects when only one was expected.
646def get_init_anonymous_user(user_model: type[User]) -> User: 647 """Build guardian's anonymous user, which has no password device and so no password. 648 649 guardian's default calls `set_unusable_password()`, which needs a writable `password`.""" 650 return user_model(username=settings.ANONYMOUS_USER_NAME)
Build guardian's anonymous user, which has no password device and so no password.
guardian's default calls set_unusable_password(), which needs a writable password.
653class Provider(SerializerModel): 654 """Application-independent Provider instance. For example SAML2 Remote, OAuth2 Application""" 655 656 name = models.TextField(unique=True) 657 658 authentication_flow = models.ForeignKey( 659 "authentik_flows.Flow", 660 null=True, 661 on_delete=models.SET_NULL, 662 help_text=_( 663 "Flow used for authentication when the associated application is accessed by an " 664 "un-authenticated user." 665 ), 666 related_name="provider_authentication", 667 ) 668 authorization_flow = models.ForeignKey( 669 "authentik_flows.Flow", 670 # Set to cascade even though null is allowed, since most providers 671 # still require an authorization flow set 672 on_delete=models.CASCADE, 673 null=True, 674 help_text=_("Flow used when authorizing this provider."), 675 related_name="provider_authorization", 676 ) 677 invalidation_flow = models.ForeignKey( 678 "authentik_flows.Flow", 679 on_delete=models.SET_DEFAULT, 680 default=None, 681 null=True, 682 help_text=_("Flow used ending the session from a provider."), 683 related_name="provider_invalidation", 684 ) 685 686 property_mappings = models.ManyToManyField( 687 "PropertyMapping", default=None, blank=True, through="ProviderPropertyMapping" 688 ) 689 690 backchannel_application = models.ForeignKey( 691 "Application", 692 default=None, 693 null=True, 694 on_delete=models.CASCADE, 695 help_text=_( 696 "Accessed from applications; optional backchannel providers for protocols " 697 "like LDAP and SCIM." 698 ), 699 related_name="backchannel_providers", 700 ) 701 702 is_backchannel = models.BooleanField(default=False) 703 704 objects = InheritanceManager() 705 706 @property 707 def launch_url(self) -> str | None: 708 """URL to this provider and initiate authorization for the user. 709 Can return None for providers that are not URL-based""" 710 return None 711 712 @property 713 def icon_url(self) -> str | None: 714 return None 715 716 @property 717 def component(self) -> str: 718 """Return component used to edit this object""" 719 raise NotImplementedError 720 721 @property 722 def serializer(self) -> type[Serializer]: 723 """Get serializer for this model""" 724 raise NotImplementedError 725 726 def __str__(self): 727 return str(self.name)
Application-independent Provider instance. For example SAML2 Remote, OAuth2 Application
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
706 @property 707 def launch_url(self) -> str | None: 708 """URL to this provider and initiate authorization for the user. 709 Can return None for providers that are not URL-based""" 710 return None
URL to this provider and initiate authorization for the user. Can return None for providers that are not URL-based
716 @property 717 def component(self) -> str: 718 """Return component used to edit this object""" 719 raise NotImplementedError
Return component used to edit this object
721 @property 722 def serializer(self) -> type[Serializer]: 723 """Get serializer for this model""" 724 raise NotImplementedError
Get serializer for this model
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
730class BackchannelProvider(Provider): 731 """Base class for providers that augment other providers, for example LDAP and SCIM. 732 Multiple of these providers can be configured per application, they may not use the application 733 slug in URLs as an application may have multiple instances of the same 734 type of Backchannel provider 735 736 They can use the application's policies and metadata""" 737 738 @property 739 def component(self) -> str: 740 raise NotImplementedError 741 742 @property 743 def serializer(self) -> type[Serializer]: 744 raise NotImplementedError 745 746 class Meta: 747 abstract = True
Base class for providers that augment other providers, for example LDAP and SCIM. Multiple of these providers can be configured per application, they may not use the application slug in URLs as an application may have multiple instances of the same type of Backchannel provider
They can use the application's policies and metadata
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
Inherited Members
- Provider
- name
- authentication_flow
- invalidation_flow
- property_mappings
- backchannel_application
- is_backchannel
- objects
- launch_url
- icon_url
- DoesNotExist
- MultipleObjectsReturned
- authentication_flow_id
- invalidation_flow_id
- backchannel_application_id
- id
- application
- providerpropertymapping_set
- outpost_set
- outpostprovider_set
- oauth2provider
- ldapprovider
- racprovider
- radiusprovider
- samlprovider
- scimprovider
- googleworkspaceprovider
- microsoftentraprovider
- ssfprovider
750class ApplicationQuerySet(QuerySet): 751 def with_provider(self) -> QuerySet[Application]: 752 """Load each application's provider as its concrete subclass, so get_provider() needs 753 no query. 754 755 The providers come from a second query rather than a join: selecting every provider 756 subclass, and the applications related to each, through the application query made a 757 statement of about 70 joins that Postgres took over 100ms to plan. 758 759 The provider is prefetched before any other lookup, so lookups through it such as 760 `provider__property_mappings` work on the concrete providers whether they were added 761 before or after, and calling this again adds nothing.""" 762 provider = Prefetch("provider", queryset=Provider.objects.select_subclasses()) 763 # Prefetches are equal when they prefetch to the same attribute 764 lookups = [lookup for lookup in self._prefetch_related_lookups if lookup != provider] 765 return self.prefetch_related(None).prefetch_related(provider, *lookups)
Represent a lazy database lookup for a set of objects.
751 def with_provider(self) -> QuerySet[Application]: 752 """Load each application's provider as its concrete subclass, so get_provider() needs 753 no query. 754 755 The providers come from a second query rather than a join: selecting every provider 756 subclass, and the applications related to each, through the application query made a 757 statement of about 70 joins that Postgres took over 100ms to plan. 758 759 The provider is prefetched before any other lookup, so lookups through it such as 760 `provider__property_mappings` work on the concrete providers whether they were added 761 before or after, and calling this again adds nothing.""" 762 provider = Prefetch("provider", queryset=Provider.objects.select_subclasses()) 763 # Prefetches are equal when they prefetch to the same attribute 764 lookups = [lookup for lookup in self._prefetch_related_lookups if lookup != provider] 765 return self.prefetch_related(None).prefetch_related(provider, *lookups)
Load each application's provider as its concrete subclass, so get_provider() needs no query.
The providers come from a second query rather than a join: selecting every provider subclass, and the applications related to each, through the application query made a statement of about 70 joins that Postgres took over 100ms to plan.
The provider is prefetched before any other lookup, so lookups through it such as
provider__property_mappings work on the concrete providers whether they were added
before or after, and calling this again adds nothing.
768class Application(RequestableModel, SerializerModel, PolicyBindingModel): 769 """Every Application which uses authentik for authentication/identification/authorization 770 needs an Application record. Other authentication types can subclass this Model to 771 add custom fields and other properties""" 772 773 name = models.TextField(help_text=_("Application's display Name.")) 774 slug = models.TextField( 775 validators=[validate_slug], 776 help_text=_("Internal application name, used in URLs."), 777 unique=True, 778 ) 779 group = models.TextField(blank=True, default="") 780 781 provider = models.OneToOneField( 782 "Provider", null=True, blank=True, default=None, on_delete=models.SET_DEFAULT 783 ) 784 785 meta_launch_url = models.TextField( 786 default="", blank=True, validators=[DomainlessFormattedURLValidator()] 787 ) 788 789 open_in_new_tab = models.BooleanField( 790 default=False, help_text=_("Open launch URL in a new browser tab or window.") 791 ) 792 793 meta_icon = FileField(default="", blank=True) 794 meta_description = models.TextField(default="", blank=True) 795 meta_publisher = models.TextField(default="", blank=True) 796 meta_hide = models.BooleanField( 797 default=False, help_text=_("Hide this application from the user's My applications page.") 798 ) 799 800 objects = ApplicationQuerySet.as_manager() 801 802 # Reserved slugs that would clash with OAuth2 provider endpoints 803 reserved_slugs = ["authorize", "token", "device", "userinfo", "introspect", "revoke"] 804 805 @property 806 def serializer(self) -> Serializer: 807 from authentik.core.api.applications import ApplicationSerializer 808 809 return ApplicationSerializer 810 811 @property 812 def get_meta_icon(self) -> str | None: 813 """Get the URL to the App Icon image""" 814 if not self.meta_icon: 815 return None 816 817 return get_file_manager(FileUsage.MEDIA).file_url(self.meta_icon) 818 819 @property 820 def get_meta_icon_themed_urls(self) -> dict[str, str] | None: 821 """Get themed URLs for meta_icon if it contains %(theme)s or is a built-in source icon""" 822 if not self.meta_icon: 823 return None 824 825 return get_file_manager(FileUsage.MEDIA).themed_urls(self.meta_icon) 826 827 def get_launch_url( 828 self, user: User | None = None, user_data: Callable[[], dict] | None = None 829 ) -> str | None: 830 """Get launch URL if set, otherwise attempt to get launch URL based on provider. 831 832 Args: 833 user: User whose data fills the URL's `%(name)s` placeholders 834 user_data: Returns `user` serialized, for a caller that formats many URLs for the 835 same user. Called only for a URL with placeholders. 836 """ 837 from authentik.core.api.users import UserSerializer 838 839 url = None 840 if self.meta_launch_url: 841 url = self.meta_launch_url 842 elif provider := self.get_provider(): 843 url = provider.launch_url 844 # Serializing the user queries their groups, roles and avatar, so it happens only for a 845 # URL with placeholders 846 if not user or not url or "%(" not in url: 847 return url 848 # Escape every `%` that is neither a placeholder nor `%%`, such as percent-encoding, so 849 # it is kept as is instead of being filled with the whole user 850 template = re.sub(r"(%%|%\()|%", lambda match: match.group(1) or "%%", url) 851 try: 852 data = user_data() if user_data else UserSerializer(instance=user).data 853 launch_url = template % data 854 except Exception as exc: # noqa 855 LOGGER.warning("Failed to format launch url", exc=exc) 856 return url 857 if url.startswith("/"): 858 launch_url = iri_to_uri(launch_url) 859 # Substitutions must preserve the root-relative URL accepted by the validator. 860 if not DomainlessFormattedURLValidator.relative_re.match(launch_url): 861 return None 862 return launch_url 863 864 def get_provider(self) -> Provider | None: 865 """Get casted provider instance. Needs Application queryset with_provider""" 866 if hasattr(self, "_cached_provider"): 867 return self._cached_provider 868 if not self.provider: 869 self._cached_provider = None 870 return None 871 self._cached_provider = get_deepest_child(self.provider) 872 return self._cached_provider 873 874 def backchannel_provider_for[T: Provider](self, provider_type: type[T], **kwargs) -> T | None: 875 """Get Backchannel provider for a specific type""" 876 provider: BackchannelProvider | None = self.backchannel_providers.filter( 877 **{f"{provider_type._meta.model_name}__isnull": False}, 878 **kwargs, 879 ).first() 880 return getattr(provider, provider_type._meta.model_name) if provider else None 881 882 def __str__(self): 883 return str(self.name) 884 885 def requestable_child_model_types(self): 886 return [ApplicationEntitlement] 887 888 class Meta: 889 verbose_name = _("Application") 890 verbose_name_plural = _("Applications")
Every Application which uses authentik for authentication/identification/authorization needs an Application record. Other authentication types can subclass this Model to add custom fields and other properties
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
805 @property 806 def serializer(self) -> Serializer: 807 from authentik.core.api.applications import ApplicationSerializer 808 809 return ApplicationSerializer
Get serializer for this model
811 @property 812 def get_meta_icon(self) -> str | None: 813 """Get the URL to the App Icon image""" 814 if not self.meta_icon: 815 return None 816 817 return get_file_manager(FileUsage.MEDIA).file_url(self.meta_icon)
Get the URL to the App Icon image
819 @property 820 def get_meta_icon_themed_urls(self) -> dict[str, str] | None: 821 """Get themed URLs for meta_icon if it contains %(theme)s or is a built-in source icon""" 822 if not self.meta_icon: 823 return None 824 825 return get_file_manager(FileUsage.MEDIA).themed_urls(self.meta_icon)
Get themed URLs for meta_icon if it contains %(theme)s or is a built-in source icon
827 def get_launch_url( 828 self, user: User | None = None, user_data: Callable[[], dict] | None = None 829 ) -> str | None: 830 """Get launch URL if set, otherwise attempt to get launch URL based on provider. 831 832 Args: 833 user: User whose data fills the URL's `%(name)s` placeholders 834 user_data: Returns `user` serialized, for a caller that formats many URLs for the 835 same user. Called only for a URL with placeholders. 836 """ 837 from authentik.core.api.users import UserSerializer 838 839 url = None 840 if self.meta_launch_url: 841 url = self.meta_launch_url 842 elif provider := self.get_provider(): 843 url = provider.launch_url 844 # Serializing the user queries their groups, roles and avatar, so it happens only for a 845 # URL with placeholders 846 if not user or not url or "%(" not in url: 847 return url 848 # Escape every `%` that is neither a placeholder nor `%%`, such as percent-encoding, so 849 # it is kept as is instead of being filled with the whole user 850 template = re.sub(r"(%%|%\()|%", lambda match: match.group(1) or "%%", url) 851 try: 852 data = user_data() if user_data else UserSerializer(instance=user).data 853 launch_url = template % data 854 except Exception as exc: # noqa 855 LOGGER.warning("Failed to format launch url", exc=exc) 856 return url 857 if url.startswith("/"): 858 launch_url = iri_to_uri(launch_url) 859 # Substitutions must preserve the root-relative URL accepted by the validator. 860 if not DomainlessFormattedURLValidator.relative_re.match(launch_url): 861 return None 862 return launch_url
Get launch URL if set, otherwise attempt to get launch URL based on provider.
Args:
user: User whose data fills the URL's %(name)s placeholders
user_data: Returns user serialized, for a caller that formats many URLs for the
same user. Called only for a URL with placeholders.
864 def get_provider(self) -> Provider | None: 865 """Get casted provider instance. Needs Application queryset with_provider""" 866 if hasattr(self, "_cached_provider"): 867 return self._cached_provider 868 if not self.provider: 869 self._cached_provider = None 870 return None 871 self._cached_provider = get_deepest_child(self.provider) 872 return self._cached_provider
Get casted provider instance. Needs Application queryset with_provider
874 def backchannel_provider_for[T: Provider](self, provider_type: type[T], **kwargs) -> T | None: 875 """Get Backchannel provider for a specific type""" 876 provider: BackchannelProvider | None = self.backchannel_providers.filter( 877 **{f"{provider_type._meta.model_name}__isnull": False}, 878 **kwargs, 879 ).first() 880 return getattr(provider, provider_type._meta.model_name) if provider else None
Get Backchannel provider for a specific type
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
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.
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.
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.
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.
Inherited Members
- authentik.policies.models.PolicyBindingModel
- pbm_uuid
- policies
- policy_engine_mode
- supported_policy_binding_targets
- get_policy_engine_mode_display
- bindings
- application
- applicationentitlement
- source
- flow
- flowstagebinding
- notificationrule
- device
- deviceaccessgroup
- oauth2dynamicclientregistration
- userexpirationrule
- request_rule_bindings
- request_rule_child_bindings
- requestrulebinding
- request_rules
- requestrule
- grantrequest_set
- grantrequesttarget_set
The requested object does not exist
The query returned multiple objects when only one was expected.
893class ApplicationEntitlement( 894 RequestableChildModel, AttributesMixin, SerializerModel, PolicyBindingModel 895): 896 """Application-scoped entitlement to control authorization in an application""" 897 898 name = models.TextField() 899 900 app = models.ForeignKey(Application, on_delete=models.CASCADE) 901 902 class Meta: 903 verbose_name = _("Application Entitlement") 904 verbose_name_plural = _("Application Entitlements") 905 unique_together = (("app", "name"),) 906 907 def __str__(self): 908 return f"Application Entitlement {self.name} for app {self.app_id}" 909 910 @property 911 def requestable_parent(self) -> Application: 912 return self.app 913 914 @property 915 def requestable_label(self): 916 return self.name 917 918 @property 919 def serializer(self) -> type[Serializer]: 920 from authentik.core.api.application_entitlements import ApplicationEntitlementSerializer 921 922 return ApplicationEntitlementSerializer 923 924 def supported_policy_binding_targets(self): 925 return ["group", "user"]
Application-scoped entitlement to control authorization in an application
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
918 @property 919 def serializer(self) -> type[Serializer]: 920 from authentik.core.api.application_entitlements import ApplicationEntitlementSerializer 921 922 return ApplicationEntitlementSerializer
Get serializer for this model
Return the list of objects that can be bound to this object.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
Inherited Members
- authentik.policies.models.PolicyBindingModel
- pbm_uuid
- policies
- policy_engine_mode
- objects
- get_policy_engine_mode_display
- bindings
- application
- applicationentitlement
- source
- flow
- flowstagebinding
- notificationrule
- device
- deviceaccessgroup
- oauth2dynamicclientregistration
- userexpirationrule
- request_rule_bindings
- request_rule_child_bindings
- requestrulebinding
- request_rules
- requestrule
- grantrequest_set
- grantrequesttarget_set
The requested object does not exist
The query returned multiple objects when only one was expected.
928class SourceUserMatchingModes(models.TextChoices): 929 """Different modes a source can handle new/returning users""" 930 931 IDENTIFIER = "identifier", _("Use the source-specific identifier") 932 EMAIL_LINK = ( 933 "email_link", 934 _( 935 "Link to a user with identical email address. Can have security implications " 936 "when a source doesn't validate email addresses." 937 ), 938 ) 939 EMAIL_DENY = ( 940 "email_deny", 941 _( 942 "Use the user's email address, but deny enrollment when the email address already " 943 "exists." 944 ), 945 ) 946 USERNAME_LINK = ( 947 "username_link", 948 _( 949 "Link to a user with identical username. Can have security implications " 950 "when a username is used with another source." 951 ), 952 ) 953 USERNAME_DENY = ( 954 "username_deny", 955 _("Use the user's username, but deny enrollment when the username already exists."), 956 )
Different modes a source can handle new/returning users
959class SourceGroupMatchingModes(models.TextChoices): 960 """Different modes a source can handle new/returning groups""" 961 962 IDENTIFIER = "identifier", _("Use the source-specific identifier") 963 NAME_LINK = ( 964 "name_link", 965 _( 966 "Link to a group with identical name. Can have security implications " 967 "when a group name is used with another source." 968 ), 969 ) 970 NAME_DENY = ( 971 "name_deny", 972 _("Use the group name, but deny enrollment when the name already exists."), 973 )
Different modes a source can handle new/returning groups
976class Source(ManagedModel, SerializerModel, PolicyBindingModel): 977 """Base Authentication source, i.e. an OAuth Provider, SAML Remote or LDAP Server""" 978 979 MANAGED_INBUILT = "goauthentik.io/sources/inbuilt" 980 981 name = models.TextField(help_text=_("Source's display Name.")) 982 slug = models.TextField( 983 validators=[validate_slug], 984 help_text=_("Internal source name, used in URLs."), 985 unique=True, 986 ) 987 988 user_path_template = models.TextField(default="goauthentik.io/sources/%(slug)s") 989 990 enabled = models.BooleanField(default=True) 991 promoted = models.BooleanField( 992 default=False, 993 help_text=_( 994 "When enabled, this source will be displayed as a prominent button on the " 995 "login page, instead of a small icon." 996 ), 997 ) 998 user_property_mappings = models.ManyToManyField( 999 "PropertyMapping", 1000 default=None, 1001 blank=True, 1002 related_name="source_userpropertymappings_set", 1003 through="SourceUserPropertyMapping", 1004 ) 1005 group_property_mappings = models.ManyToManyField( 1006 "PropertyMapping", 1007 default=None, 1008 blank=True, 1009 related_name="source_grouppropertymappings_set", 1010 through="SourceGroupPropertyMapping", 1011 ) 1012 1013 icon = FileField(blank=True, default="") 1014 1015 authentication_flow = models.ForeignKey( 1016 "authentik_flows.Flow", 1017 blank=True, 1018 null=True, 1019 default=None, 1020 on_delete=models.SET_NULL, 1021 help_text=_("Flow to use when authenticating existing users."), 1022 related_name="source_authentication", 1023 ) 1024 enrollment_flow = models.ForeignKey( 1025 "authentik_flows.Flow", 1026 blank=True, 1027 null=True, 1028 default=None, 1029 on_delete=models.SET_NULL, 1030 help_text=_("Flow to use when enrolling new users."), 1031 related_name="source_enrollment", 1032 ) 1033 1034 user_matching_mode = models.TextField( 1035 choices=SourceUserMatchingModes.choices, 1036 default=SourceUserMatchingModes.IDENTIFIER, 1037 help_text=_( 1038 "How the source determines if an existing user should be authenticated or " 1039 "a new user enrolled." 1040 ), 1041 ) 1042 group_matching_mode = models.TextField( 1043 choices=SourceGroupMatchingModes.choices, 1044 default=SourceGroupMatchingModes.IDENTIFIER, 1045 help_text=_( 1046 "How the source determines if an existing group should be used or a new group created." 1047 ), 1048 ) 1049 1050 objects = InheritanceManager() 1051 1052 def get_icon_url(self, request=None, use_cache: bool = True) -> str | None: 1053 """Get the URL to the source icon.""" 1054 if not self.icon: 1055 return None 1056 return get_file_manager(FileUsage.MEDIA).file_url(self.icon, request, use_cache=use_cache) 1057 1058 @property 1059 def icon_url(self) -> str | None: 1060 """Get the URL to the source icon""" 1061 return self.get_icon_url() 1062 1063 def get_icon_themed_urls( 1064 self, 1065 request=None, 1066 use_cache: bool = True, 1067 ) -> dict[str, str] | None: 1068 """Get themed URLs for the icon if it contains %(theme)s or is a built-in source icon.""" 1069 if not self.icon: 1070 # Subclasses fall back to a built-in default icon, relative like their icon_url 1071 return get_file_manager(FileUsage.MEDIA).themed_urls(static_url_name(self.icon_url)) 1072 return get_file_manager(FileUsage.MEDIA).themed_urls( 1073 self.icon, 1074 request, 1075 use_cache=use_cache, 1076 ) 1077 1078 @property 1079 def icon_themed_urls(self) -> dict[str, str] | None: 1080 return self.get_icon_themed_urls() 1081 1082 def get_user_path(self) -> str: 1083 """Get user path, fallback to default for formatting errors""" 1084 try: 1085 return self.user_path_template % { 1086 "slug": self.slug, 1087 } 1088 1089 except Exception as exc: # noqa 1090 LOGGER.warning("Failed to template user path", exc=exc, source=self) 1091 return User.default_path() 1092 1093 @property 1094 def component(self) -> str: 1095 """Return component used to edit this object""" 1096 if self.managed == self.MANAGED_INBUILT: 1097 return "" 1098 raise NotImplementedError 1099 1100 @property 1101 def property_mapping_type(self) -> type[PropertyMapping]: 1102 """Return property mapping type used by this object""" 1103 if self.managed == self.MANAGED_INBUILT: 1104 from authentik.core.models import PropertyMapping 1105 1106 return PropertyMapping 1107 raise NotImplementedError 1108 1109 def ui_login_button(self, request: HttpRequest) -> UILoginButton | None: 1110 """If source uses a http-based flow, return UI Information about the login 1111 button. If source doesn't use http-based flow, return None.""" 1112 return None 1113 1114 def ui_user_settings(self) -> UserSettingSerializer | None: 1115 """Entrypoint to integrate with User settings. Can either return None if no 1116 user settings are available, or UserSettingSerializer.""" 1117 return None 1118 1119 def get_base_user_properties(self, **kwargs) -> dict[str, Any | dict[str, Any]]: 1120 """Get base properties for a user to build final properties upon.""" 1121 if self.managed == self.MANAGED_INBUILT: 1122 return {} 1123 raise NotImplementedError 1124 1125 def get_base_group_properties(self, **kwargs) -> dict[str, Any | dict[str, Any]]: 1126 """Get base properties for a group to build final properties upon.""" 1127 if self.managed == self.MANAGED_INBUILT: 1128 return {} 1129 raise NotImplementedError 1130 1131 def __str__(self): 1132 return str(self.name) 1133 1134 class Meta: 1135 indexes = [ 1136 models.Index( 1137 fields=[ 1138 "slug", 1139 ] 1140 ), 1141 models.Index( 1142 fields=[ 1143 "name", 1144 ] 1145 ), 1146 models.Index( 1147 fields=[ 1148 "enabled", 1149 ] 1150 ), 1151 ]
Base Authentication source, i.e. an OAuth Provider, SAML Remote or LDAP Server
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
1052 def get_icon_url(self, request=None, use_cache: bool = True) -> str | None: 1053 """Get the URL to the source icon.""" 1054 if not self.icon: 1055 return None 1056 return get_file_manager(FileUsage.MEDIA).file_url(self.icon, request, use_cache=use_cache)
Get the URL to the source icon.
1058 @property 1059 def icon_url(self) -> str | None: 1060 """Get the URL to the source icon""" 1061 return self.get_icon_url()
Get the URL to the source icon
1063 def get_icon_themed_urls( 1064 self, 1065 request=None, 1066 use_cache: bool = True, 1067 ) -> dict[str, str] | None: 1068 """Get themed URLs for the icon if it contains %(theme)s or is a built-in source icon.""" 1069 if not self.icon: 1070 # Subclasses fall back to a built-in default icon, relative like their icon_url 1071 return get_file_manager(FileUsage.MEDIA).themed_urls(static_url_name(self.icon_url)) 1072 return get_file_manager(FileUsage.MEDIA).themed_urls( 1073 self.icon, 1074 request, 1075 use_cache=use_cache, 1076 )
Get themed URLs for the icon if it contains %(theme)s or is a built-in source icon.
1082 def get_user_path(self) -> str: 1083 """Get user path, fallback to default for formatting errors""" 1084 try: 1085 return self.user_path_template % { 1086 "slug": self.slug, 1087 } 1088 1089 except Exception as exc: # noqa 1090 LOGGER.warning("Failed to template user path", exc=exc, source=self) 1091 return User.default_path()
Get user path, fallback to default for formatting errors
1093 @property 1094 def component(self) -> str: 1095 """Return component used to edit this object""" 1096 if self.managed == self.MANAGED_INBUILT: 1097 return "" 1098 raise NotImplementedError
Return component used to edit this object
1100 @property 1101 def property_mapping_type(self) -> type[PropertyMapping]: 1102 """Return property mapping type used by this object""" 1103 if self.managed == self.MANAGED_INBUILT: 1104 from authentik.core.models import PropertyMapping 1105 1106 return PropertyMapping 1107 raise NotImplementedError
Return property mapping type used by this object
1114 def ui_user_settings(self) -> UserSettingSerializer | None: 1115 """Entrypoint to integrate with User settings. Can either return None if no 1116 user settings are available, or UserSettingSerializer.""" 1117 return None
Entrypoint to integrate with User settings. Can either return None if no user settings are available, or UserSettingSerializer.
1119 def get_base_user_properties(self, **kwargs) -> dict[str, Any | dict[str, Any]]: 1120 """Get base properties for a user to build final properties upon.""" 1121 if self.managed == self.MANAGED_INBUILT: 1122 return {} 1123 raise NotImplementedError
Get base properties for a user to build final properties upon.
1125 def get_base_group_properties(self, **kwargs) -> dict[str, Any | dict[str, Any]]: 1126 """Get base properties for a group to build final properties upon.""" 1127 if self.managed == self.MANAGED_INBUILT: 1128 return {} 1129 raise NotImplementedError
Get base properties for a group to build final properties upon.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Inherited Members
- authentik.policies.models.PolicyBindingModel
- pbm_uuid
- policies
- policy_engine_mode
- supported_policy_binding_targets
- get_policy_engine_mode_display
- bindings
- application
- applicationentitlement
- source
- flow
- flowstagebinding
- notificationrule
- device
- deviceaccessgroup
- oauth2dynamicclientregistration
- userexpirationrule
- request_rule_bindings
- request_rule_child_bindings
- requestrulebinding
- request_rules
- requestrule
- grantrequest_set
- grantrequesttarget_set
The requested object does not exist
The query returned multiple objects when only one was expected.
1154class UserSourceConnection(SerializerModel, CreatedUpdatedModel): 1155 """Connection between User and Source.""" 1156 1157 user = models.ForeignKey(User, on_delete=models.CASCADE) 1158 source = models.ForeignKey(Source, on_delete=models.CASCADE) 1159 identifier = models.TextField() 1160 1161 objects = InheritanceManager() 1162 1163 @property 1164 def serializer(self) -> type[Serializer]: 1165 """Get serializer for this model""" 1166 raise NotImplementedError 1167 1168 def __str__(self) -> str: 1169 return f"User-source connection (user={self.user_id}, source={self.source_id})" 1170 1171 class Meta: 1172 unique_together = (("user", "source"),) 1173 indexes = ( 1174 models.Index(fields=("identifier",)), 1175 models.Index(fields=("source", "identifier")), 1176 )
Connection between User and Source.
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
1163 @property 1164 def serializer(self) -> type[Serializer]: 1165 """Get serializer for this model""" 1166 raise NotImplementedError
Get serializer for this model
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
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.
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.
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.
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.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
1179class GroupSourceConnection(SerializerModel, CreatedUpdatedModel): 1180 """Connection between Group and Source.""" 1181 1182 group = models.ForeignKey(Group, on_delete=models.CASCADE) 1183 source = models.ForeignKey(Source, on_delete=models.CASCADE) 1184 identifier = models.TextField() 1185 1186 objects = InheritanceManager() 1187 1188 @property 1189 def serializer(self) -> type[Serializer]: 1190 """Get serializer for this model""" 1191 raise NotImplementedError 1192 1193 def __str__(self) -> str: 1194 return f"Group-source connection (group={self.group_id}, source={self.source_id})" 1195 1196 class Meta: 1197 unique_together = (("group", "source"),)
Connection between Group and Source.
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
1188 @property 1189 def serializer(self) -> type[Serializer]: 1190 """Get serializer for this model""" 1191 raise NotImplementedError
Get serializer for this model
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
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.
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.
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.
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.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
1200class TokenIntents(models.TextChoices): 1201 """Intents a Token can be created for.""" 1202 1203 # Single use token 1204 INTENT_VERIFICATION = "verification" 1205 1206 # Allow access to API 1207 INTENT_API = "api" 1208 1209 # Recovery use for the recovery app 1210 INTENT_RECOVERY = "recovery" 1211 1212 # App-specific passwords 1213 INTENT_APP_PASSWORD = "app_password" # nosec
Intents a Token can be created for.
1216class Token(SerializerModel, ManagedModel, ExpiringModel): 1217 """Token used to authenticate the User for API Access or confirm another Stage like Email.""" 1218 1219 token_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 1220 identifier = models.SlugField(max_length=255, unique=True) 1221 key = models.TextField(default=default_token_key) 1222 intent = models.TextField( 1223 choices=TokenIntents.choices, default=TokenIntents.INTENT_VERIFICATION 1224 ) 1225 user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="+") 1226 description = models.TextField(default="", blank=True) 1227 1228 class Meta: 1229 verbose_name = _("Token") 1230 verbose_name_plural = _("Tokens") 1231 indexes = ExpiringModel.Meta.indexes + [ 1232 models.Index(fields=["identifier"]), 1233 models.Index(fields=["key"]), 1234 ] 1235 permissions = [ 1236 ("view_token_key", _("View token's key")), 1237 ("set_token_key", _("Set a token's key")), 1238 ] 1239 1240 def __str__(self): 1241 description = f"{self.identifier}" 1242 if self.expiring: 1243 description += f" (expires={self.expires})" 1244 return description 1245 1246 @property 1247 def serializer(self) -> type[Serializer]: 1248 from authentik.core.api.tokens import TokenSerializer 1249 1250 return TokenSerializer 1251 1252 def expire_action(self, *args, **kwargs): 1253 """Handler which is called when this object is expired.""" 1254 from authentik.events.models import Event, EventAction 1255 1256 if ( 1257 self.intent 1258 in [ 1259 TokenIntents.INTENT_RECOVERY, 1260 TokenIntents.INTENT_VERIFICATION, 1261 TokenIntents.INTENT_APP_PASSWORD, 1262 ] 1263 or Actor.objects.filter(pk=self.user_id).exists() 1264 ): 1265 super().expire_action(*args, **kwargs) 1266 return 1267 1268 self.key = default_token_key() 1269 self.expires = default_token_duration() 1270 self.save(*args, **kwargs) 1271 Event.new( 1272 action=EventAction.SECRET_ROTATE, 1273 token=self, 1274 message=f"Token {self.identifier}'s secret was rotated.", 1275 ).save()
Token used to authenticate the User for API Access or confirm another Stage like Email.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
1246 @property 1247 def serializer(self) -> type[Serializer]: 1248 from authentik.core.api.tokens import TokenSerializer 1249 1250 return TokenSerializer
Get serializer for this model
1252 def expire_action(self, *args, **kwargs): 1253 """Handler which is called when this object is expired.""" 1254 from authentik.events.models import Event, EventAction 1255 1256 if ( 1257 self.intent 1258 in [ 1259 TokenIntents.INTENT_RECOVERY, 1260 TokenIntents.INTENT_VERIFICATION, 1261 TokenIntents.INTENT_APP_PASSWORD, 1262 ] 1263 or Actor.objects.filter(pk=self.user_id).exists() 1264 ): 1265 super().expire_action(*args, **kwargs) 1266 return 1267 1268 self.key = default_token_key() 1269 self.expires = default_token_duration() 1270 self.save(*args, **kwargs) 1271 Event.new( 1272 action=EventAction.SECRET_ROTATE, 1273 token=self, 1274 message=f"Token {self.identifier}'s secret was rotated.", 1275 ).save()
Handler which is called when this object is expired.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
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.
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.
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.
The requested object does not exist
The query returned multiple objects when only one was expected.
1278class PropertyMapping(SerializerModel, ManagedModel): 1279 """User-defined key -> x mapping which can be used by providers to expose extra data.""" 1280 1281 pm_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 1282 name = models.TextField(unique=True) 1283 expression = models.TextField() 1284 1285 objects = InheritanceManager() 1286 1287 # Types the expression may return (besides None); empty allows any type 1288 expression_allowed_types: list[type] = [] 1289 1290 @property 1291 def component(self) -> str: 1292 """Return component used to edit this object""" 1293 raise NotImplementedError 1294 1295 @property 1296 def serializer(self) -> type[Serializer]: 1297 """Get serializer for this model""" 1298 raise NotImplementedError 1299 1300 def evaluate( 1301 self, 1302 user: User | None, 1303 request: HttpRequest | None, 1304 globals: dict[str, Any] | None = None, 1305 **kwargs, 1306 ) -> Any: 1307 """Evaluate `self.expression` using `**kwargs` as Context.""" 1308 from authentik.core.expression.evaluator import PropertyMappingEvaluator 1309 1310 evaluator = PropertyMappingEvaluator(self, user, request, **kwargs) 1311 evaluator.allowed_types = self.expression_allowed_types 1312 if globals: 1313 evaluator._globals.update(globals) 1314 try: 1315 return evaluator.evaluate(self.expression) 1316 except ControlFlowException as exc: 1317 raise exc 1318 except Exception as exc: 1319 raise PropertyMappingExpressionException(exc, self) from exc 1320 1321 def __str__(self): 1322 return f"Property Mapping {self.name}" 1323 1324 class Meta: 1325 verbose_name = _("Property Mapping") 1326 verbose_name_plural = _("Property Mappings")
User-defined key -> x mapping which can be used by providers to expose extra data.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
1290 @property 1291 def component(self) -> str: 1292 """Return component used to edit this object""" 1293 raise NotImplementedError
Return component used to edit this object
1295 @property 1296 def serializer(self) -> type[Serializer]: 1297 """Get serializer for this model""" 1298 raise NotImplementedError
Get serializer for this model
1300 def evaluate( 1301 self, 1302 user: User | None, 1303 request: HttpRequest | None, 1304 globals: dict[str, Any] | None = None, 1305 **kwargs, 1306 ) -> Any: 1307 """Evaluate `self.expression` using `**kwargs` as Context.""" 1308 from authentik.core.expression.evaluator import PropertyMappingEvaluator 1309 1310 evaluator = PropertyMappingEvaluator(self, user, request, **kwargs) 1311 evaluator.allowed_types = self.expression_allowed_types 1312 if globals: 1313 evaluator._globals.update(globals) 1314 try: 1315 return evaluator.evaluate(self.expression) 1316 except ControlFlowException as exc: 1317 raise exc 1318 except Exception as exc: 1319 raise PropertyMappingExpressionException(exc, self) from exc
Evaluate self.expression using **kwargs as Context.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
1329class SourceUserPropertyMapping(SimpleThroughModel): 1330 property_mapping = models.ForeignKey( 1331 PropertyMapping, on_delete=models.CASCADE, db_column="propertymapping_id" 1332 ) 1333 source = models.ForeignKey(Source, on_delete=models.CASCADE) 1334 1335 class Meta: 1336 db_table = "authentik_core_source_user_property_mappings" 1337 unique_together = (("property_mapping", "source"),) 1338 verbose_name = _("Source User Property Mapping") 1339 verbose_name_plural = _("Source User Property Mappings") 1340 1341 def __str__(self): 1342 return ( 1343 f"SourceUserPropertyMapping for Source {self.source_id} " 1344 f"and PropertyMapping {self.property_mapping_id}." 1345 )
SourceUserPropertyMapping(id, property_mapping, source)
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
1348class SourceGroupPropertyMapping(SimpleThroughModel): 1349 property_mapping = models.ForeignKey( 1350 PropertyMapping, on_delete=models.CASCADE, db_column="propertymapping_id" 1351 ) 1352 source = models.ForeignKey(Source, on_delete=models.CASCADE) 1353 1354 class Meta: 1355 db_table = "authentik_core_source_group_property_mappings" 1356 unique_together = (("property_mapping", "source"),) 1357 verbose_name = _("Source Group Property Mapping") 1358 verbose_name_plural = _("Source Group Property Mappings") 1359 1360 def __str__(self): 1361 return ( 1362 f"SourceGroupPropertyMapping for Source {self.source_id} " 1363 f"and PropertyMapping {self.property_mapping_id}." 1364 )
SourceGroupPropertyMapping(id, property_mapping, source)
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
1367class ProviderPropertyMapping(SimpleThroughModel): 1368 property_mapping = models.ForeignKey( 1369 PropertyMapping, on_delete=models.CASCADE, db_column="propertymapping_id" 1370 ) 1371 provider = models.ForeignKey(Provider, on_delete=models.CASCADE) 1372 1373 class Meta: 1374 db_table = "authentik_core_provider_property_mappings" 1375 unique_together = (("property_mapping", "provider"),) 1376 verbose_name = _("Provider Property Mapping") 1377 verbose_name_plural = _("Provider Property Mappings") 1378 1379 def __str__(self): 1380 return ( 1381 f"ProviderPropertyMapping for Provider {self.provider_id} " 1382 f"and PropertyMapping {self.property_mapping_id}." 1383 )
ProviderPropertyMapping(id, property_mapping, provider)
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
1386class UserRole(SimpleThroughModel): 1387 user = models.ForeignKey(User, on_delete=models.CASCADE) 1388 role = models.ForeignKey(Role, on_delete=models.CASCADE) 1389 1390 class Meta: 1391 db_table = "authentik_core_user_roles" 1392 unique_together = (("user", "role"),) 1393 verbose_name = _("User Role") 1394 verbose_name_plural = _("User Roles") 1395 1396 def __str__(self): 1397 return f"UserRole for User {self.user_id} and Role {self.role_id}."
UserRole(id, user, role)
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
1400class GroupRole(SimpleThroughModel): 1401 group = models.ForeignKey(Group, on_delete=models.CASCADE) 1402 role = models.ForeignKey(Role, on_delete=models.CASCADE) 1403 1404 class Meta: 1405 db_table = "authentik_core_group_roles" 1406 unique_together = (("group", "role"),) 1407 verbose_name = _("Group Role") 1408 verbose_name_plural = _("Group Roles") 1409 1410 def __str__(self): 1411 return f"GroupRole for Group {self.group_id} and Role {self.role_id}."
GroupRole(id, group, role)
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
1414class UserGroup(SimpleThroughModel): 1415 user = models.ForeignKey(User, on_delete=models.CASCADE) 1416 group = models.ForeignKey(Group, on_delete=models.CASCADE) 1417 1418 class Meta: 1419 db_table = "authentik_core_user_groups" 1420 unique_together = (("user", "group"),) 1421 verbose_name = _("User Group") 1422 verbose_name_plural = _("User Groups") 1423 1424 def __str__(self): 1425 return f"UserGroup for User {self.user_id} and Group {self.group_id}."
UserGroup(id, user, 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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
1428class Session(ExpiringModel, AbstractBaseSession): 1429 """User session with extra fields for fast access""" 1430 1431 # Remove upstream field because we're using our own ExpiringModel 1432 expire_date = None 1433 session_data = models.BinaryField(_("session data")) 1434 1435 # Keep in sync with Session.Keys 1436 last_ip = models.GenericIPAddressField() 1437 last_user_agent = models.TextField(blank=True) 1438 last_used = models.DateTimeField(auto_now=True) 1439 1440 class Meta: 1441 verbose_name = _("Session") 1442 verbose_name_plural = _("Sessions") 1443 indexes = ExpiringModel.Meta.indexes + [ 1444 models.Index(fields=["expires", "session_key"]), 1445 ] 1446 default_permissions = [] 1447 1448 def __str__(self): 1449 return self.session_key 1450 1451 class Keys(StrEnum): 1452 """ 1453 Keys to be set with the session interface for the fields above to be updated. 1454 1455 If a field is added here that needs to be initialized when the session is initialized, 1456 it must also be reflected in authentik.root.middleware.SessionMiddleware.process_request 1457 and in authentik.core.sessions.SessionStore.__init__ 1458 """ 1459 1460 LAST_IP = "last_ip" 1461 LAST_USER_AGENT = "last_user_agent" 1462 LAST_USED = "last_used" 1463 1464 @classmethod 1465 def get_session_store_class(cls): 1466 from authentik.core.sessions import SessionStore 1467 1468 return SessionStore 1469 1470 def get_decoded(self): 1471 raise NotImplementedError
User session with extra fields for fast access
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
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.
Inherited Members
1451 class Keys(StrEnum): 1452 """ 1453 Keys to be set with the session interface for the fields above to be updated. 1454 1455 If a field is added here that needs to be initialized when the session is initialized, 1456 it must also be reflected in authentik.root.middleware.SessionMiddleware.process_request 1457 and in authentik.core.sessions.SessionStore.__init__ 1458 """ 1459 1460 LAST_IP = "last_ip" 1461 LAST_USER_AGENT = "last_user_agent" 1462 LAST_USED = "last_used"
Keys to be set with the session interface for the fields above to be updated.
If a field is added here that needs to be initialized when the session is initialized, it must also be reflected in authentik.root.middleware.SessionMiddleware.process_request and in authentik.core.sessions.SessionStore.__init__
The requested object does not exist
The query returned multiple objects when only one was expected.
1474class UserSwitchingSession(models.Model): 1475 """Sessions grouped by one browser's user-switching cookie.""" 1476 1477 token = models.CharField(max_length=64, primary_key=True) 1478 current_session = models.OneToOneField( 1479 "authentik_core.AuthenticatedSession", 1480 null=True, 1481 on_delete=models.SET_NULL, 1482 related_name="+", 1483 ) 1484 1485 class Meta: 1486 verbose_name = _("User Switching Session") 1487 verbose_name_plural = _("User Switching Sessions") 1488 default_permissions = [] 1489 1490 def __str__(self) -> str: 1491 return f"User Switching Session {self.token[:10]}"
Sessions grouped by one browser's user-switching cookie.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
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.
The requested object does not exist
The query returned multiple objects when only one was expected.
1494class AuthenticatedSession(SerializerModel): 1495 session = models.OneToOneField(Session, on_delete=models.CASCADE, primary_key=True) 1496 # We use the session as primary key, but we need the API to be able to reference 1497 # this object uniquely without exposing the session key 1498 uuid = models.UUIDField(default=uuid4, unique=True) 1499 1500 user = models.ForeignKey(User, on_delete=models.CASCADE) 1501 1502 user_switching_session = models.ForeignKey( 1503 UserSwitchingSession, 1504 null=True, 1505 on_delete=models.SET_NULL, 1506 related_name="authenticated_sessions", 1507 ) 1508 1509 @property 1510 def is_current(self) -> bool: 1511 """Whether this is the current login for its browser.""" 1512 return ( 1513 self.user_switching_session_id is None 1514 or self.user_switching_session.current_session_id == self.session_id 1515 ) 1516 1517 @property 1518 def serializer(self) -> type[Serializer]: 1519 from authentik.core.api.authenticated_sessions import AuthenticatedSessionSerializer 1520 1521 return AuthenticatedSessionSerializer 1522 1523 @classmethod 1524 def from_request(cls, request: HttpRequest, user: User) -> Self | None: 1525 """Return an in-memory authenticated session for the request's session. 1526 1527 This does not touch the database; because ``session`` is the primary key the 1528 returned instance can be used to look up related objects. Callers that want to 1529 persist a login should use ``create_from_request`` instead.""" 1530 if not hasattr(request, "session") or not request.session.exists( 1531 request.session.session_key 1532 ): 1533 return None 1534 return cls( 1535 session=Session.objects.filter(session_key=request.session.session_key).first(), 1536 user=user, 1537 ) 1538 1539 @classmethod 1540 def create_from_request(cls, request: HttpRequest, user: User) -> Self | None: 1541 """Persist the request's session as the current login and bind the switching token.""" 1542 from authentik.core import user_switching 1543 1544 if not hasattr(request, "session") or not request.session.exists( 1545 request.session.session_key 1546 ): 1547 return None 1548 session = Session.objects.filter(session_key=request.session.session_key).first() 1549 if session is None: 1550 return None 1551 authenticated_session, _ = cls.objects.update_or_create( 1552 session=session, 1553 defaults={"user": user}, 1554 ) 1555 token = user_switching.ensure_request_token(request) 1556 if token: 1557 user_switching.activate_session(session.session_key, token) 1558 authenticated_session.user_switching_session_id = token 1559 return authenticated_session 1560 1561 class Meta: 1562 verbose_name = _("Authenticated Session") 1563 verbose_name_plural = _("Authenticated Sessions") 1564 1565 def __str__(self) -> str: 1566 return f"Authenticated Session {str(self.pk)[:10]}"
AuthenticatedSession(session, uuid, user, user_switching_session)
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
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.
1509 @property 1510 def is_current(self) -> bool: 1511 """Whether this is the current login for its browser.""" 1512 return ( 1513 self.user_switching_session_id is None 1514 or self.user_switching_session.current_session_id == self.session_id 1515 )
Whether this is the current login for its browser.
1517 @property 1518 def serializer(self) -> type[Serializer]: 1519 from authentik.core.api.authenticated_sessions import AuthenticatedSessionSerializer 1520 1521 return AuthenticatedSessionSerializer
Get serializer for this model
1523 @classmethod 1524 def from_request(cls, request: HttpRequest, user: User) -> Self | None: 1525 """Return an in-memory authenticated session for the request's session. 1526 1527 This does not touch the database; because ``session`` is the primary key the 1528 returned instance can be used to look up related objects. Callers that want to 1529 persist a login should use ``create_from_request`` instead.""" 1530 if not hasattr(request, "session") or not request.session.exists( 1531 request.session.session_key 1532 ): 1533 return None 1534 return cls( 1535 session=Session.objects.filter(session_key=request.session.session_key).first(), 1536 user=user, 1537 )
Return an in-memory authenticated session for the request's session.
This does not touch the database; because session is the primary key the
returned instance can be used to look up related objects. Callers that want to
persist a login should use create_from_request instead.
1539 @classmethod 1540 def create_from_request(cls, request: HttpRequest, user: User) -> Self | None: 1541 """Persist the request's session as the current login and bind the switching token.""" 1542 from authentik.core import user_switching 1543 1544 if not hasattr(request, "session") or not request.session.exists( 1545 request.session.session_key 1546 ): 1547 return None 1548 session = Session.objects.filter(session_key=request.session.session_key).first() 1549 if session is None: 1550 return None 1551 authenticated_session, _ = cls.objects.update_or_create( 1552 session=session, 1553 defaults={"user": user}, 1554 ) 1555 token = user_switching.ensure_request_token(request) 1556 if token: 1557 user_switching.activate_session(session.session_key, token) 1558 authenticated_session.user_switching_session_id = token 1559 return authenticated_session
Persist the request's session as the current login and bind the switching token.
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.
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.
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.
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.
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.
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.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
1569class ObjectAttribute(SerializerModel, ManagedModel, CreatedUpdatedModel): 1570 """User-defined schema for models' `attributes` JSON field.""" 1571 1572 class AttributeType(models.TextChoices): 1573 TEXT = "text" 1574 NUMBER = "number" 1575 BOOLEAN = "boolean" 1576 1577 attribute_id = models.UUIDField(default=uuid4, primary_key=True) 1578 1579 enabled = models.BooleanField(default=True) 1580 1581 object_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) 1582 label = models.TextField() 1583 group = models.TextField(blank=True) 1584 key = models.TextField() 1585 1586 type = models.TextField(choices=AttributeType.choices) 1587 is_unique = models.BooleanField(default=False) 1588 is_required = models.BooleanField(default=False) 1589 regex = models.TextField(blank=True) 1590 # Currently not accessible via API/UI, as there are some challenges UI-wise 1591 # with regards to merging data 1592 # https://github.com/goauthentik/authentik/issues/24250 1593 is_array = models.BooleanField(default=False) 1594 1595 def run_validation(self, value: Any, instance: models.Model | None = None) -> None: 1596 err_key = f"attributes_{self.key}" 1597 1598 if self.is_required and value is None: 1599 raise ValidationError({err_key: _("This field is required")}) 1600 if value is None: 1601 return 1602 1603 field_kwargs = {} 1604 1605 match self.type: 1606 case self.AttributeType.TEXT: 1607 field_cls = CharField 1608 field_kwargs["allow_blank"] = True 1609 case self.AttributeType.NUMBER: 1610 field_cls = IntegerField 1611 case self.AttributeType.BOOLEAN: 1612 field_cls = BooleanField 1613 case _: 1614 raise ValidationError("Invalid field type") 1615 1616 field = field_cls(required=False, **field_kwargs) 1617 if self.is_array: 1618 field = ListField( 1619 child=field, 1620 required=False, 1621 error_messages={"not_a_list": _("Value must be an array.")}, 1622 ) 1623 1624 try: 1625 field.run_validation(value) 1626 except ValidationError as exc: 1627 raise ValidationError({err_key: exc.detail}) from exc 1628 1629 if self.regex != "": 1630 values = value if self.is_array else [value] 1631 if not all(re.fullmatch(self.regex, str(v)) for v in values): 1632 raise ValidationError({err_key: _("Value does not match configured pattern.")}) 1633 1634 if not self.is_array and self.is_unique: 1635 model: type[models.Model] = self.object_type.model_class() 1636 lookup_key = f"attributes__{self.key.replace('.', '__')}" 1637 existing = model.objects.filter(**{lookup_key: value}) 1638 # The row being saved already has this value; uniqueness is against other objects. 1639 if instance is not None and isinstance(instance, model) and instance.pk is not None: 1640 existing = existing.exclude(pk=instance.pk) 1641 if existing.exists(): 1642 raise ValidationError({err_key: _("Value is not unique.")}) 1643 1644 @property 1645 def serializer(self) -> type[Serializer]: 1646 from authentik.core.api.object_attributes import ObjectAttributeSerializer 1647 1648 return ObjectAttributeSerializer 1649 1650 def __str__(self): 1651 return f"Object attribute '{self.key}' for content type {self.object_type_id}" 1652 1653 class Meta: 1654 verbose_name = _("Object Attribute") 1655 verbose_name_plural = _("Object Attributes") 1656 unique_together = (("object_type", "key", "enabled"),)
User-defined schema for models' attributes JSON field.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
1595 def run_validation(self, value: Any, instance: models.Model | None = None) -> None: 1596 err_key = f"attributes_{self.key}" 1597 1598 if self.is_required and value is None: 1599 raise ValidationError({err_key: _("This field is required")}) 1600 if value is None: 1601 return 1602 1603 field_kwargs = {} 1604 1605 match self.type: 1606 case self.AttributeType.TEXT: 1607 field_cls = CharField 1608 field_kwargs["allow_blank"] = True 1609 case self.AttributeType.NUMBER: 1610 field_cls = IntegerField 1611 case self.AttributeType.BOOLEAN: 1612 field_cls = BooleanField 1613 case _: 1614 raise ValidationError("Invalid field type") 1615 1616 field = field_cls(required=False, **field_kwargs) 1617 if self.is_array: 1618 field = ListField( 1619 child=field, 1620 required=False, 1621 error_messages={"not_a_list": _("Value must be an array.")}, 1622 ) 1623 1624 try: 1625 field.run_validation(value) 1626 except ValidationError as exc: 1627 raise ValidationError({err_key: exc.detail}) from exc 1628 1629 if self.regex != "": 1630 values = value if self.is_array else [value] 1631 if not all(re.fullmatch(self.regex, str(v)) for v in values): 1632 raise ValidationError({err_key: _("Value does not match configured pattern.")}) 1633 1634 if not self.is_array and self.is_unique: 1635 model: type[models.Model] = self.object_type.model_class() 1636 lookup_key = f"attributes__{self.key.replace('.', '__')}" 1637 existing = model.objects.filter(**{lookup_key: value}) 1638 # The row being saved already has this value; uniqueness is against other objects. 1639 if instance is not None and isinstance(instance, model) and instance.pk is not None: 1640 existing = existing.exclude(pk=instance.pk) 1641 if existing.exists(): 1642 raise ValidationError({err_key: _("Value is not unique.")})
1644 @property 1645 def serializer(self) -> type[Serializer]: 1646 from authentik.core.api.object_attributes import ObjectAttributeSerializer 1647 1648 return ObjectAttributeSerializer
Get serializer for this model
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Inherited Members
1572 class AttributeType(models.TextChoices): 1573 TEXT = "text" 1574 NUMBER = "number" 1575 BOOLEAN = "boolean"
Class for creating enumerated string choices.
The requested object does not exist
The query returned multiple objects when only one was expected.
1659class ActorPolicyInheritance(models.TextChoices): 1660 1661 MIRROR = "mirror", _("Mirror policy engine") 1662 COPY = "copy", _("Copy policy bindings") 1663 NONE = "none", _("Don't inherit any policy bindings")
Class for creating enumerated string choices.
1666class Actor(ExpiringModel, User): 1667 """Generic actor which can either perform tasks by itself 1668 or on behalf of a parent user.""" 1669 1670 parent = models.ForeignKey( 1671 User, on_delete=models.SET_DEFAULT, default=None, null=True, related_name="actors" 1672 ) 1673 policy_behavior = models.TextField(choices=ActorPolicyInheritance) 1674 1675 class Meta(ExpiringModel.Meta): 1676 verbose_name = _("Actor") 1677 verbose_name_plural = _("Actors") 1678 1679 def save(self, *args, **kwargs): 1680 # policy_behavior determines how the actor derives access and may only be chosen at 1681 # creation time; changing it afterwards is rejected. 1682 if ( 1683 not self._state.adding 1684 and hasattr(self, "_original_policy_behavior") 1685 and self._original_policy_behavior != self.policy_behavior 1686 ): 1687 raise ValidationError( 1688 {"policy_behavior": _("Policy behavior cannot be changed after creation.")} 1689 ) 1690 super().save(*args, **kwargs) 1691 self._original_policy_behavior = self.policy_behavior 1692 1693 @classmethod 1694 def from_db(cls, db, field_names, values): 1695 instance = super().from_db(db, field_names, values) 1696 instance._original_policy_behavior = instance.policy_behavior 1697 return instance 1698 1699 def copy_parent_policy_bindings(self): 1700 """Snapshot the parent's directly-assigned policy bindings onto this actor. 1701 1702 Unlike MIRROR (which defers to the parent live), COPY takes an independent snapshot at 1703 creation: the actor holds its own PolicyBindings, so later changes to the parent don't 1704 affect it. Only bindings that reference the parent as a *user* are copied -- access the 1705 parent derives from group membership is not (use MIRROR, or add the actor to groups). 1706 """ 1707 from authentik.policies.models import PolicyBinding 1708 1709 if not self.parent_id: 1710 return 1711 for binding in PolicyBinding.objects.filter(user_id=self.parent_id): 1712 binding.pk = None 1713 binding.policy_binding_uuid = uuid4() 1714 binding._state.adding = True 1715 binding.user = self 1716 binding.save() 1717 1718 @staticmethod 1719 def for_user(user: User | None, policy_behavior: ActorPolicyInheritance, **kwargs): 1720 prefix = f"{user.username}" if user else "global" 1721 actor = Actor.objects.create( 1722 username=f"{prefix}-{generate_id()}"[:USERNAME_MAX_LENGTH], 1723 parent=user, 1724 policy_behavior=policy_behavior, 1725 type=UserTypes.SERVICE_ACCOUNT, 1726 **kwargs, 1727 ) 1728 return actor
Generic actor which can either perform tasks by itself or on behalf of a parent 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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
1679 def save(self, *args, **kwargs): 1680 # policy_behavior determines how the actor derives access and may only be chosen at 1681 # creation time; changing it afterwards is rejected. 1682 if ( 1683 not self._state.adding 1684 and hasattr(self, "_original_policy_behavior") 1685 and self._original_policy_behavior != self.policy_behavior 1686 ): 1687 raise ValidationError( 1688 {"policy_behavior": _("Policy behavior cannot be changed after creation.")} 1689 ) 1690 super().save(*args, **kwargs) 1691 self._original_policy_behavior = self.policy_behavior
Save the current instance. Override this in a subclass if you want to control the saving process.
The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.
1699 def copy_parent_policy_bindings(self): 1700 """Snapshot the parent's directly-assigned policy bindings onto this actor. 1701 1702 Unlike MIRROR (which defers to the parent live), COPY takes an independent snapshot at 1703 creation: the actor holds its own PolicyBindings, so later changes to the parent don't 1704 affect it. Only bindings that reference the parent as a *user* are copied -- access the 1705 parent derives from group membership is not (use MIRROR, or add the actor to groups). 1706 """ 1707 from authentik.policies.models import PolicyBinding 1708 1709 if not self.parent_id: 1710 return 1711 for binding in PolicyBinding.objects.filter(user_id=self.parent_id): 1712 binding.pk = None 1713 binding.policy_binding_uuid = uuid4() 1714 binding._state.adding = True 1715 binding.user = self 1716 binding.save()
Snapshot the parent's directly-assigned policy bindings onto this actor.
Unlike MIRROR (which defers to the parent live), COPY takes an independent snapshot at creation: the actor holds its own PolicyBindings, so later changes to the parent don't affect it. Only bindings that reference the parent as a user are copied -- access the parent derives from group membership is not (use MIRROR, or add the actor to groups).
1718 @staticmethod 1719 def for_user(user: User | None, policy_behavior: ActorPolicyInheritance, **kwargs): 1720 prefix = f"{user.username}" if user else "global" 1721 actor = Actor.objects.create( 1722 username=f"{prefix}-{generate_id()}"[:USERNAME_MAX_LENGTH], 1723 parent=user, 1724 policy_behavior=policy_behavior, 1725 type=UserTypes.SERVICE_ACCOUNT, 1726 **kwargs, 1727 ) 1728 return actor
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
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.
Inherited Members
- User
- user_permissions
- uuid
- name
- path
- type
- sources
- groups
- roles
- last_updated
- default_path
- all_groups
- all_roles
- get_managed_role
- get_all_model_perms_on_managed_role
- get_all_obj_perms_on_managed_role
- assign_perms_to_managed_role
- remove_perms_from_managed_role
- remove_all_perms_from_managed_role
- group_attributes
- app_entitlements
- all_app_entitlements
- app_entitlements_attributes
- serializer
- is_superuser
- is_staff
- ak_groups
- password
- password_change_date
- check_password
- acheck_password
- set_password
- set_unusable_password
- uid
- locale
- avatar
- attributes
- username
- first_name
- last_name
- is_active
- date_joined
- last_login
- get_type_display
- get_next_by_last_updated
- get_previous_by_last_updated
- get_next_by_date_joined
- get_previous_by_date_joined
- id
- policybinding_set
- usersourceconnection_set
- userrole_set
- usergroup_set
- authenticatedsession_set
- actors
- actor
- activity
- notification_set
- password_device
- deviceauthenticationtoken_set
- appleindependentsecureenclave_set
- invitation_set
- accesstoken_set
- actor_for_accesstokens
- refreshtoken_set
- actor_for_refreshtokens
- devicetoken_set
- samlsession_set
- scimprovideruser_set
- scimprovider_set
- staticdevice_set
- duodevice_set
- emaildevice_set
- smsdevice_set
- webauthndevice_set
- scimsourceuser_set
- totpdevice_set
- userconsent_set
- lifecyclerule_set
- lifecyclerulereviewer_set
- review_set
- offboardings
- old_passwords
- googleworkspaceprovideruser_set
- microsoftentraprovideruser_set
- dataexport_set
- grant_requests_created
- grant_requests_fulfilled
- grant_requests_revoked
- agent_grant_requests
- grantrequestapproval_set
- endpointdevice_set
The requested object does not exist
The query returned multiple objects when only one was expected.
1731class UserActivityManager(models.Manager["UserActivity"]): 1732 """Record successful activity without rewriting frequently active users.""" 1733 1734 def record(self, user_id: Any, at: datetime | None = None) -> None: 1735 if type(user_id) is not int or not 0 < user_id <= 2147483647: # noqa: PLR2004 1736 return 1737 excluded = ExcludedCol(self.model._meta.get_field("last_activity_at")) 1738 with postgres_manager(self.model) as manager: 1739 manager.on_conflict( 1740 ["user_id"], 1741 ConflictAction.UPDATE, 1742 update_condition=Q(last_activity_at__lte=excluded - USER_ACTIVITY_INTERVAL), 1743 update_values={"last_activity_at": excluded}, 1744 ).insert(user_id=user_id, last_activity_at=at or now())
Record successful activity without rewriting frequently active users.
1734 def record(self, user_id: Any, at: datetime | None = None) -> None: 1735 if type(user_id) is not int or not 0 < user_id <= 2147483647: # noqa: PLR2004 1736 return 1737 excluded = ExcludedCol(self.model._meta.get_field("last_activity_at")) 1738 with postgres_manager(self.model) as manager: 1739 manager.on_conflict( 1740 ["user_id"], 1741 ConflictAction.UPDATE, 1742 update_condition=Q(last_activity_at__lte=excluded - USER_ACTIVITY_INTERVAL), 1743 update_values={"last_activity_at": excluded}, 1744 ).insert(user_id=user_id, last_activity_at=at or now())
1747class UserActivity(models.Model): 1748 """Latest sampled successful activity, independent of audit retention.""" 1749 1750 # A late write after user deletion may leave an orphan; expiration joins existing users. 1751 user = models.OneToOneField( 1752 User, 1753 on_delete=models.CASCADE, 1754 primary_key=True, 1755 related_name="activity", 1756 db_constraint=False, 1757 ) 1758 last_activity_at = models.DateTimeField() 1759 objects = UserActivityManager() 1760 1761 def __str__(self): 1762 return f"Activity for user {self.user_id}"
Latest sampled successful activity, independent of audit retention.
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
The requested object does not exist
The query returned multiple objects when only one was expected.