2018-11-11 12:41:48 +00:00
|
|
|
"""passbook core models"""
|
2019-02-25 19:46:23 +00:00
|
|
|
from datetime import timedelta
|
2018-12-09 20:20:34 +00:00
|
|
|
from random import SystemRandom
|
2018-12-09 20:06:21 +00:00
|
|
|
from time import sleep
|
2020-02-18 09:13:53 +00:00
|
|
|
from typing import Any, Optional
|
2018-12-09 20:05:25 +00:00
|
|
|
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
|
2020-02-18 14:12:22 +00:00
|
|
|
from django.core.exceptions import ValidationError
|
2018-11-11 12:41:48 +00:00
|
|
|
from django.db import models
|
2020-02-17 16:47:51 +00:00
|
|
|
from django.http import HttpRequest
|
2020-02-18 09:13:53 +00:00
|
|
|
from django.urls import reverse_lazy
|
2019-02-25 14:41:36 +00:00
|
|
|
from django.utils.timezone import now
|
2020-02-17 16:47:51 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2020-02-14 14:17:40 +00:00
|
|
|
from django_prometheus.models import ExportModelOperationsMixin
|
2019-10-10 08:45:51 +00:00
|
|
|
from guardian.mixins import GuardianUserMixin
|
2020-02-19 15:18:31 +00:00
|
|
|
from jinja2 import Undefined
|
2020-02-18 09:13:53 +00:00
|
|
|
from jinja2.exceptions import TemplateSyntaxError, UndefinedError
|
|
|
|
from jinja2.nativetypes import NativeEnvironment
|
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
|
|
|
|
2020-02-18 09:12:42 +00:00
|
|
|
from passbook.core.exceptions import PropertyMappingExpressionException
|
2019-02-25 14:41:36 +00:00
|
|
|
from passbook.core.signals import password_changed
|
2020-02-20 16:23:05 +00:00
|
|
|
from passbook.core.types import UILoginButton, UIUserSettings
|
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
|
2020-02-20 12:52:05 +00:00
|
|
|
from passbook.policies.types import PolicyRequest, PolicyResult
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2019-10-04 08:08:53 +00:00
|
|
|
LOGGER = get_logger()
|
2020-02-17 16:47:51 +00:00
|
|
|
NATIVE_ENVIRONMENT = NativeEnvironment()
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2019-02-25 19:46:23 +00:00
|
|
|
|
|
|
|
def default_nonce_duration():
|
|
|
|
"""Default duration a Nonce is valid"""
|
|
|
|
return now() + timedelta(hours=4)
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
|
2020-01-19 20:01:26 +00:00
|
|
|
class Group(ExportModelOperationsMixin("group"), UUIDModel):
|
2018-12-26 23:38:42 +00:00
|
|
|
"""Custom Group model which supports a basic hierarchy"""
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
name = models.CharField(_("name"), max_length=80)
|
|
|
|
parent = models.ForeignKey(
|
|
|
|
"Group",
|
|
|
|
blank=True,
|
|
|
|
null=True,
|
|
|
|
on_delete=models.SET_NULL,
|
|
|
|
related_name="children",
|
|
|
|
)
|
2019-10-11 10:47:06 +00:00
|
|
|
attributes = JSONField(default=dict, blank=True)
|
2018-12-26 23:38:42 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
2019-10-07 14:33:48 +00:00
|
|
|
return f"Group {self.name}"
|
2018-12-26 23:38:42 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
unique_together = (("name", "parent",),)
|
|
|
|
|
2018-12-26 23:38:42 +00:00
|
|
|
|
2020-01-19 20:01:26 +00:00
|
|
|
class User(ExportModelOperationsMixin("user"), GuardianUserMixin, AbstractUser):
|
2018-11-11 12:41:48 +00:00
|
|
|
"""Custom User model to allow easier adding o f user-based settings"""
|
|
|
|
|
2018-12-09 20:05:25 +00:00
|
|
|
uuid = models.UUIDField(default=uuid4, editable=False)
|
2019-02-27 14:09:05 +00:00
|
|
|
name = models.TextField()
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
sources = models.ManyToManyField("Source", through="UserSourceConnection")
|
|
|
|
groups = models.ManyToManyField("Group")
|
2019-02-25 14:41:36 +00:00
|
|
|
password_change_date = models.DateTimeField(auto_now_add=True)
|
|
|
|
|
2019-10-11 10:47:06 +00:00
|
|
|
attributes = JSONField(default=dict, blank=True)
|
|
|
|
|
2019-02-25 14:41:36 +00:00
|
|
|
def set_password(self, password):
|
2019-02-26 14:40:58 +00:00
|
|
|
if self.pk:
|
|
|
|
password_changed.send(sender=self, user=self, password=password)
|
2019-02-25 14:41:36 +00:00
|
|
|
self.password_change_date = now()
|
|
|
|
return super().set_password(password)
|
2018-11-16 10:41:14 +00:00
|
|
|
|
2019-10-10 11:01:36 +00:00
|
|
|
class Meta:
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
permissions = (("reset_user_password", "Reset Password"),)
|
|
|
|
|
2019-10-10 11:01:36 +00:00
|
|
|
|
2020-01-19 20:01:26 +00:00
|
|
|
class Provider(ExportModelOperationsMixin("provider"), models.Model):
|
2018-11-22 12:12:59 +00:00
|
|
|
"""Application-independent Provider instance. For example SAML2 Remote, OAuth2 Application"""
|
2018-11-16 10:41:14 +00:00
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
property_mappings = models.ManyToManyField(
|
|
|
|
"PropertyMapping", default=None, blank=True
|
|
|
|
)
|
2019-03-08 11:47:50 +00:00
|
|
|
|
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
|
2018-11-24 21:26:28 +00:00
|
|
|
def __str__(self):
|
2019-12-31 11:51:16 +00:00
|
|
|
if hasattr(self, "name"):
|
|
|
|
return getattr(self, "name")
|
2018-11-24 21:26:28 +00:00
|
|
|
return super().__str__()
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2019-10-10 12:04:58 +00:00
|
|
|
|
2019-02-16 09:24:31 +00:00
|
|
|
class PolicyModel(UUIDModel, CreatedUpdatedModel):
|
|
|
|
"""Base model which can have policies applied to it"""
|
2018-11-22 12:12:59 +00:00
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
policies = models.ManyToManyField("Policy", blank=True)
|
2018-11-22 12:12:59 +00:00
|
|
|
|
2019-10-09 10:47:14 +00:00
|
|
|
|
2020-01-19 20:01:26 +00:00
|
|
|
class Factor(ExportModelOperationsMixin("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)
|
2019-02-24 21:39:09 +00:00
|
|
|
|
|
|
|
objects = InheritanceManager()
|
2019-12-31 11:51:16 +00:00
|
|
|
type = ""
|
|
|
|
form = ""
|
2019-02-16 08:52:37 +00:00
|
|
|
|
2020-02-20 12:51:41 +00:00
|
|
|
@property
|
|
|
|
def ui_user_settings(self) -> Optional[UIUserSettings]:
|
2019-10-09 10:47:14 +00:00
|
|
|
"""Entrypoint to integrate with User settings. Can either return None if no
|
2020-02-20 12:51:41 +00:00
|
|
|
user settings are available, or an instanace of UIUserSettings."""
|
2019-10-09 10:47:14 +00:00
|
|
|
return None
|
2019-02-25 12:20:07 +00:00
|
|
|
|
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-24 21:39:09 +00:00
|
|
|
|
2020-01-19 20:01:26 +00:00
|
|
|
class Application(ExportModelOperationsMixin("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()
|
2020-02-20 12:45:22 +00:00
|
|
|
skip_authorization = models.BooleanField(default=False)
|
2019-12-31 11:51:16 +00:00
|
|
|
provider = models.OneToOneField(
|
|
|
|
"Provider", null=True, blank=True, default=None, on_delete=models.SET_DEFAULT
|
|
|
|
)
|
2020-02-20 12:45:22 +00:00
|
|
|
|
|
|
|
meta_launch_url = models.URLField(null=True, blank=True)
|
|
|
|
meta_icon_url = models.TextField(null=True, blank=True)
|
|
|
|
meta_description = models.TextField(null=True, blank=True)
|
|
|
|
meta_publisher = models.TextField(null=True, blank=True)
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2018-11-16 08:10:35 +00:00
|
|
|
objects = InheritanceManager()
|
|
|
|
|
2020-02-20 12:45:22 +00:00
|
|
|
def get_provider(self) -> Optional[Provider]:
|
2019-02-27 13:47:11 +00:00
|
|
|
"""Get casted provider instance"""
|
2019-03-07 13:09:52 +00:00
|
|
|
if not self.provider:
|
|
|
|
return None
|
2019-02-27 13:47:11 +00:00
|
|
|
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
|
|
|
|
2020-01-19 20:01:26 +00:00
|
|
|
class Source(ExportModelOperationsMixin("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()
|
2020-02-20 12:45:22 +00:00
|
|
|
|
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
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
form = "" # ModelForm-based class ued to create/edit instance
|
2019-04-29 21:19:37 +00:00
|
|
|
|
2018-11-16 08:10:35 +00:00
|
|
|
objects = InheritanceManager()
|
|
|
|
|
2018-12-18 12:24:58 +00:00
|
|
|
@property
|
2020-02-20 12:51:41 +00:00
|
|
|
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."""
|
2019-10-13 14:47:05 +00:00
|
|
|
return None
|
2018-12-18 12:24:58 +00:00
|
|
|
|
2019-02-25 13:10:10 +00:00
|
|
|
@property
|
2020-02-20 12:51:41 +00:00
|
|
|
def ui_additional_info(self) -> Optional[str]:
|
2019-02-25 13:10:10 +00:00
|
|
|
"""Return additional Info, such as a callback URL. Show in the administration interface."""
|
|
|
|
return None
|
|
|
|
|
2020-02-20 12:51:41 +00:00
|
|
|
@property
|
|
|
|
def ui_user_settings(self) -> Optional[UIUserSettings]:
|
2019-10-09 10:47:14 +00:00
|
|
|
"""Entrypoint to integrate with User settings. Can either return None if no
|
2020-02-20 12:51:41 +00:00
|
|
|
user settings are available, or an instanace of UIUserSettings."""
|
2019-10-09 10:47:14 +00:00
|
|
|
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:
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
unique_together = (("user", "source"),)
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2019-10-07 14:33:48 +00:00
|
|
|
|
2020-01-19 20:01:26 +00:00
|
|
|
class Policy(ExportModelOperationsMixin("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."""
|
|
|
|
|
|
|
|
name = models.TextField(blank=True, null=True)
|
|
|
|
negate = models.BooleanField(default=False)
|
2018-11-25 19:38:49 +00:00
|
|
|
order = models.IntegerField(default=0)
|
2019-03-21 13:48:51 +00:00
|
|
|
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):
|
2019-10-14 13:00:20 +00:00
|
|
|
return f"Policy {self.name}"
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2019-10-03 08:45:31 +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
|
|
|
|
2018-12-09 20:06:21 +00:00
|
|
|
|
2019-02-16 09:24:31 +00:00
|
|
|
class DebugPolicy(Policy):
|
|
|
|
"""Policy used for debugging the PolicyEngine. Returns a fixed result,
|
2018-12-09 20:06:21 +00:00
|
|
|
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-12-31 11:51:16 +00:00
|
|
|
form = "passbook.core.forms.policies.DebugPolicyForm"
|
2018-12-09 20:06:21 +00:00
|
|
|
|
2019-10-03 08:45:31 +00:00
|
|
|
def passes(self, request: PolicyRequest) -> PolicyResult:
|
2018-12-09 20:06:21 +00:00
|
|
|
"""Wait random time then return result"""
|
2018-12-09 20:20:34 +00:00
|
|
|
wait = SystemRandom().randrange(self.wait_min, self.wait_max)
|
2019-10-04 08:21:33 +00:00
|
|
|
LOGGER.debug("Policy waiting", policy=self, delay=wait)
|
2018-12-09 20:06:21 +00:00
|
|
|
sleep(wait)
|
2019-12-31 11:51:16 +00:00
|
|
|
return PolicyResult(self.result, "Debugging")
|
2018-12-09 20:06:21 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
verbose_name = _("Debug Policy")
|
|
|
|
verbose_name_plural = _("Debug Policies")
|
2018-12-10 12:48:22 +00:00
|
|
|
|
2019-04-29 21:19:37 +00:00
|
|
|
|
2020-01-19 20:01:26 +00:00
|
|
|
class Invitation(ExportModelOperationsMixin("invitation"), UUIDModel):
|
2018-12-10 13:21:42 +00:00
|
|
|
"""Single-use invitation link"""
|
2018-12-10 12:48:22 +00:00
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
created_by = models.ForeignKey("User", on_delete=models.CASCADE)
|
2018-12-10 12:48:22 +00:00
|
|
|
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)
|
2019-02-25 20:03:24 +00:00
|
|
|
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-12-31 11:51:16 +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:
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
verbose_name = _("Invitation")
|
|
|
|
verbose_name_plural = _("Invitations")
|
2019-02-25 19:46:23 +00:00
|
|
|
|
2019-10-10 12:04:58 +00:00
|
|
|
|
2020-01-19 20:01:26 +00:00
|
|
|
class Nonce(ExportModelOperationsMixin("nonce"), UUIDModel):
|
2019-03-08 11:47:50 +00:00
|
|
|
"""One-time link for password resets/sign-up-confirmations"""
|
2019-02-25 19:46:23 +00:00
|
|
|
|
|
|
|
expires = models.DateTimeField(default=default_nonce_duration)
|
2019-12-31 11:51:16 +00:00
|
|
|
user = models.ForeignKey("User", on_delete=models.CASCADE)
|
2019-04-04 19:49:10 +00:00
|
|
|
expiring = models.BooleanField(default=True)
|
2019-12-31 11:51:16 +00:00
|
|
|
description = models.TextField(default="", blank=True)
|
2019-10-10 12:04:58 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_expired(self) -> bool:
|
|
|
|
"""Check if nonce is expired yet."""
|
|
|
|
return now() > self.expires
|
2019-02-25 19:46:23 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
2019-10-10 12:04:58 +00:00
|
|
|
return f"Nonce f{self.uuid.hex} {self.description} (expires={self.expires})"
|
2019-02-25 19:46:23 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
verbose_name = _("Nonce")
|
|
|
|
verbose_name_plural = _("Nonces")
|
2019-03-08 11:47:50 +00:00
|
|
|
|
2019-10-10 12:04:58 +00:00
|
|
|
|
2019-03-08 11:47:50 +00:00
|
|
|
class PropertyMapping(UUIDModel):
|
|
|
|
"""User-defined key -> x mapping which can be used by providers to expose extra data."""
|
|
|
|
|
|
|
|
name = models.TextField()
|
2020-02-17 19:38:14 +00:00
|
|
|
expression = models.TextField()
|
2019-03-08 11:47:50 +00:00
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
form = ""
|
2019-03-08 11:47:50 +00:00
|
|
|
objects = InheritanceManager()
|
|
|
|
|
2020-02-18 21:12:51 +00:00
|
|
|
def evaluate(
|
|
|
|
self, user: Optional[User], request: Optional[HttpRequest], **kwargs
|
|
|
|
) -> Any:
|
2020-02-17 19:38:14 +00:00
|
|
|
"""Evaluate `self.expression` using `**kwargs` as Context."""
|
2020-02-18 09:12:42 +00:00
|
|
|
try:
|
|
|
|
expression = NATIVE_ENVIRONMENT.from_string(self.expression)
|
|
|
|
except TemplateSyntaxError as exc:
|
|
|
|
raise PropertyMappingExpressionException from exc
|
|
|
|
try:
|
2020-02-19 15:18:31 +00:00
|
|
|
response = expression.render(user=user, request=request, **kwargs)
|
|
|
|
if isinstance(response, Undefined):
|
|
|
|
raise PropertyMappingExpressionException("Response was 'Undefined'")
|
|
|
|
return response
|
2020-02-18 09:12:42 +00:00
|
|
|
except UndefinedError as exc:
|
|
|
|
raise PropertyMappingExpressionException from exc
|
2020-02-17 16:47:51 +00:00
|
|
|
|
2020-02-18 14:12:05 +00:00
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
try:
|
|
|
|
NATIVE_ENVIRONMENT.from_string(self.expression)
|
|
|
|
except TemplateSyntaxError as exc:
|
|
|
|
raise ValidationError("Expression Syntax Error") from exc
|
|
|
|
return super().save(*args, **kwargs)
|
|
|
|
|
2019-03-08 11:47:50 +00:00
|
|
|
def __str__(self):
|
2019-10-07 14:33:48 +00:00
|
|
|
return f"Property Mapping {self.name}"
|
2019-03-08 11:47:50 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
verbose_name = _("Property Mapping")
|
|
|
|
verbose_name_plural = _("Property Mappings")
|