This repository has been archived on 2024-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
authentik/authentik/core/models.py

514 lines
17 KiB
Python
Raw Normal View History

2020-12-05 21:08:42 +00:00
"""authentik core models"""
from datetime import timedelta
from hashlib import md5, sha256
from typing import Any, Optional, Type
from urllib.parse import urlencode
from uuid import uuid4
2018-11-11 12:41:48 +00:00
from deepmerge import always_merger
from django.conf import settings
2018-11-11 12:41:48 +00:00
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import UserManager as DjangoUserManager
from django.core import validators
2018-11-11 12:41:48 +00:00
from django.db import models
from django.db.models import Q, QuerySet, options
from django.http import HttpRequest
from django.templatetags.static import static
2020-09-25 21:59:06 +00:00
from django.utils.functional import cached_property
from django.utils.html import escape
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from guardian.mixins import GuardianUserMixin
2018-11-16 08:10:35 +00:00
from model_utils.managers import InheritanceManager
2020-12-16 20:38:40 +00:00
from rest_framework.serializers import Serializer
from structlog.stdlib import get_logger
2018-11-11 12:41:48 +00:00
2020-12-05 21:08:42 +00:00
from authentik.core.exceptions import PropertyMappingExpressionException
from authentik.core.signals import password_changed
from authentik.core.types import UILoginButton, UserSettingSerializer
2020-12-05 21:08:42 +00:00
from authentik.flows.models import Flow
from authentik.lib.config import CONFIG
web: remove policy bindings page (#370) * admin: accept ?target for PolicyBindingCreateView * core: fix rendering of hidden fields in horizontal form * web: add create button for application's bound policies * admin: fix delete form not working * web: fix ak-refresh event not being dispatched correctly * web: fix linting errors * admin: fix tests not loading * build(deps-dev): bump eslint from 7.14.0 to 7.15.0 in /web (#372) Bumps [eslint](https://github.com/eslint/eslint) from 7.14.0 to 7.15.0. - [Release notes](https://github.com/eslint/eslint/releases) - [Changelog](https://github.com/eslint/eslint/blob/master/CHANGELOG.md) - [Commits](https://github.com/eslint/eslint/compare/v7.14.0...v7.15.0) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * build(deps): bump rollup from 2.34.1 to 2.34.2 in /web (#373) Bumps [rollup](https://github.com/rollup/rollup) from 2.34.1 to 2.34.2. - [Release notes](https://github.com/rollup/rollup/releases) - [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md) - [Commits](https://github.com/rollup/rollup/compare/v2.34.1...v2.34.2) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * build(deps): bump @types/codemirror from 0.0.100 to 0.0.102 in /web (#374) Bumps [@types/codemirror](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/codemirror) from 0.0.100 to 0.0.102. - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/codemirror) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * build(deps-dev): bump bandit from 1.6.2 to 1.6.3 (#371) * build(deps-dev): bump bandit from 1.6.2 to 1.6.3 Bumps [bandit](https://github.com/PyCQA/bandit) from 1.6.2 to 1.6.3. - [Release notes](https://github.com/PyCQA/bandit/releases) - [Commits](https://github.com/PyCQA/bandit/compare/1.6.2...1.6.3) Signed-off-by: dependabot[bot] <support@github.com> * root: update for new bandit version Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Jens Langhammer <jens.langhammer@beryju.org> * web: add header to bound-policies * web: fix spacing between bulk_select buttons * web: add separate ak-bound-policies-list, add flow view page * web: fix flows' policies not loading * Squashed commit of the following: commit e535cb0ec82f38e6cfbe1a1ba4e1b49dd518d669 Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu Dec 10 09:58:07 2020 +0100 build(deps): bump boto3 from 1.16.32 to 1.16.33 (#383) Bumps [boto3](https://github.com/boto/boto3) from 1.16.32 to 1.16.33. - [Release notes](https://github.com/boto/boto3/releases) - [Changelog](https://github.com/boto/boto3/blob/develop/CHANGELOG.rst) - [Commits](https://github.com/boto/boto3/compare/1.16.32...1.16.33) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> commit 8c1f55d3e3cfd88257b1e9eb285c3aeeccb941a9 Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed Dec 9 09:06:45 2020 +0100 build(deps): bump boto3 from 1.16.31 to 1.16.32 (#382) Bumps [boto3](https://github.com/boto/boto3) from 1.16.31 to 1.16.32. - [Release notes](https://github.com/boto/boto3/releases) - [Changelog](https://github.com/boto/boto3/blob/develop/CHANGELOG.rst) - [Commits](https://github.com/boto/boto3/compare/1.16.31...1.16.32) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> commit c3a2cb44cd52b885045a7bd90466809f8bc9b35e Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed Dec 9 09:06:29 2020 +0100 build(deps): bump celery from 5.0.3 to 5.0.4 (#380) Bumps [celery](https://github.com/celery/celery) from 5.0.3 to 5.0.4. - [Release notes](https://github.com/celery/celery/releases) - [Changelog](https://github.com/celery/celery/blob/master/Changelog.rst) - [Commits](https://github.com/celery/celery/compare/v5.0.3...v5.0.4) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> commit 682401bbf23de689cdcf01e0ecf3431fe485e5dc Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed Dec 9 07:20:45 2020 +0100 build(deps): bump uvicorn from 0.12.3 to 0.13.0 (#381) Bumps [uvicorn](https://github.com/encode/uvicorn) from 0.12.3 to 0.13.0. - [Release notes](https://github.com/encode/uvicorn/releases) - [Changelog](https://github.com/encode/uvicorn/blob/master/CHANGELOG.md) - [Commits](https://github.com/encode/uvicorn/compare/0.12.3...0.13.0) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> commit 3e6e16734859e1c7cb897d64d4f8de71b6007227 Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue Dec 8 10:32:00 2020 +0100 build(deps-dev): bump @typescript-eslint/parser in /web (#377) Bumps [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) from 4.9.0 to 4.9.1. - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/parser/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v4.9.1/packages/parser) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> commit d08c1b7b02e0946560eebc5556069e709e86cada Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue Dec 8 10:31:47 2020 +0100 build(deps): bump @sentry/browser from 5.28.0 to 5.29.0 in /web (#378) Bumps [@sentry/browser](https://github.com/getsentry/sentry-javascript) from 5.28.0 to 5.29.0. - [Release notes](https://github.com/getsentry/sentry-javascript/releases) - [Changelog](https://github.com/getsentry/sentry-javascript/blob/master/CHANGELOG.md) - [Commits](https://github.com/getsentry/sentry-javascript/compare/5.28.0...5.29.0) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> commit 94d70d252c0f1e1990c6fd83359edae30ae533bd Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue Dec 8 09:02:37 2020 +0100 build(deps): bump boto3 from 1.16.30 to 1.16.31 (#375) Bumps [boto3](https://github.com/boto/boto3) from 1.16.30 to 1.16.31. - [Release notes](https://github.com/boto/boto3/releases) - [Changelog](https://github.com/boto/boto3/blob/develop/CHANGELOG.rst) - [Commits](https://github.com/boto/boto3/compare/1.16.30...1.16.31) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> commit ccfe746dd59bc08764dc7db016bfa6dadcb54fc7 Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue Dec 8 09:02:28 2020 +0100 build(deps-dev): bump @typescript-eslint/eslint-plugin in /web (#376) Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 4.9.0 to 4.9.1. - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v4.9.1/packages/eslint-plugin) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> commit ef5dffa96a36fe3dd71447680ddce796d16028ef Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue Dec 8 09:02:16 2020 +0100 build(deps): bump @sentry/tracing from 5.28.0 to 5.29.0 in /web (#379) Bumps [@sentry/tracing](https://github.com/getsentry/sentry-javascript) from 5.28.0 to 5.29.0. - [Release notes](https://github.com/getsentry/sentry-javascript/releases) - [Changelog](https://github.com/getsentry/sentry-javascript/blob/master/CHANGELOG.md) - [Commits](https://github.com/getsentry/sentry-javascript/compare/5.28.0...5.29.0) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> commit 2caa1e765092e9a00618cd9e9bc426c4eaefda33 Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon Dec 7 11:21:07 2020 +0100 build(deps-dev): bump bandit from 1.6.2 to 1.6.3 (#371) * build(deps-dev): bump bandit from 1.6.2 to 1.6.3 Bumps [bandit](https://github.com/PyCQA/bandit) from 1.6.2 to 1.6.3. - [Release notes](https://github.com/PyCQA/bandit/releases) - [Commits](https://github.com/PyCQA/bandit/compare/1.6.2...1.6.3) Signed-off-by: dependabot[bot] <support@github.com> * root: update for new bandit version Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Jens Langhammer <jens.langhammer@beryju.org> commit 2246f3a53445e92f9fc2b5946f4ea4d0ba5f7934 Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon Dec 7 10:26:01 2020 +0100 build(deps): bump @types/codemirror from 0.0.100 to 0.0.102 in /web (#374) Bumps [@types/codemirror](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/codemirror) from 0.0.100 to 0.0.102. - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/codemirror) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> commit 95ba00cb79fbff8e68e2b76d50a3c923361bec97 Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon Dec 7 09:09:49 2020 +0100 build(deps): bump rollup from 2.34.1 to 2.34.2 in /web (#373) Bumps [rollup](https://github.com/rollup/rollup) from 2.34.1 to 2.34.2. - [Release notes](https://github.com/rollup/rollup/releases) - [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md) - [Commits](https://github.com/rollup/rollup/compare/v2.34.1...v2.34.2) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> commit 2ab4d6620f21eaab3f43739b61a83d595088d60d Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon Dec 7 09:09:24 2020 +0100 build(deps-dev): bump eslint from 7.14.0 to 7.15.0 in /web (#372) Bumps [eslint](https://github.com/eslint/eslint) from 7.14.0 to 7.15.0. - [Release notes](https://github.com/eslint/eslint/releases) - [Changelog](https://github.com/eslint/eslint/blob/master/CHANGELOG.md) - [Commits](https://github.com/eslint/eslint/compare/v7.14.0...v7.15.0) Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * web: fix linting error * web: simplify sidebar logic * web: add support for multiple active matchers per sidebar item * web: move router to elements * flows: add stage_obj to flows api * sources/*: make all sources implement SerializerModel * web: improve listing of stages * web: implement expandable table * web/table: use TemplateResult as return value for row() * web: add empty state, fix link for BoundStageList * admin: make stage binding form accept ?target like policy binding * web: fix styles in dark mode for expanding tables * flows: add policybindingmodel_ptr_id to FlowStageBinding API * web: improve wording for policies * web: fix dark theme for tertiary buttons and static modals * web: implement SourceViewPage * web: add empty state for BoundPoliciesList * web: cleanup URLs for FlowStageBindings * root: remove url attribute from ak-messages Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-12-12 18:39:09 +00:00
from authentik.lib.models import CreatedUpdatedModel, SerializerModel
from authentik.lib.utils.http import get_client_ip
from authentik.managed.models import ManagedModel
2020-12-05 21:08:42 +00:00
from authentik.policies.models import PolicyBindingModel
2018-11-11 12:41:48 +00:00
LOGGER = get_logger()
2020-12-05 21:08:42 +00:00
USER_ATTRIBUTE_DEBUG = "goauthentik.io/user/debug"
USER_ATTRIBUTE_SA = "goauthentik.io/user/service-account"
USER_ATTRIBUTE_SOURCES = "goauthentik.io/user/sources"
2018-11-11 12:41:48 +00:00
GRAVATAR_URL = "https://secure.gravatar.com"
DEFAULT_AVATAR = static("dist/assets/images/user_default.png")
options.DEFAULT_NAMES = options.DEFAULT_NAMES + ("authentik_used_by_shadows",)
2020-05-16 14:11:53 +00:00
def default_token_duration():
"""Default duration a Token is valid"""
return now() + timedelta(minutes=30)
2019-12-31 11:51:16 +00:00
def default_token_key():
"""Default token key"""
return uuid4().hex
class Group(models.Model):
"""Custom Group model which supports a basic hierarchy"""
group_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
2019-12-31 11:51:16 +00:00
name = models.CharField(_("name"), max_length=80)
is_superuser = models.BooleanField(
default=False, help_text=_("Users added to this group will be superusers.")
)
2019-12-31 11:51:16 +00:00
parent = models.ForeignKey(
"Group",
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name="children",
)
2020-08-15 19:04:22 +00:00
attributes = models.JSONField(default=dict, blank=True)
def __str__(self):
2019-10-07 14:33:48 +00:00
return f"Group {self.name}"
class Meta:
2020-09-30 17:34:22 +00:00
unique_together = (
(
"name",
"parent",
),
)
2019-12-31 11:51:16 +00:00
class UserManager(DjangoUserManager):
"""Custom user manager that doesn't assign is_superuser and is_staff"""
def create_user(self, username, email=None, password=None, **extra_fields):
"""Custom user manager that doesn't assign is_superuser and is_staff"""
return self._create_user(username, email, password, **extra_fields)
class User(GuardianUserMixin, AbstractUser):
"""Custom User model to allow easier adding of user-based settings"""
2018-11-11 12:41:48 +00:00
uuid = models.UUIDField(default=uuid4, editable=False)
name = models.TextField(help_text=_("User's display name."))
sources = models.ManyToManyField("Source", through="UserSourceConnection")
2020-12-05 21:08:42 +00:00
ak_groups = models.ManyToManyField("Group", related_name="users")
password_change_date = models.DateTimeField(auto_now_add=True)
2020-08-15 19:04:22 +00:00
attributes = models.JSONField(default=dict, blank=True)
objects = UserManager()
def group_attributes(self) -> dict[str, Any]:
"""Get a dictionary containing the attributes from all groups the user belongs to,
including the users attributes"""
2020-09-24 13:45:58 +00:00
final_attributes = {}
2020-12-05 21:08:42 +00:00
for group in self.ak_groups.all().order_by("name"):
always_merger.merge(final_attributes, group.attributes)
always_merger.merge(final_attributes, self.attributes)
2020-09-24 13:45:58 +00:00
return final_attributes
2020-09-25 21:59:06 +00:00
@cached_property
def is_superuser(self) -> bool:
"""Get supseruser status based on membership in a group with superuser status"""
2020-12-05 21:08:42 +00:00
return self.ak_groups.filter(is_superuser=True).exists()
@property
def is_staff(self) -> bool:
"""superuser == staff user"""
2020-09-25 21:59:06 +00:00
return self.is_superuser # type: ignore
def set_password(self, password, signal=True):
if self.pk and signal:
password_changed.send(sender=self, user=self, password=password)
self.password_change_date = now()
return super().set_password(password)
2018-11-16 10:41:14 +00:00
@property
def uid(self) -> str:
"""Generate a globall unique UID, based on the user ID and the hashed secret key"""
return sha256(f"{self.id}-{settings.SECRET_KEY}".encode("ascii")).hexdigest()
@property
def avatar(self) -> str:
"""Get avatar, depending on authentik.avatar setting"""
mode: str = CONFIG.y("avatars", "none")
if mode == "none":
return DEFAULT_AVATAR
# gravatar uses md5 for their URLs, so md5 can't be avoided
mail_hash = md5(self.email.encode("utf-8")).hexdigest() # nosec
if mode == "gravatar":
parameters = [
("s", "158"),
("r", "g"),
]
gravatar_url = (
f"{GRAVATAR_URL}/avatar/{mail_hash}?{urlencode(parameters, doseq=True)}"
)
return escape(gravatar_url)
return mode % {
"username": self.username,
"mail_hash": mail_hash,
"upn": self.attributes.get("upn", ""),
}
class Meta:
permissions = (
("reset_user_password", "Reset Password"),
("impersonate", "Can impersonate other users"),
)
verbose_name = _("User")
verbose_name_plural = _("Users")
2019-12-31 11:51:16 +00:00
2020-12-16 20:38:40 +00:00
class Provider(SerializerModel):
"""Application-independent Provider instance. For example SAML2 Remote, OAuth2 Application"""
2020-10-03 18:01:10 +00:00
name = models.TextField()
WIP Use Flows for Sources and Providers (#32) * core: start migrating to flows for authorisation * sources/oauth: start type-hinting * core: create default user * core: only show user delete button if an unenrollment flow exists * flows: Correctly check initial policies on flow with context * policies: add more verbosity to engine * sources/oauth: migrate to flows * sources/oauth: fix typing errors * flows: add more tests * sources/oauth: start implementing unittests * sources/ldap: add option to disable user sync, move connection init to model * sources/ldap: re-add default PropertyMappings * providers/saml: re-add default PropertyMappings * admin: fix missing stage count * stages/identification: fix sources not being shown * crypto: fix being unable to save with private key * crypto: re-add default self-signed keypair * policies: rewrite cache_key to prevent wrong cache * sources/saml: migrate to flows for auth and enrollment * stages/consent: add new stage * admin: fix PropertyMapping widget not rendering properly * core: provider.authorization_flow is mandatory * flows: add support for "autosubmit" attribute on form * flows: add InMemoryStage for dynamic stages * flows: optionally allow empty flows from FlowPlanner * providers/saml: update to authorization_flow * sources/*: fix flow executor URL * flows: fix pylint error * flows: wrap responses in JSON object to easily handle redirects * flow: dont cache plan's context * providers/oauth: rewrite OAuth2 Provider to use flows * providers/*: update docstrings of models * core: fix forms not passing help_text through safe * flows: fix HttpResponses not being converted to JSON * providers/oidc: rewrite to use flows * flows: fix linting
2020-06-07 14:35:08 +00:00
authorization_flow = models.ForeignKey(
Flow,
on_delete=models.CASCADE,
help_text=_("Flow used when authorizing this provider."),
related_name="provider_authorization",
)
property_mappings = models.ManyToManyField(
"PropertyMapping", default=None, blank=True
)
objects = InheritanceManager()
@property
def launch_url(self) -> Optional[str]:
"""URL to this provider and initiate authorization for the user.
Can return None for providers that are not URL-based"""
return None
@property
def component(self) -> str:
"""Return component used to edit this object"""
raise NotImplementedError
2020-12-16 20:38:40 +00:00
@property
def serializer(self) -> Type[Serializer]:
"""Get serializer for this model"""
raise NotImplementedError
def __str__(self):
2020-10-03 18:01:10 +00:00
return self.name
class Application(PolicyBindingModel):
2020-12-05 21:08:42 +00:00
"""Every Application which uses authentik for authentication/identification/authorization
2018-11-11 12:41:48 +00:00
needs an Application record. Other authentication types can subclass this Model to
add custom fields and other properties"""
name = models.TextField(help_text=_("Application's display Name."))
slug = models.SlugField(
help_text=_("Internal application name, used in URLs."), unique=True
)
provider = models.OneToOneField(
"Provider", null=True, blank=True, default=None, on_delete=models.SET_DEFAULT
2019-12-31 11:51:16 +00:00
)
meta_launch_url = models.TextField(
default="", blank=True, validators=[validators.URLValidator()]
)
2020-12-05 21:08:42 +00:00
# For template applications, this can be set to /static/authentik/applications/*
meta_icon = models.FileField(
upload_to="application-icons/", default=None, null=True
)
meta_description = models.TextField(default="", blank=True)
meta_publisher = models.TextField(default="", blank=True)
2018-11-11 12:41:48 +00:00
@property
def get_meta_icon(self) -> Optional[str]:
"""Get the URL to the App Icon image. If the name is /static or starts with http
it is returned as-is"""
if not self.meta_icon:
return None
if self.meta_icon.name.startswith("http") or self.meta_icon.name.startswith(
"/static"
):
return self.meta_icon.name
return self.meta_icon.url
def get_launch_url(self) -> Optional[str]:
"""Get launch URL if set, otherwise attempt to get launch URL based on provider."""
if self.meta_launch_url:
return self.meta_launch_url
if self.provider:
return self.get_provider().launch_url
return None
def get_provider(self) -> Optional[Provider]:
"""Get casted provider instance"""
if not self.provider:
return None
return Provider.objects.get_subclass(pk=self.provider.pk)
2018-11-11 12:41:48 +00:00
def __str__(self):
return self.name
class Meta:
verbose_name = _("Application")
verbose_name_plural = _("Applications")
2019-10-07 14:33:48 +00:00
class SourceUserMatchingModes(models.TextChoices):
"""Different modes a source can handle new/returning users"""
IDENTIFIER = "identifier", _("Use the source-specific identifier")
EMAIL_LINK = "email_link", _(
(
"Link to a user with identical email address. Can have security implications "
"when a source doesn't validate email addresses."
)
)
EMAIL_DENY = "email_deny", _(
"Use the user's email address, but deny enrollment when the email address already exists."
)
USERNAME_LINK = "username_link", _(
(
"Link to a user with identical username address. Can have security implications "
"when a username is used with another source."
)
)
USERNAME_DENY = "username_deny", _(
"Use the user's username, but deny enrollment when the username already exists."
)
class Source(ManagedModel, SerializerModel, PolicyBindingModel):
2018-11-11 12:41:48 +00:00
"""Base Authentication source, i.e. an OAuth Provider, SAML Remote or LDAP Server"""
name = models.TextField(help_text=_("Source's display Name."))
2020-07-09 20:57:27 +00:00
slug = models.SlugField(
help_text=_("Internal source name, used in URLs."), unique=True
)
2018-11-11 12:41:48 +00:00
enabled = models.BooleanField(default=True)
2019-12-31 11:51:16 +00:00
property_mappings = models.ManyToManyField(
"PropertyMapping", default=None, blank=True
)
2018-11-11 12:41:48 +00:00
WIP Use Flows for Sources and Providers (#32) * core: start migrating to flows for authorisation * sources/oauth: start type-hinting * core: create default user * core: only show user delete button if an unenrollment flow exists * flows: Correctly check initial policies on flow with context * policies: add more verbosity to engine * sources/oauth: migrate to flows * sources/oauth: fix typing errors * flows: add more tests * sources/oauth: start implementing unittests * sources/ldap: add option to disable user sync, move connection init to model * sources/ldap: re-add default PropertyMappings * providers/saml: re-add default PropertyMappings * admin: fix missing stage count * stages/identification: fix sources not being shown * crypto: fix being unable to save with private key * crypto: re-add default self-signed keypair * policies: rewrite cache_key to prevent wrong cache * sources/saml: migrate to flows for auth and enrollment * stages/consent: add new stage * admin: fix PropertyMapping widget not rendering properly * core: provider.authorization_flow is mandatory * flows: add support for "autosubmit" attribute on form * flows: add InMemoryStage for dynamic stages * flows: optionally allow empty flows from FlowPlanner * providers/saml: update to authorization_flow * sources/*: fix flow executor URL * flows: fix pylint error * flows: wrap responses in JSON object to easily handle redirects * flow: dont cache plan's context * providers/oauth: rewrite OAuth2 Provider to use flows * providers/*: update docstrings of models * core: fix forms not passing help_text through safe * flows: fix HttpResponses not being converted to JSON * providers/oidc: rewrite to use flows * flows: fix linting
2020-06-07 14:35:08 +00:00
authentication_flow = models.ForeignKey(
Flow,
blank=True,
null=True,
default=None,
on_delete=models.SET_NULL,
help_text=_("Flow to use when authenticating existing users."),
related_name="source_authentication",
)
enrollment_flow = models.ForeignKey(
Flow,
blank=True,
null=True,
default=None,
on_delete=models.SET_NULL,
help_text=_("Flow to use when enrolling new users."),
related_name="source_enrollment",
)
user_matching_mode = models.TextField(
choices=SourceUserMatchingModes.choices,
default=SourceUserMatchingModes.IDENTIFIER,
help_text=_(
(
"How the source determines if an existing user should be authenticated or "
"a new user enrolled."
)
),
)
2018-11-16 08:10:35 +00:00
objects = InheritanceManager()
@property
def component(self) -> str:
"""Return component used to edit this object"""
raise NotImplementedError
@property
def ui_login_button(self) -> Optional[UILoginButton]:
"""If source uses a http-based flow, return UI Information about the login
button. If source doesn't use http-based flow, return None."""
return None
@property
def ui_user_settings(self) -> Optional[UserSettingSerializer]:
"""Entrypoint to integrate with User settings. Can either return None if no
user settings are available, or UserSettingSerializer."""
return None
2019-03-13 15:49:30 +00:00
2018-11-11 12:41:48 +00:00
def __str__(self):
return self.name
2019-10-07 14:33:48 +00:00
class UserSourceConnection(CreatedUpdatedModel):
"""Connection between User and Source."""
2018-11-11 12:41:48 +00:00
user = models.ForeignKey(User, on_delete=models.CASCADE)
source = models.ForeignKey(Source, on_delete=models.CASCADE)
2018-11-11 12:41:48 +00:00
objects = InheritanceManager()
class Meta:
2018-11-11 12:41:48 +00:00
unique_together = (("user", "source"),)
class ExpiringModel(models.Model):
"""Base Model which can expire, and is automatically cleaned up."""
expires = models.DateTimeField(default=default_token_duration)
expiring = models.BooleanField(default=True)
@classmethod
def filter_not_expired(cls, **kwargs) -> QuerySet:
"""Filer for tokens which are not expired yet or are not expiring,
and match filters in `kwargs`"""
expired = Q(expires__lt=now(), expiring=True)
return cls.objects.exclude(expired).filter(**kwargs)
@property
def is_expired(self) -> bool:
"""Check if token is expired yet."""
if not self.expiring:
return False
return now() > self.expires
class Meta:
abstract = True
2020-07-05 21:14:57 +00:00
class TokenIntents(models.TextChoices):
"""Intents a Token can be created for."""
# Single use token
2020-07-05 21:14:57 +00:00
INTENT_VERIFICATION = "verification"
# Allow access to API
INTENT_API = "api"
# Recovery use for the recovery app
INTENT_RECOVERY = "recovery"
2020-07-05 21:14:57 +00:00
class Token(ManagedModel, ExpiringModel):
2020-07-05 21:14:57 +00:00
"""Token used to authenticate the User for API Access or confirm another Stage like Email."""
token_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
identifier = models.SlugField(max_length=255, unique=True)
key = models.TextField(default=default_token_key)
2020-07-05 21:14:57 +00:00
intent = models.TextField(
choices=TokenIntents.choices, default=TokenIntents.INTENT_VERIFICATION
)
2020-05-16 14:11:53 +00:00
user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="+")
description = models.TextField(default="", blank=True)
def __str__(self):
description = f"{self.identifier}"
if self.expiring:
description += f" (expires={self.expires})"
return description
class Meta:
2020-05-16 14:11:53 +00:00
verbose_name = _("Token")
verbose_name_plural = _("Tokens")
indexes = [
models.Index(fields=["identifier"]),
models.Index(fields=["key"]),
]
permissions = (("view_token_key", "View token's key"),)
class PropertyMapping(SerializerModel, ManagedModel):
"""User-defined key -> x mapping which can be used by providers to expose extra data."""
pm_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
name = models.TextField()
expression = models.TextField()
objects = InheritanceManager()
@property
def component(self) -> str:
"""Return component used to edit this object"""
raise NotImplementedError
@property
def serializer(self) -> Type[Serializer]:
"""Get serializer for this model"""
raise NotImplementedError
def evaluate(
self, user: Optional[User], request: Optional[HttpRequest], **kwargs
) -> Any:
"""Evaluate `self.expression` using `**kwargs` as Context."""
2020-12-05 21:08:42 +00:00
from authentik.core.expression import PropertyMappingEvaluator
evaluator = PropertyMappingEvaluator()
evaluator.set_context(user, request, self, **kwargs)
try:
return evaluator.evaluate(self.expression)
except (ValueError, SyntaxError) as exc:
raise PropertyMappingExpressionException from exc
def __str__(self):
2019-10-07 14:33:48 +00:00
return f"Property Mapping {self.name}"
class Meta:
2019-12-31 11:51:16 +00:00
verbose_name = _("Property Mapping")
verbose_name_plural = _("Property Mappings")
class AuthenticatedSession(ExpiringModel):
"""Additional session class for authenticated users. Augments the standard django session
to achieve the following:
- Make it queryable by user
- Have a direct connection to user objects
- Allow users to view their own sessions and terminate them
- Save structured and well-defined information.
"""
uuid = models.UUIDField(default=uuid4, primary_key=True)
session_key = models.CharField(max_length=40)
user = models.ForeignKey(User, on_delete=models.CASCADE)
last_ip = models.TextField()
last_user_agent = models.TextField(blank=True)
last_used = models.DateTimeField(auto_now=True)
@staticmethod
def from_request(
request: HttpRequest, user: User
) -> Optional["AuthenticatedSession"]:
"""Create a new session from a http request"""
if not hasattr(request, "session") or not request.session.session_key:
return None
return AuthenticatedSession(
session_key=request.session.session_key,
user=user,
last_ip=get_client_ip(request),
last_user_agent=request.META.get("HTTP_USER_AGENT", ""),
expires=request.session.get_expiry_date(),
)