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/passbook/core/models.py

297 lines
9.1 KiB
Python
Raw Normal View History

2018-11-11 12:41:48 +00:00
"""passbook core models"""
from datetime import timedelta
2018-12-09 20:20:34 +00:00
from random import SystemRandom
from time import sleep
from typing import Optional
from uuid import uuid4
2018-11-11 12:41:48 +00:00
from django.contrib.auth.models import AbstractUser
2019-10-07 14:33:48 +00:00
from django.contrib.postgres.fields import JSONField
2018-11-11 12:41:48 +00:00
from django.db import models
2018-12-10 13:49:15 +00:00
from django.urls import reverse_lazy
from django.utils.timezone import now
2018-11-26 21:08:48 +00:00
from django.utils.translation import gettext as _
2018-11-16 08:10:35 +00:00
from model_utils.managers import InheritanceManager
2019-10-01 08:24:10 +00:00
from structlog import get_logger
2018-11-11 12:41:48 +00:00
from passbook.core.signals import password_changed
2018-11-16 08:10:35 +00:00
from passbook.lib.models import CreatedUpdatedModel, UUIDModel
2019-10-07 14:33:48 +00:00
from passbook.policies.exceptions import PolicyException
from passbook.policies.struct import PolicyRequest, PolicyResult
2018-11-11 12:41:48 +00:00
LOGGER = get_logger()
2018-11-11 12:41:48 +00:00
def default_nonce_duration():
"""Default duration a Nonce is valid"""
return now() + timedelta(hours=4)
class Group(UUIDModel):
"""Custom Group model which supports a basic hierarchy"""
name = models.CharField(_('name'), max_length=80)
parent = models.ForeignKey('Group', blank=True, null=True,
on_delete=models.SET_NULL, related_name='children')
attributes = JSONField(default=dict, blank=True)
def __str__(self):
2019-10-07 14:33:48 +00:00
return f"Group {self.name}"
class Meta:
unique_together = (('name', 'parent',),)
2018-11-11 12:41:48 +00:00
class User(AbstractUser):
"""Custom User model to allow easier adding o f user-based settings"""
uuid = models.UUIDField(default=uuid4, editable=False)
name = models.TextField()
2018-11-11 12:41:48 +00:00
sources = models.ManyToManyField('Source', through='UserSourceConnection')
groups = models.ManyToManyField('Group')
password_change_date = models.DateTimeField(auto_now_add=True)
attributes = JSONField(default=dict, blank=True)
def set_password(self, password):
if self.pk:
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
2018-11-16 10:41:14 +00:00
class Provider(models.Model):
"""Application-independent Provider instance. For example SAML2 Remote, OAuth2 Application"""
2018-11-16 10:41:14 +00:00
property_mappings = models.ManyToManyField('PropertyMapping', default=None, blank=True)
2018-11-25 19:38:49 +00:00
objects = InheritanceManager()
2018-11-16 10:41:14 +00:00
# This class defines no field for easier inheritance
def __str__(self):
if hasattr(self, 'name'):
return getattr(self, 'name')
return super().__str__()
2018-11-11 12:41:48 +00:00
2019-02-16 09:24:31 +00:00
class PolicyModel(UUIDModel, CreatedUpdatedModel):
"""Base model which can have policies applied to it"""
2019-02-16 09:24:31 +00:00
policies = models.ManyToManyField('Policy', blank=True)
class UserSettings:
"""Dataclass for Factor and Source's user_settings"""
name: str
icon: str
view_name: str
def __init__(self, name: str, icon: str, view_name: str):
self.name = name
self.icon = icon
self.view_name = view_name
2019-02-16 09:24:31 +00:00
class Factor(PolicyModel):
2019-02-16 08:52:37 +00:00
"""Authentication factor, multiple instances of the same Factor can be used"""
name = models.TextField()
slug = models.SlugField(unique=True)
order = models.IntegerField()
enabled = models.BooleanField(default=True)
objects = InheritanceManager()
type = ''
form = ''
2019-02-16 08:52:37 +00:00
def user_settings(self) -> Optional[UserSettings]:
"""Entrypoint to integrate with User settings. Can either return None if no
user settings are available, or an instanace of UserSettings."""
return None
2019-02-16 08:52:37 +00:00
def __str__(self):
2019-10-07 14:33:48 +00:00
return f"Factor {self.slug}"
2019-02-16 08:52:37 +00:00
2019-02-16 09:24:31 +00:00
class Application(PolicyModel):
2018-11-11 12:41:48 +00:00
"""Every Application which uses passbook for authentication/identification/authorization
needs an Application record. Other authentication types can subclass this Model to
add custom fields and other properties"""
name = models.TextField()
2018-12-26 16:17:39 +00:00
slug = models.SlugField()
2018-11-11 12:41:48 +00:00
launch_url = models.URLField(null=True, blank=True)
icon_url = models.TextField(null=True, blank=True)
2019-02-16 08:52:37 +00:00
provider = models.OneToOneField('Provider', null=True, blank=True,
default=None, on_delete=models.SET_DEFAULT)
skip_authorization = models.BooleanField(default=False)
2018-11-11 12:41:48 +00:00
2018-11-16 08:10:35 +00:00
objects = InheritanceManager()
def get_provider(self):
"""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
2019-10-07 14:33:48 +00:00
2019-02-16 09:24:31 +00:00
class Source(PolicyModel):
2018-11-11 12:41:48 +00:00
"""Base Authentication source, i.e. an OAuth Provider, SAML Remote or LDAP Server"""
name = models.TextField()
slug = models.SlugField()
enabled = models.BooleanField(default=True)
property_mappings = models.ManyToManyField('PropertyMapping', default=None, blank=True)
2018-11-11 12:41:48 +00:00
form = '' # ModelForm-based class ued to create/edit instance
2018-11-16 08:10:35 +00:00
objects = InheritanceManager()
@property
def login_button(self):
"""Return a tuple of URL, Icon name and Name
if Source should get a link on the login page"""
return None
@property
def additional_info(self):
"""Return additional Info, such as a callback URL. Show in the administration interface."""
return None
def user_settings(self) -> Optional[UserSettings]:
"""Entrypoint to integrate with User settings. Can either return None if no
user settings are available, or an instanace of UserSettings."""
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
2018-11-11 12:41:48 +00:00
class UserSourceConnection(CreatedUpdatedModel):
"""Connection between User and Source."""
user = models.ForeignKey(User, on_delete=models.CASCADE)
source = models.ForeignKey(Source, on_delete=models.CASCADE)
class Meta:
unique_together = (('user', 'source'),)
2019-10-07 14:33:48 +00:00
2019-02-16 09:24:31 +00:00
class Policy(UUIDModel, CreatedUpdatedModel):
2019-02-16 10:13:00 +00:00
"""Policies which specify if a user is authorized to use an Application. Can be overridden by
2018-11-11 12:41:48 +00:00
other types to add other fields, more logic, etc."""
ACTION_ALLOW = 'allow'
ACTION_DENY = 'deny'
ACTIONS = (
(ACTION_ALLOW, ACTION_ALLOW),
(ACTION_DENY, ACTION_DENY),
)
name = models.TextField(blank=True, null=True)
action = models.CharField(max_length=20, choices=ACTIONS)
negate = models.BooleanField(default=False)
2018-11-25 19:38:49 +00:00
order = models.IntegerField(default=0)
timeout = models.IntegerField(default=30)
2018-11-11 12:41:48 +00:00
2018-11-16 08:10:35 +00:00
objects = InheritanceManager()
2018-11-11 12:41:48 +00:00
def __str__(self):
if self.name:
return self.name
2019-10-07 14:33:48 +00:00
return f"{self.name} action {self.action}"
2018-11-11 12:41:48 +00:00
def passes(self, request: PolicyRequest) -> PolicyResult:
2019-02-16 09:24:31 +00:00
"""Check if user instance passes this policy"""
2019-10-02 20:28:39 +00:00
raise PolicyException()
2018-11-11 12:41:48 +00:00
2019-02-16 09:24:31 +00:00
class DebugPolicy(Policy):
"""Policy used for debugging the PolicyEngine. Returns a fixed result,
but takes a random time to process."""
result = models.BooleanField(default=False)
wait_min = models.IntegerField(default=5)
wait_max = models.IntegerField(default=30)
2019-02-16 09:24:31 +00:00
form = 'passbook.core.forms.policies.DebugPolicyForm'
def passes(self, request: PolicyRequest) -> PolicyResult:
"""Wait random time then return result"""
2018-12-09 20:20:34 +00:00
wait = SystemRandom().randrange(self.wait_min, self.wait_max)
LOGGER.debug("Policy waiting", policy=self, delay=wait)
sleep(wait)
return PolicyResult(self.result, 'Debugging')
class Meta:
2019-02-16 09:24:31 +00:00
verbose_name = _('Debug Policy')
2019-02-16 10:13:00 +00:00
verbose_name_plural = _('Debug Policies')
2018-12-10 12:48:22 +00:00
2018-12-10 13:49:15 +00:00
class Invitation(UUIDModel):
2018-12-10 13:21:42 +00:00
"""Single-use invitation link"""
2018-12-10 12:48:22 +00:00
created_by = models.ForeignKey('User', on_delete=models.CASCADE)
expires = models.DateTimeField(default=None, blank=True, null=True)
fixed_username = models.TextField(blank=True, default=None)
fixed_email = models.TextField(blank=True, default=None)
needs_confirmation = models.BooleanField(default=True)
2018-12-10 12:48:22 +00:00
2018-12-10 13:49:15 +00:00
@property
def link(self):
"""Get link to use invitation"""
2019-10-07 14:33:48 +00:00
return reverse_lazy('passbook_core:auth-sign-up') + f'?invitation={self.uuid.hex}'
2018-12-10 13:49:15 +00:00
2018-12-10 12:48:22 +00:00
def __str__(self):
2019-10-07 14:33:48 +00:00
return f"Invitation {self.uuid.hex} created by {self.created_by}"
2018-12-10 12:48:22 +00:00
class Meta:
2018-12-10 13:49:15 +00:00
verbose_name = _('Invitation')
2018-12-10 13:21:42 +00:00
verbose_name_plural = _('Invitations')
class Nonce(UUIDModel):
"""One-time link for password resets/sign-up-confirmations"""
expires = models.DateTimeField(default=default_nonce_duration)
user = models.ForeignKey('User', on_delete=models.CASCADE)
expiring = models.BooleanField(default=True)
description = models.TextField(default='', blank=True)
@property
def is_expired(self) -> bool:
"""Check if nonce is expired yet."""
return now() > self.expires
def __str__(self):
return f"Nonce f{self.uuid.hex} {self.description} (expires={self.expires})"
class Meta:
verbose_name = _('Nonce')
verbose_name_plural = _('Nonces')
class PropertyMapping(UUIDModel):
"""User-defined key -> x mapping which can be used by providers to expose extra data."""
name = models.TextField()
form = ''
objects = InheritanceManager()
def __str__(self):
2019-10-07 14:33:48 +00:00
return f"Property Mapping {self.name}"
class Meta:
verbose_name = _('Property Mapping')
verbose_name_plural = _('Property Mappings')