2018-11-11 12:41:48 +00:00
|
|
|
"""passbook core models"""
|
2019-02-25 19:46:23 +00:00
|
|
|
from datetime import timedelta
|
2020-07-20 16:17:14 +00:00
|
|
|
from typing import Any, Optional, Type
|
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
|
2018-11-11 12:41:48 +00:00
|
|
|
from django.db import models
|
2020-07-05 21:14:57 +00:00
|
|
|
from django.db.models import Q, QuerySet
|
2020-07-20 16:17:14 +00:00
|
|
|
from django.forms import ModelForm
|
2020-02-17 16:47:51 +00:00
|
|
|
from django.http import HttpRequest
|
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 _
|
2019-10-10 08:45:51 +00:00
|
|
|
from guardian.mixins import GuardianUserMixin
|
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
|
2020-06-07 14:35:08 +00:00
|
|
|
from passbook.flows.models import Flow
|
2020-05-20 07:17:06 +00:00
|
|
|
from passbook.lib.models import CreatedUpdatedModel
|
2020-05-16 16:07:00 +00:00
|
|
|
from passbook.policies.models import PolicyBindingModel
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2019-10-04 08:08:53 +00:00
|
|
|
LOGGER = get_logger()
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2019-02-25 19:46:23 +00:00
|
|
|
|
2020-05-16 14:11:53 +00:00
|
|
|
def default_token_duration():
|
|
|
|
"""Default duration a Token is valid"""
|
2020-05-10 18:15:56 +00:00
|
|
|
return now() + timedelta(minutes=30)
|
2019-02-25 19:46:23 +00:00
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
|
2020-05-20 07:17:06 +00:00
|
|
|
class Group(models.Model):
|
2018-12-26 23:38:42 +00:00
|
|
|
"""Custom Group model which supports a basic hierarchy"""
|
|
|
|
|
2020-05-20 07:17:06 +00:00
|
|
|
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)
|
|
|
|
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-05-20 07:17:06 +00:00
|
|
|
class 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)
|
2020-02-21 14:12:16 +00:00
|
|
|
name = models.TextField(help_text=_("User's display name."))
|
2019-02-27 14:09:05 +00:00
|
|
|
|
2020-05-16 14:02:42 +00:00
|
|
|
sources = models.ManyToManyField("Source", through="UserSourceConnection")
|
2019-12-31 11:51:16 +00:00
|
|
|
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"),)
|
2020-07-03 22:16:16 +00:00
|
|
|
verbose_name = _("User")
|
|
|
|
verbose_name_plural = _("Users")
|
2019-12-31 11:51:16 +00:00
|
|
|
|
2019-10-10 11:01:36 +00:00
|
|
|
|
2020-05-20 07:17:06 +00:00
|
|
|
class Provider(models.Model):
|
2020-05-16 14:02:42 +00:00
|
|
|
"""Application-independent Provider instance. For example SAML2 Remote, OAuth2 Application"""
|
|
|
|
|
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",
|
|
|
|
)
|
|
|
|
|
2020-05-16 14:02:42 +00:00
|
|
|
property_mappings = models.ManyToManyField(
|
|
|
|
"PropertyMapping", default=None, blank=True
|
|
|
|
)
|
|
|
|
|
|
|
|
objects = InheritanceManager()
|
|
|
|
|
2020-07-20 16:17:14 +00:00
|
|
|
def form(self) -> Type[ModelForm]:
|
|
|
|
"""Return Form class used to edit this object"""
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2020-05-16 14:02:42 +00:00
|
|
|
# This class defines no field for easier inheritance
|
|
|
|
def __str__(self):
|
|
|
|
if hasattr(self, "name"):
|
|
|
|
return getattr(self, "name")
|
|
|
|
return super().__str__()
|
|
|
|
|
|
|
|
|
2020-05-20 07:17:06 +00:00
|
|
|
class Application(PolicyBindingModel):
|
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"""
|
|
|
|
|
2020-02-21 14:12:16 +00:00
|
|
|
name = models.TextField(help_text=_("Application's display Name."))
|
|
|
|
slug = models.SlugField(help_text=_("Internal application name, used in URLs."))
|
2020-05-16 14:02:42 +00:00
|
|
|
provider = models.OneToOneField(
|
|
|
|
"Provider", null=True, blank=True, default=None, on_delete=models.SET_DEFAULT
|
2019-12-31 11:51:16 +00:00
|
|
|
)
|
2020-02-20 12:45:22 +00:00
|
|
|
|
2020-02-21 22:10:00 +00:00
|
|
|
meta_launch_url = models.URLField(default="", blank=True)
|
|
|
|
meta_icon_url = models.TextField(default="", blank=True)
|
|
|
|
meta_description = models.TextField(default="", blank=True)
|
|
|
|
meta_publisher = models.TextField(default="", blank=True)
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2020-05-16 14:02:42 +00:00
|
|
|
def get_provider(self) -> Optional[Provider]:
|
|
|
|
"""Get casted provider instance"""
|
|
|
|
if not self.provider:
|
2019-03-07 13:09:52 +00:00
|
|
|
return None
|
2020-05-16 14:02:42 +00:00
|
|
|
return Provider.objects.get_subclass(pk=self.provider.pk)
|
2019-02-27 13:47:11 +00:00
|
|
|
|
2018-11-11 12:41:48 +00:00
|
|
|
def __str__(self):
|
|
|
|
return self.name
|
|
|
|
|
2020-07-03 22:16:16 +00:00
|
|
|
class Meta:
|
|
|
|
|
|
|
|
verbose_name = _("Application")
|
|
|
|
verbose_name_plural = _("Applications")
|
|
|
|
|
2019-10-07 14:33:48 +00:00
|
|
|
|
2020-05-20 07:17:06 +00:00
|
|
|
class Source(PolicyBindingModel):
|
2018-11-11 12:41:48 +00:00
|
|
|
"""Base Authentication source, i.e. an OAuth Provider, SAML Remote or LDAP Server"""
|
|
|
|
|
2020-05-16 14:02:42 +00:00
|
|
|
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
|
|
|
|
)
|
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
|
|
|
|
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",
|
|
|
|
)
|
|
|
|
|
2018-11-16 08:10:35 +00:00
|
|
|
objects = InheritanceManager()
|
|
|
|
|
2020-07-20 16:17:14 +00:00
|
|
|
def form(self) -> Type[ModelForm]:
|
|
|
|
"""Return Form class used to edit this object"""
|
|
|
|
raise NotImplementedError
|
|
|
|
|
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
|
|
|
|
2020-05-16 14:02:42 +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)
|
2020-05-16 14:02:42 +00:00
|
|
|
source = models.ForeignKey(Source, on_delete=models.CASCADE)
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2020-05-15 20:15:01 +00:00
|
|
|
class Meta:
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2020-05-16 14:02:42 +00:00
|
|
|
unique_together = (("user", "source"),)
|
2018-12-09 20:06:21 +00:00
|
|
|
|
2019-02-25 19:46:23 +00:00
|
|
|
|
2020-07-20 08:57:12 +00:00
|
|
|
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`"""
|
|
|
|
query = Q(**kwargs)
|
|
|
|
query_not_expired_yet = Q(expires__lt=now(), expiring=True)
|
|
|
|
query_not_expiring = Q(expiring=False)
|
|
|
|
return cls.objects.filter(query & (query_not_expired_yet | query_not_expiring))
|
|
|
|
|
|
|
|
@property
|
|
|
|
def is_expired(self) -> bool:
|
|
|
|
"""Check if token is expired yet."""
|
|
|
|
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 user token
|
|
|
|
INTENT_VERIFICATION = "verification"
|
|
|
|
|
|
|
|
# Allow access to API
|
|
|
|
INTENT_API = "api"
|
|
|
|
|
|
|
|
|
2020-07-20 08:57:12 +00:00
|
|
|
class Token(ExpiringModel):
|
2020-07-05 21:14:57 +00:00
|
|
|
"""Token used to authenticate the User for API Access or confirm another Stage like Email."""
|
2020-05-15 20:15:01 +00:00
|
|
|
|
2020-05-20 07:17:06 +00:00
|
|
|
token_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
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="+")
|
2020-05-16 14:02:42 +00:00
|
|
|
description = models.TextField(default="", blank=True)
|
|
|
|
|
2019-02-25 19:46:23 +00:00
|
|
|
def __str__(self):
|
2020-05-20 07:17:06 +00:00
|
|
|
return (
|
2020-07-05 21:14:57 +00:00
|
|
|
f"Token {self.token_uuid.hex} {self.description} (expires={self.expires})"
|
2020-05-20 07:17:06 +00:00
|
|
|
)
|
2019-02-25 19:46:23 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
2020-05-16 14:11:53 +00:00
|
|
|
verbose_name = _("Token")
|
|
|
|
verbose_name_plural = _("Tokens")
|
2019-03-08 11:47:50 +00:00
|
|
|
|
2019-10-10 12:04:58 +00:00
|
|
|
|
2020-05-20 07:17:06 +00:00
|
|
|
class PropertyMapping(models.Model):
|
2019-03-08 11:47:50 +00:00
|
|
|
"""User-defined key -> x mapping which can be used by providers to expose extra data."""
|
|
|
|
|
2020-05-20 07:17:06 +00:00
|
|
|
pm_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
2019-03-08 11:47:50 +00:00
|
|
|
name = models.TextField()
|
2020-02-17 19:38:14 +00:00
|
|
|
expression = models.TextField()
|
2019-03-08 11:47:50 +00:00
|
|
|
|
|
|
|
objects = InheritanceManager()
|
|
|
|
|
2020-07-20 16:17:14 +00:00
|
|
|
def form(self) -> Type[ModelForm]:
|
|
|
|
"""Return Form class used to edit this object"""
|
|
|
|
raise NotImplementedError
|
|
|
|
|
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-06-05 10:00:27 +00:00
|
|
|
from passbook.core.expression import PropertyMappingEvaluator
|
2020-06-01 13:25:38 +00:00
|
|
|
|
2020-06-05 10:00:27 +00:00
|
|
|
evaluator = PropertyMappingEvaluator()
|
|
|
|
evaluator.set_context(user, request, **kwargs)
|
2020-02-18 09:12:42 +00:00
|
|
|
try:
|
2020-06-05 10:00:27 +00:00
|
|
|
return evaluator.evaluate(self.expression)
|
|
|
|
except (ValueError, SyntaxError) as exc:
|
2020-02-18 09:12:42 +00:00
|
|
|
raise PropertyMappingExpressionException from exc
|
2020-02-18 14:12:05 +00:00
|
|
|
|
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")
|