2016-07-03 16:11:48 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
2015-05-27 20:10:06 +00:00
|
|
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
|
|
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
|
|
|
# FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
|
|
|
|
# more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License version 3
|
|
|
|
# along with this program; if not, write to the Free Software Foundation, Inc., 51
|
|
|
|
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
|
|
#
|
2016-06-30 22:00:53 +00:00
|
|
|
# (c) 2015-2016 Valentin Samir
|
2015-05-27 19:56:39 +00:00
|
|
|
"""models for the app"""
|
2016-07-20 16:28:23 +00:00
|
|
|
from .default_settings import settings, SessionStore
|
2015-05-28 15:30:27 +00:00
|
|
|
|
2015-05-16 21:43:46 +00:00
|
|
|
from django.db import models
|
2015-05-28 15:30:27 +00:00
|
|
|
from django.db.models import Q
|
2015-05-16 21:43:46 +00:00
|
|
|
from django.contrib import messages
|
2015-05-27 20:56:20 +00:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2015-05-28 12:02:17 +00:00
|
|
|
from django.utils import timezone
|
2016-07-04 15:23:11 +00:00
|
|
|
from django.utils.encoding import python_2_unicode_compatible
|
2016-07-29 12:33:02 +00:00
|
|
|
from django.core.mail import send_mail
|
2015-05-16 21:43:46 +00:00
|
|
|
|
|
|
|
import re
|
2015-05-28 15:30:27 +00:00
|
|
|
import sys
|
2016-07-29 12:33:02 +00:00
|
|
|
import smtplib
|
2015-12-13 12:50:29 +00:00
|
|
|
import logging
|
2015-05-28 15:30:27 +00:00
|
|
|
from datetime import timedelta
|
2015-05-18 18:30:00 +00:00
|
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
from requests_futures.sessions import FuturesSession
|
2015-05-16 21:43:46 +00:00
|
|
|
|
2016-08-05 15:56:34 +00:00
|
|
|
from cas_server import utils
|
2016-07-29 12:33:02 +00:00
|
|
|
from . import VERSION
|
2015-05-27 19:56:39 +00:00
|
|
|
|
2016-07-20 16:28:23 +00:00
|
|
|
#: logger facility
|
2015-12-13 12:50:29 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2016-08-05 15:56:34 +00:00
|
|
|
class JsonAttributes(models.Model):
|
|
|
|
"""
|
|
|
|
Bases: :class:`django.db.models.Model`
|
|
|
|
|
|
|
|
A base class for models storing attributes as a json
|
|
|
|
"""
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
abstract = True
|
|
|
|
|
|
|
|
#: The attributes json encoded
|
|
|
|
_attributs = models.TextField(default=None, null=True, blank=True)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def attributs(self):
|
|
|
|
"""The attributes"""
|
|
|
|
if self._attributs is not None:
|
|
|
|
return utils.json.loads(self._attributs)
|
|
|
|
|
|
|
|
@attributs.setter
|
|
|
|
def attributs(self, value):
|
|
|
|
"""attributs property setter"""
|
|
|
|
self._attributs = utils.json_encode(value)
|
|
|
|
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
|
|
|
class FederatedIendityProvider(models.Model):
|
2016-07-06 17:43:09 +00:00
|
|
|
"""
|
2016-07-20 16:28:23 +00:00
|
|
|
Bases: :class:`django.db.models.Model`
|
|
|
|
|
2016-07-06 17:43:09 +00:00
|
|
|
An identity provider for the federated mode
|
|
|
|
"""
|
2016-07-04 15:23:11 +00:00
|
|
|
class Meta:
|
2016-07-06 17:43:09 +00:00
|
|
|
verbose_name = _(u"identity provider")
|
|
|
|
verbose_name_plural = _(u"identity providers")
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Suffix append to backend CAS returned username: ``returned_username`` @ ``suffix``.
|
|
|
|
#: it must be unique.
|
2016-07-04 15:23:11 +00:00
|
|
|
suffix = models.CharField(
|
|
|
|
max_length=30,
|
|
|
|
unique=True,
|
|
|
|
verbose_name=_(u"suffix"),
|
2016-07-06 17:43:09 +00:00
|
|
|
help_text=_(
|
2016-07-20 16:28:23 +00:00
|
|
|
u"Suffix append to backend CAS returned "
|
2016-07-06 17:43:09 +00:00
|
|
|
u"username: ``returned_username`` @ ``suffix``."
|
|
|
|
)
|
2016-07-04 15:23:11 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: URL to the root of the CAS server application. If login page is
|
|
|
|
#: https://cas.example.net/cas/login then :attr:`server_url` should be
|
|
|
|
#: https://cas.example.net/cas/
|
2016-07-04 15:23:11 +00:00
|
|
|
server_url = models.CharField(max_length=255, verbose_name=_(u"server url"))
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Version of the CAS protocol to use when sending requests the the backend CAS.
|
2016-07-04 15:23:11 +00:00
|
|
|
cas_protocol_version = models.CharField(
|
|
|
|
max_length=30,
|
|
|
|
choices=[
|
|
|
|
("1", "CAS 1.0"),
|
|
|
|
("2", "CAS 2.0"),
|
|
|
|
("3", "CAS 3.0"),
|
|
|
|
("CAS_2_SAML_1_0", "SAML 1.1")
|
|
|
|
],
|
|
|
|
verbose_name=_(u"CAS protocol version"),
|
2016-07-06 17:43:09 +00:00
|
|
|
help_text=_(
|
|
|
|
u"Version of the CAS protocol to use when sending requests the the backend CAS."
|
|
|
|
),
|
2016-07-04 15:23:11 +00:00
|
|
|
default="3"
|
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Name for this identity provider displayed on the login page.
|
2016-07-04 15:23:11 +00:00
|
|
|
verbose_name = models.CharField(
|
|
|
|
max_length=255,
|
|
|
|
verbose_name=_(u"verbose name"),
|
2016-07-06 17:43:09 +00:00
|
|
|
help_text=_(u"Name for this identity provider displayed on the login page.")
|
2016-07-04 15:23:11 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Position of the identity provider on the login page. Identity provider are sorted using the
|
|
|
|
#: (:attr:`pos`, :attr:`verbose_name`, :attr:`suffix`) attributes.
|
2016-07-04 15:23:11 +00:00
|
|
|
pos = models.IntegerField(
|
|
|
|
default=100,
|
|
|
|
verbose_name=_(u"position"),
|
|
|
|
help_text=_(
|
|
|
|
(
|
2016-07-06 17:43:09 +00:00
|
|
|
u"Position of the identity provider on the login page. "
|
2016-07-04 15:23:11 +00:00
|
|
|
u"Identity provider are sorted using the "
|
2016-07-06 17:43:09 +00:00
|
|
|
u"(position, verbose name, suffix) attributes."
|
2016-07-04 15:23:11 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Display the provider on the login page. Beware that this do not disable the identity
|
|
|
|
#: provider, it just hide it on the login page. User will always be able to log in using this
|
|
|
|
#: provider by fetching ``/federate/suffix``.
|
2016-07-04 15:40:31 +00:00
|
|
|
display = models.BooleanField(
|
|
|
|
default=True,
|
|
|
|
verbose_name=_(u"display"),
|
2016-07-06 17:43:09 +00:00
|
|
|
help_text=_("Display the provider on the login page.")
|
2016-07-04 15:40:31 +00:00
|
|
|
)
|
2016-07-04 15:23:11 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.verbose_name
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def build_username_from_suffix(username, suffix):
|
2016-07-06 17:43:09 +00:00
|
|
|
"""
|
|
|
|
Transform backend username into federated username using ``suffix``
|
|
|
|
|
|
|
|
:param unicode username: A CAS backend returned username
|
|
|
|
:param unicode suffix: A suffix identifying the CAS backend
|
2016-07-20 16:28:23 +00:00
|
|
|
:return: The federated username: ``username`` @ ``suffix``.
|
|
|
|
:rtype: unicode
|
2016-07-06 17:43:09 +00:00
|
|
|
"""
|
2016-07-04 15:23:11 +00:00
|
|
|
return u'%s@%s' % (username, suffix)
|
|
|
|
|
|
|
|
def build_username(self, username):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Transform backend username into federated username
|
|
|
|
|
|
|
|
:param unicode username: A CAS backend returned username
|
|
|
|
:return: The federated username: ``username`` @ :attr:`suffix`.
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
2016-07-04 15:23:11 +00:00
|
|
|
return u'%s@%s' % (username, self.suffix)
|
|
|
|
|
|
|
|
|
|
|
|
@python_2_unicode_compatible
|
2016-08-05 15:56:34 +00:00
|
|
|
class FederatedUser(JsonAttributes):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
2016-08-05 15:56:34 +00:00
|
|
|
Bases: :class:`JsonAttributes`
|
2016-07-20 16:28:23 +00:00
|
|
|
|
|
|
|
A federated user as returner by a CAS provider (username and attributes)
|
|
|
|
"""
|
2016-06-17 17:28:49 +00:00
|
|
|
class Meta:
|
|
|
|
unique_together = ("username", "provider")
|
2016-10-07 13:22:49 +00:00
|
|
|
verbose_name = _("Federated user")
|
|
|
|
verbose_name_plural = _("Federated users")
|
2016-07-20 16:28:23 +00:00
|
|
|
#: The user username returned by the CAS backend on successful ticket validation
|
2016-06-17 17:28:49 +00:00
|
|
|
username = models.CharField(max_length=124)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: A foreign key to :class:`FederatedIendityProvider`
|
2016-07-04 15:23:11 +00:00
|
|
|
provider = models.ForeignKey(FederatedIendityProvider, on_delete=models.CASCADE)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: The last ticket used to authenticate :attr:`username` against :attr:`provider`
|
2016-06-17 17:28:49 +00:00
|
|
|
ticket = models.CharField(max_length=255)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Last update timespampt. Usually, the last time :attr:`ticket` has been set.
|
2016-06-17 17:28:49 +00:00
|
|
|
last_update = models.DateTimeField(auto_now=True)
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
|
|
|
return self.federated_username
|
|
|
|
|
|
|
|
@property
|
|
|
|
def federated_username(self):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""The federated username with a suffix for the current :class:`FederatedUser`."""
|
2016-07-04 15:23:11 +00:00
|
|
|
return self.provider.build_username(self.username)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_from_federated_username(cls, username):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
:return: A :class:`FederatedUser` object from a federated ``username``
|
|
|
|
:rtype: :class:`FederatedUser`
|
|
|
|
"""
|
2016-07-04 15:23:11 +00:00
|
|
|
if username is None:
|
|
|
|
raise cls.DoesNotExist()
|
|
|
|
else:
|
|
|
|
component = username.split('@')
|
|
|
|
username = '@'.join(component[:-1])
|
|
|
|
suffix = component[-1]
|
|
|
|
try:
|
|
|
|
provider = FederatedIendityProvider.objects.get(suffix=suffix)
|
|
|
|
return cls.objects.get(username=username, provider=provider)
|
|
|
|
except FederatedIendityProvider.DoesNotExist:
|
|
|
|
raise cls.DoesNotExist()
|
2016-06-19 11:00:28 +00:00
|
|
|
|
2016-07-03 11:51:00 +00:00
|
|
|
@classmethod
|
|
|
|
def clean_old_entries(cls):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""remove old unused :class:`FederatedUser`"""
|
2016-07-03 11:51:00 +00:00
|
|
|
federated_users = cls.objects.filter(
|
|
|
|
last_update__lt=(timezone.now() - timedelta(seconds=settings.CAS_TICKET_TIMEOUT))
|
|
|
|
)
|
|
|
|
known_users = {user.username for user in User.objects.all()}
|
|
|
|
for user in federated_users:
|
2016-07-04 15:23:11 +00:00
|
|
|
if user.federated_username not in known_users:
|
2016-07-03 11:51:00 +00:00
|
|
|
user.delete()
|
|
|
|
|
2016-06-17 17:28:49 +00:00
|
|
|
|
2016-06-23 15:18:53 +00:00
|
|
|
class FederateSLO(models.Model):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`django.db.models.Model`
|
|
|
|
|
|
|
|
An association between a CAS provider ticket and a (username, session) for processing SLO
|
|
|
|
"""
|
2016-06-23 15:18:53 +00:00
|
|
|
class Meta:
|
2016-07-04 15:23:11 +00:00
|
|
|
unique_together = ("username", "session_key", "ticket")
|
2016-07-20 16:28:23 +00:00
|
|
|
#: the federated username with the ``@``component
|
2016-06-23 15:18:53 +00:00
|
|
|
username = models.CharField(max_length=30)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: the session key for the session :attr:`username` has been authenticated using :attr:`ticket`
|
2016-06-23 15:18:53 +00:00
|
|
|
session_key = models.CharField(max_length=40, blank=True, null=True)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: The ticket used to authenticate :attr:`username`
|
2016-07-04 15:23:11 +00:00
|
|
|
ticket = models.CharField(max_length=255, db_index=True)
|
2016-06-23 15:18:53 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def clean_deleted_sessions(cls):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""remove old :class:`FederateSLO` object for which the session do not exists anymore"""
|
2016-06-23 15:18:53 +00:00
|
|
|
for federate_slo in cls.objects.all():
|
|
|
|
if not SessionStore(session_key=federate_slo.session_key).get('authenticated'):
|
|
|
|
federate_slo.delete()
|
|
|
|
|
|
|
|
|
2016-10-07 13:22:49 +00:00
|
|
|
@python_2_unicode_compatible
|
|
|
|
class UserAttributes(JsonAttributes):
|
|
|
|
"""
|
|
|
|
Bases: :class:`JsonAttributes`
|
|
|
|
|
|
|
|
Local cache of the user attributes, used then needed
|
|
|
|
"""
|
|
|
|
class Meta:
|
|
|
|
verbose_name = _("User attributes cache")
|
|
|
|
verbose_name_plural = _("User attributes caches")
|
|
|
|
#: The username of the user for which we cache attributes
|
|
|
|
username = models.CharField(max_length=155, unique=True)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.username
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def clean_old_entries(cls):
|
|
|
|
"""Remove :class:`UserAttributes` for which no more :class:`User` exists."""
|
|
|
|
for user in cls.objects.all():
|
|
|
|
if User.objects.filter(username=user.username).count() == 0:
|
|
|
|
user.delete()
|
|
|
|
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
2015-05-16 21:43:46 +00:00
|
|
|
class User(models.Model):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`django.db.models.Model`
|
|
|
|
|
|
|
|
A user logged into the CAS
|
|
|
|
"""
|
2015-06-09 20:04:05 +00:00
|
|
|
class Meta:
|
2015-06-11 21:04:26 +00:00
|
|
|
unique_together = ("username", "session_key")
|
2015-12-17 18:24:10 +00:00
|
|
|
verbose_name = _("User")
|
|
|
|
verbose_name_plural = _("Users")
|
2016-07-20 16:28:23 +00:00
|
|
|
#: The session key of the current authenticated user
|
2015-06-11 21:04:26 +00:00
|
|
|
session_key = models.CharField(max_length=40, blank=True, null=True)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: The username of the current authenticated user
|
2015-06-09 20:04:05 +00:00
|
|
|
username = models.CharField(max_length=30)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Last time the authenticated user has do something (auth, fetch ticket, etc…)
|
2015-12-12 12:51:59 +00:00
|
|
|
date = models.DateTimeField(auto_now=True)
|
2016-10-07 13:22:49 +00:00
|
|
|
#: last time the user logged
|
|
|
|
last_login = models.DateTimeField(auto_now_add=True)
|
2015-05-16 21:43:46 +00:00
|
|
|
|
2016-07-03 11:51:00 +00:00
|
|
|
def delete(self, *args, **kwargs):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Remove the current :class:`User`. If ``settings.CAS_FEDERATE`` is ``True``, also delete
|
|
|
|
the corresponding :class:`FederateSLO` object.
|
|
|
|
"""
|
2016-07-03 11:51:00 +00:00
|
|
|
if settings.CAS_FEDERATE:
|
|
|
|
FederateSLO.objects.filter(
|
|
|
|
username=self.username,
|
|
|
|
session_key=self.session_key
|
|
|
|
).delete()
|
|
|
|
super(User, self).delete(*args, **kwargs)
|
|
|
|
|
2015-06-09 20:04:05 +00:00
|
|
|
@classmethod
|
|
|
|
def clean_old_entries(cls):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Remove :class:`User` objects inactive since more that
|
|
|
|
:django:setting:`SESSION_COOKIE_AGE` and send corresponding SingleLogOut requests.
|
|
|
|
"""
|
2016-10-07 13:22:49 +00:00
|
|
|
filter = Q(date__lt=(timezone.now() - timedelta(seconds=settings.SESSION_COOKIE_AGE)))
|
|
|
|
if settings.CAS_TGT_VALIDITY is not None:
|
|
|
|
filter |= Q(
|
|
|
|
last_login__lt=(timezone.now() - timedelta(seconds=settings.CAS_TGT_VALIDITY))
|
|
|
|
)
|
|
|
|
users = cls.objects.filter(filter)
|
2015-06-09 20:04:05 +00:00
|
|
|
for user in users:
|
|
|
|
user.logout()
|
|
|
|
users.delete()
|
|
|
|
|
2015-06-11 21:04:26 +00:00
|
|
|
@classmethod
|
|
|
|
def clean_deleted_sessions(cls):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""Remove :class:`User` objects where the corresponding session do not exists anymore."""
|
2015-06-11 21:04:26 +00:00
|
|
|
for user in cls.objects.all():
|
|
|
|
if not SessionStore(session_key=user.session_key).get('authenticated'):
|
|
|
|
user.logout()
|
|
|
|
user.delete()
|
|
|
|
|
2015-05-30 17:45:59 +00:00
|
|
|
@property
|
|
|
|
def attributs(self):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Property.
|
2016-10-07 13:22:49 +00:00
|
|
|
A fresh :class:`dict` for the user attributes, using ``settings.CAS_AUTH_CLASS`` if
|
|
|
|
possible, and if not, try to fallback to cached attributes (actually only used for ldap
|
|
|
|
auth class with bind password check mthode).
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
2016-10-07 13:22:49 +00:00
|
|
|
try:
|
|
|
|
return utils.import_attr(settings.CAS_AUTH_CLASS)(self.username).attributs()
|
|
|
|
except NotImplementedError:
|
|
|
|
try:
|
|
|
|
user = UserAttributes.objects.get(username=self.username)
|
|
|
|
attributes = user.attributs
|
|
|
|
if attributes is not None:
|
|
|
|
return attributes
|
|
|
|
else:
|
|
|
|
return {}
|
|
|
|
except UserAttributes.DoesNotExist:
|
|
|
|
return {}
|
2015-05-30 17:45:59 +00:00
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
2015-06-11 21:34:25 +00:00
|
|
|
return u"%s - %s" % (self.username, self.session_key)
|
2015-05-16 21:43:46 +00:00
|
|
|
|
2015-06-09 20:04:05 +00:00
|
|
|
def logout(self, request=None):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Send SLO requests to all services the user is logged in.
|
|
|
|
|
|
|
|
:param request: The current django HttpRequest to display possible failure to the user.
|
|
|
|
:type request: :class:`django.http.HttpRequest` or :obj:`NoneType<types.NoneType>`
|
|
|
|
"""
|
2015-11-14 00:05:53 +00:00
|
|
|
ticket_classes = [ProxyGrantingTicket, ServiceTicket, ProxyTicket]
|
2016-08-05 15:56:34 +00:00
|
|
|
for error in Ticket.send_slos(
|
|
|
|
[ticket_class.objects.filter(user=self) for ticket_class in ticket_classes]
|
|
|
|
):
|
|
|
|
logger.warning(
|
|
|
|
"Error during SLO for user %s: %s" % (
|
|
|
|
self.username,
|
|
|
|
error
|
|
|
|
)
|
|
|
|
)
|
|
|
|
if request is not None:
|
|
|
|
error = utils.unpack_nested_exception(error)
|
|
|
|
messages.add_message(
|
|
|
|
request,
|
|
|
|
messages.WARNING,
|
|
|
|
_(u'Error during service logout %s') % error
|
|
|
|
)
|
2015-05-27 19:56:39 +00:00
|
|
|
|
|
|
|
def get_ticket(self, ticket_class, service, service_pattern, renew):
|
|
|
|
"""
|
2016-07-20 16:28:23 +00:00
|
|
|
Generate a ticket using ``ticket_class`` for the service
|
|
|
|
``service`` matching ``service_pattern`` and asking or not for
|
|
|
|
authentication renewal with ``renew``
|
|
|
|
|
|
|
|
:param type ticket_class: :class:`ServiceTicket` or :class:`ProxyTicket` or
|
|
|
|
:class:`ProxyGrantingTicket`.
|
|
|
|
:param unicode service: The service url for which we want a ticket.
|
|
|
|
:param ServicePattern service_pattern: The service pattern matching ``service``.
|
|
|
|
Beware that ``service`` must match :attr:`ServicePattern.pattern` and the current
|
|
|
|
:class:`User` must pass :meth:`ServicePattern.check_user`. These checks are not done
|
|
|
|
here and you must perform them before calling this method.
|
|
|
|
:param bool renew: Should be ``True`` if authentication has been renewed. Must be
|
|
|
|
``False`` otherwise.
|
|
|
|
:return: A :class:`Ticket` object.
|
|
|
|
:rtype: :class:`ServiceTicket` or :class:`ProxyTicket` or
|
|
|
|
:class:`ProxyGrantingTicket`.
|
2015-05-27 19:56:39 +00:00
|
|
|
"""
|
|
|
|
attributs = dict(
|
|
|
|
(a.name, a.replace if a.replace else a.name) for a in service_pattern.attributs.all()
|
|
|
|
)
|
|
|
|
replacements = dict(
|
2016-06-30 11:55:19 +00:00
|
|
|
(a.attribut, (a.pattern, a.replace)) for a in service_pattern.replacements.all()
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2015-05-18 18:30:00 +00:00
|
|
|
service_attributs = {}
|
2015-05-27 19:56:39 +00:00
|
|
|
for (key, value) in self.attributs.items():
|
2015-06-07 12:39:12 +00:00
|
|
|
if key in attributs or '*' in attributs:
|
2015-05-27 19:56:39 +00:00
|
|
|
if key in replacements:
|
2016-06-30 11:55:19 +00:00
|
|
|
if isinstance(value, list):
|
|
|
|
for index, subval in enumerate(value):
|
|
|
|
value[index] = re.sub(
|
|
|
|
replacements[key][0],
|
|
|
|
replacements[key][1],
|
|
|
|
subval
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
value = re.sub(replacements[key][0], replacements[key][1], value)
|
2015-06-07 12:39:12 +00:00
|
|
|
service_attributs[attributs.get(key, key)] = value
|
2015-05-27 19:56:39 +00:00
|
|
|
ticket = ticket_class.objects.create(
|
|
|
|
user=self,
|
|
|
|
attributs=service_attributs,
|
|
|
|
service=service,
|
|
|
|
renew=renew,
|
2015-05-28 12:02:17 +00:00
|
|
|
service_pattern=service_pattern,
|
|
|
|
single_log_out=service_pattern.single_log_out
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2015-05-16 21:43:46 +00:00
|
|
|
ticket.save()
|
2015-06-11 21:04:26 +00:00
|
|
|
self.save()
|
2015-05-18 18:30:00 +00:00
|
|
|
return ticket
|
|
|
|
|
|
|
|
def get_service_url(self, service, service_pattern, renew):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Return the url to which the user must be redirected to
|
|
|
|
after a Service Ticket has been generated
|
|
|
|
|
|
|
|
:param unicode service: The service url for which we want a ticket.
|
|
|
|
:param ServicePattern service_pattern: The service pattern matching ``service``.
|
|
|
|
Beware that ``service`` must match :attr:`ServicePattern.pattern` and the current
|
|
|
|
:class:`User` must pass :meth:`ServicePattern.check_user`. These checks are not done
|
|
|
|
here and you must perform them before calling this method.
|
|
|
|
:param bool renew: Should be ``True`` if authentication has been renewed. Must be
|
|
|
|
``False`` otherwise.
|
|
|
|
:return unicode: The service url with the ticket GET param added.
|
|
|
|
:rtype: unicode
|
|
|
|
"""
|
2015-05-18 18:30:00 +00:00
|
|
|
ticket = self.get_ticket(ServiceTicket, service, service_pattern, renew)
|
2015-06-12 16:10:52 +00:00
|
|
|
url = utils.update_url(service, {'ticket': ticket.value})
|
2015-12-13 12:50:29 +00:00
|
|
|
logger.info("Service ticket created for service %s by user %s." % (service, self.username))
|
2015-05-16 21:43:46 +00:00
|
|
|
return url
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-06-03 16:15:37 +00:00
|
|
|
class ServicePatternException(Exception):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`exceptions.Exception`
|
|
|
|
|
|
|
|
Base exception of exceptions raised in the ServicePattern model"""
|
2015-06-03 16:15:37 +00:00
|
|
|
pass
|
2015-06-12 16:10:52 +00:00
|
|
|
|
|
|
|
|
2015-06-03 16:15:37 +00:00
|
|
|
class BadUsername(ServicePatternException):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`ServicePatternException`
|
|
|
|
|
|
|
|
Exception raised then an non allowed username try to get a ticket for a service
|
|
|
|
"""
|
2015-05-17 21:24:41 +00:00
|
|
|
pass
|
2015-06-12 16:10:52 +00:00
|
|
|
|
|
|
|
|
2015-06-03 16:15:37 +00:00
|
|
|
class BadFilter(ServicePatternException):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`ServicePatternException`
|
|
|
|
|
|
|
|
Exception raised then a user try to get a ticket for a service and do not reach a condition
|
|
|
|
"""
|
2015-05-17 21:24:41 +00:00
|
|
|
pass
|
2015-05-27 19:56:39 +00:00
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-06-03 16:15:37 +00:00
|
|
|
class UserFieldNotDefined(ServicePatternException):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`ServicePatternException`
|
|
|
|
|
|
|
|
Exception raised then a user try to get a ticket for a service using as username
|
|
|
|
an attribut not present on this user
|
|
|
|
"""
|
2015-05-17 21:24:41 +00:00
|
|
|
pass
|
2015-06-12 16:10:52 +00:00
|
|
|
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
2015-05-17 21:24:41 +00:00
|
|
|
class ServicePattern(models.Model):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`django.db.models.Model`
|
|
|
|
|
2016-09-18 09:34:46 +00:00
|
|
|
Allowed services pattern against services are tested to
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
2015-05-17 21:24:41 +00:00
|
|
|
class Meta:
|
|
|
|
ordering = ("pos", )
|
2015-12-17 18:24:10 +00:00
|
|
|
verbose_name = _("Service pattern")
|
|
|
|
verbose_name_plural = _("Services patterns")
|
2015-05-17 21:24:41 +00:00
|
|
|
|
2016-07-20 16:28:23 +00:00
|
|
|
#: service patterns are sorted using the :attr:`pos` attribute
|
2015-05-27 20:56:20 +00:00
|
|
|
pos = models.IntegerField(
|
|
|
|
default=100,
|
2016-07-04 15:23:11 +00:00
|
|
|
verbose_name=_(u"position"),
|
|
|
|
help_text=_(u"service patterns are sorted using the position attribute")
|
2015-05-27 20:56:20 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: A name for the service (this can bedisplayed to the user on the login page)
|
2015-05-27 19:56:39 +00:00
|
|
|
name = models.CharField(
|
|
|
|
max_length=255,
|
|
|
|
unique=True,
|
|
|
|
blank=True,
|
|
|
|
null=True,
|
2015-05-27 20:56:20 +00:00
|
|
|
verbose_name=_(u"name"),
|
|
|
|
help_text=_(u"A name for the service")
|
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: A regular expression matching services. "Will usually looks like
|
|
|
|
#: '^https://some\\.server\\.com/path/.*$'. As it is a regular expression, special character
|
|
|
|
#: must be escaped with a '\\'.
|
2015-05-27 20:56:20 +00:00
|
|
|
pattern = models.CharField(
|
|
|
|
max_length=255,
|
|
|
|
unique=True,
|
2015-12-12 17:21:10 +00:00
|
|
|
verbose_name=_(u"pattern"),
|
|
|
|
help_text=_(
|
|
|
|
"A regular expression matching services. "
|
|
|
|
"Will usually looks like '^https://some\\.server\\.com/path/.*$'."
|
|
|
|
"As it is a regular expression, special character must be escaped with a '\\'."
|
2016-08-21 07:03:32 +00:00
|
|
|
),
|
|
|
|
validators=[utils.regexpr_validator]
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2016-07-29 23:31:43 +00:00
|
|
|
#: Name of the attribute to transmit as username, if empty the user login is used
|
2015-05-27 19:56:39 +00:00
|
|
|
user_field = models.CharField(
|
|
|
|
max_length=255,
|
|
|
|
default="",
|
|
|
|
blank=True,
|
2015-05-27 20:56:20 +00:00
|
|
|
verbose_name=_(u"user field"),
|
2016-07-29 23:31:43 +00:00
|
|
|
help_text=_("Name of the attribute to transmit as username, empty = login")
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: A boolean allowing to limit username allowed to connect to :attr:`usernames`.
|
2015-05-27 19:56:39 +00:00
|
|
|
restrict_users = models.BooleanField(
|
|
|
|
default=False,
|
2015-05-27 20:56:20 +00:00
|
|
|
verbose_name=_(u"restrict username"),
|
|
|
|
help_text=_("Limit username allowed to connect to the list provided bellow")
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: A boolean allowing to deliver :class:`ProxyTicket` to the service.
|
2015-05-27 19:56:39 +00:00
|
|
|
proxy = models.BooleanField(
|
|
|
|
default=False,
|
2015-05-27 20:56:20 +00:00
|
|
|
verbose_name=_(u"proxy"),
|
2015-05-28 13:26:46 +00:00
|
|
|
help_text=_("Proxy tickets can be delivered to the service")
|
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: A boolean allowing the service to be used as a proxy callback (via the pgtUrl GET param)
|
|
|
|
#: to deliver :class:`ProxyGrantingTicket`.
|
2015-05-28 13:26:46 +00:00
|
|
|
proxy_callback = models.BooleanField(
|
|
|
|
default=False,
|
|
|
|
verbose_name=_(u"proxy callback"),
|
|
|
|
help_text=_("can be used as a proxy callback to deliver PGT")
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Enable SingleLogOut for the service. Old validaed tickets for the service will be kept
|
|
|
|
#: until ``settings.CAS_TICKET_TIMEOUT`` after what a SLO request is send to the service and
|
|
|
|
#: the ticket is purged from database. A SLO can be send earlier if the user log-out.
|
2015-05-28 00:13:09 +00:00
|
|
|
single_log_out = models.BooleanField(
|
2015-05-27 20:23:16 +00:00
|
|
|
default=False,
|
2015-05-28 00:13:09 +00:00
|
|
|
verbose_name=_(u"single log out"),
|
|
|
|
help_text=_("Enable SLO for the service")
|
2015-05-27 20:23:16 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: An URL where the SLO request will be POST. If empty the service url will be used.
|
|
|
|
#: This is usefull for non HTTP proxied services like smtp or imap.
|
2015-06-08 16:22:10 +00:00
|
|
|
single_log_out_callback = models.CharField(
|
|
|
|
max_length=255,
|
|
|
|
default="",
|
|
|
|
blank=True,
|
|
|
|
verbose_name=_(u"single log out callback"),
|
2015-06-12 16:10:52 +00:00
|
|
|
help_text=_(u"URL where the SLO request will be POST. empty = service url\n"
|
2015-06-08 16:22:10 +00:00
|
|
|
u"This is usefull for non HTTP proxied services.")
|
|
|
|
)
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
2015-05-17 21:24:41 +00:00
|
|
|
return u"%s: %s" % (self.pos, self.pattern)
|
|
|
|
|
|
|
|
def check_user(self, user):
|
2016-07-06 17:43:09 +00:00
|
|
|
"""
|
|
|
|
Check if ``user`` if allowed to use theses services. If ``user`` is not allowed,
|
|
|
|
raises one of :class:`BadFilter`, :class:`UserFieldNotDefined`, :class:`BadUsername`
|
|
|
|
|
2016-07-20 16:28:23 +00:00
|
|
|
:param User user: a :class:`User` object
|
|
|
|
:raises BadUsername: if :attr:`restrict_users` if ``True`` and :attr:`User.username`
|
|
|
|
is not within :attr:`usernames`.
|
|
|
|
:raises BadFilter: if a :class:`FilterAttributValue` condition of :attr:`filters`
|
|
|
|
connot be verified.
|
|
|
|
:raises UserFieldNotDefined: if :attr:`user_field` is defined and its value is not
|
|
|
|
within :attr:`User.attributs`.
|
|
|
|
:return: ``True``
|
|
|
|
:rtype: bool
|
2016-07-06 17:43:09 +00:00
|
|
|
"""
|
2015-05-18 18:30:00 +00:00
|
|
|
if self.restrict_users and not self.usernames.filter(value=user.username):
|
2015-12-13 12:50:29 +00:00
|
|
|
logger.warning("Username %s not allowed on service %s" % (user.username, self.name))
|
2015-05-17 21:24:41 +00:00
|
|
|
raise BadUsername()
|
2015-05-27 19:56:39 +00:00
|
|
|
for filtre in self.filters.all():
|
2015-06-04 22:14:56 +00:00
|
|
|
if isinstance(user.attributs.get(filtre.attribut, []), list):
|
|
|
|
attrs = user.attributs.get(filtre.attribut, [])
|
2015-05-18 18:30:00 +00:00
|
|
|
else:
|
2015-05-27 19:56:39 +00:00
|
|
|
attrs = [user.attributs[filtre.attribut]]
|
|
|
|
for value in attrs:
|
|
|
|
if re.match(filtre.pattern, str(value)):
|
2015-05-18 18:30:00 +00:00
|
|
|
break
|
|
|
|
else:
|
2016-08-05 15:56:34 +00:00
|
|
|
bad_filter = (filtre.pattern, filtre.attribut, user.attributs.get(filtre.attribut))
|
2015-12-13 12:50:29 +00:00
|
|
|
logger.warning(
|
|
|
|
"User constraint failed for %s, service %s: %s do not match %s %s." % (
|
2016-08-05 15:56:34 +00:00
|
|
|
(user.username, self.name) + bad_filter
|
2015-12-13 12:50:29 +00:00
|
|
|
)
|
|
|
|
)
|
2016-08-05 15:56:34 +00:00
|
|
|
raise BadFilter('%s do not match %s %s' % bad_filter)
|
2015-05-17 21:24:41 +00:00
|
|
|
if self.user_field and not user.attributs.get(self.user_field):
|
2015-12-13 12:50:29 +00:00
|
|
|
logger.warning(
|
|
|
|
"Cannot use %s a loggin for user %s on service %s because it is absent" % (
|
|
|
|
self.user_field,
|
|
|
|
user.username,
|
|
|
|
self.name
|
|
|
|
)
|
|
|
|
)
|
2015-05-17 21:24:41 +00:00
|
|
|
raise UserFieldNotDefined()
|
|
|
|
return True
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def validate(cls, service):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Get a :class:`ServicePattern` intance from a service url.
|
|
|
|
|
|
|
|
:param unicode service: A service url
|
|
|
|
:return: A :class:`ServicePattern` instance matching ``service``.
|
|
|
|
:rtype: :class:`ServicePattern`
|
|
|
|
:raises ServicePattern.DoesNotExist: if no :class:`ServicePattern` is matching
|
|
|
|
``service``.
|
|
|
|
"""
|
2015-05-27 19:56:39 +00:00
|
|
|
for service_pattern in cls.objects.all().order_by('pos'):
|
|
|
|
if re.match(service_pattern.pattern, service):
|
|
|
|
return service_pattern
|
2015-12-13 12:50:29 +00:00
|
|
|
logger.warning("Service %s not allowed." % service)
|
2015-05-17 21:24:41 +00:00
|
|
|
raise cls.DoesNotExist()
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
2015-05-27 19:56:39 +00:00
|
|
|
class Username(models.Model):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`django.db.models.Model`
|
|
|
|
|
|
|
|
A list of allowed usernames on a :class:`ServicePattern`
|
|
|
|
"""
|
|
|
|
#: username allowed to connect to the service
|
2015-05-27 20:56:20 +00:00
|
|
|
value = models.CharField(
|
|
|
|
max_length=255,
|
|
|
|
verbose_name=_(u"username"),
|
|
|
|
help_text=_(u"username allowed to connect to the service")
|
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: ForeignKey to a :class:`ServicePattern`. :class:`Username` instances for a
|
|
|
|
#: :class:`ServicePattern` are accessible thought its :attr:`ServicePattern.usernames`
|
|
|
|
#: attribute.
|
2015-05-18 18:30:00 +00:00
|
|
|
service_pattern = models.ForeignKey(ServicePattern, related_name="usernames")
|
2015-05-18 21:38:28 +00:00
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
2015-05-27 19:56:39 +00:00
|
|
|
return self.value
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
2015-05-18 18:30:00 +00:00
|
|
|
class ReplaceAttributName(models.Model):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`django.db.models.Model`
|
|
|
|
|
|
|
|
A replacement of an attribute name for a :class:`ServicePattern`. It also tell to transmit
|
|
|
|
an attribute of :attr:`User.attributs` to the service. An empty :attr:`replace` mean
|
|
|
|
to use the original attribute name.
|
|
|
|
"""
|
2015-05-18 21:38:28 +00:00
|
|
|
class Meta:
|
2015-05-23 17:32:02 +00:00
|
|
|
unique_together = ('name', 'replace', 'service_pattern')
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Name the attribute: a key of :attr:`User.attributs`
|
2015-05-27 19:56:39 +00:00
|
|
|
name = models.CharField(
|
|
|
|
max_length=255,
|
2015-05-27 20:56:20 +00:00
|
|
|
verbose_name=_(u"name"),
|
2016-07-29 23:31:43 +00:00
|
|
|
help_text=_(u"name of an attribute to send to the service, use * for all attributes")
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: The name of the attribute to transmit to the service. If empty, the value of :attr:`name`
|
|
|
|
#: is used.
|
2015-05-27 19:56:39 +00:00
|
|
|
replace = models.CharField(
|
|
|
|
max_length=255,
|
|
|
|
blank=True,
|
2015-05-27 20:56:20 +00:00
|
|
|
verbose_name=_(u"replace"),
|
2016-08-24 15:20:57 +00:00
|
|
|
help_text=_(u"name under which the attribute will be show "
|
2015-06-12 16:10:52 +00:00
|
|
|
u"to the service. empty = default name of the attribut")
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: ForeignKey to a :class:`ServicePattern`. :class:`ReplaceAttributName` instances for a
|
|
|
|
#: :class:`ServicePattern` are accessible thought its :attr:`ServicePattern.attributs`
|
|
|
|
#: attribute.
|
2015-05-18 18:30:00 +00:00
|
|
|
service_pattern = models.ForeignKey(ServicePattern, related_name="attributs")
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
2015-05-18 18:30:00 +00:00
|
|
|
if not self.replace:
|
|
|
|
return self.name
|
|
|
|
else:
|
|
|
|
return u"%s → %s" % (self.name, self.replace)
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
2015-05-18 18:30:00 +00:00
|
|
|
class FilterAttributValue(models.Model):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`django.db.models.Model`
|
|
|
|
|
|
|
|
A filter on :attr:`User.attributs` for a :class:`ServicePattern`. If a :class:`User` do not
|
|
|
|
have an attribute :attr:`attribut` or its value do not match :attr:`pattern`, then
|
|
|
|
:meth:`ServicePattern.check_user` will raises :class:`BadFilter` if called with that user.
|
|
|
|
"""
|
|
|
|
#: The name of a user attribute
|
2015-05-27 19:56:39 +00:00
|
|
|
attribut = models.CharField(
|
|
|
|
max_length=255,
|
2016-07-29 23:31:43 +00:00
|
|
|
verbose_name=_(u"attribute"),
|
|
|
|
help_text=_(u"Name of the attribute which must verify pattern")
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: A regular expression the attribute :attr:`attribut` value must verify. If :attr:`attribut`
|
|
|
|
#: if a list, only one of the list values needs to match.
|
2015-05-27 19:56:39 +00:00
|
|
|
pattern = models.CharField(
|
|
|
|
max_length=255,
|
2015-05-27 20:56:20 +00:00
|
|
|
verbose_name=_(u"pattern"),
|
2016-08-21 07:03:32 +00:00
|
|
|
help_text=_(u"a regular expression"),
|
|
|
|
validators=[utils.regexpr_validator]
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: ForeignKey to a :class:`ServicePattern`. :class:`FilterAttributValue` instances for a
|
|
|
|
#: :class:`ServicePattern` are accessible thought its :attr:`ServicePattern.filters`
|
|
|
|
#: attribute.
|
2015-05-18 18:30:00 +00:00
|
|
|
service_pattern = models.ForeignKey(ServicePattern, related_name="filters")
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
2015-05-18 18:30:00 +00:00
|
|
|
return u"%s %s" % (self.attribut, self.pattern)
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
2015-05-18 18:30:00 +00:00
|
|
|
class ReplaceAttributValue(models.Model):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`django.db.models.Model`
|
|
|
|
|
|
|
|
A replacement (using a regular expression) of an attribute value for a
|
|
|
|
:class:`ServicePattern`.
|
|
|
|
"""
|
|
|
|
#: Name the attribute: a key of :attr:`User.attributs`
|
2015-05-27 19:56:39 +00:00
|
|
|
attribut = models.CharField(
|
|
|
|
max_length=255,
|
2016-07-29 23:31:43 +00:00
|
|
|
verbose_name=_(u"attribute"),
|
|
|
|
help_text=_(u"Name of the attribute for which the value must be replace")
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: A regular expression matching the part of the attribute value that need to be changed
|
2015-05-27 19:56:39 +00:00
|
|
|
pattern = models.CharField(
|
|
|
|
max_length=255,
|
2015-05-27 20:56:20 +00:00
|
|
|
verbose_name=_(u"pattern"),
|
2016-08-21 07:03:32 +00:00
|
|
|
help_text=_(u"An regular expression maching whats need to be replaced"),
|
|
|
|
validators=[utils.regexpr_validator]
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: The replacement to what is mached by :attr:`pattern`. groups are capture by \\1, \\2 …
|
2015-05-27 19:56:39 +00:00
|
|
|
replace = models.CharField(
|
|
|
|
max_length=255,
|
|
|
|
blank=True,
|
2015-05-27 20:56:20 +00:00
|
|
|
verbose_name=_(u"replace"),
|
|
|
|
help_text=_(u"replace expression, groups are capture by \\1, \\2 …")
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: ForeignKey to a :class:`ServicePattern`. :class:`ReplaceAttributValue` instances for a
|
|
|
|
#: :class:`ServicePattern` are accessible thought its :attr:`ServicePattern.replacements`
|
|
|
|
#: attribute.
|
2015-05-18 18:30:00 +00:00
|
|
|
service_pattern = models.ForeignKey(ServicePattern, related_name="replacements")
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
2015-05-18 18:30:00 +00:00
|
|
|
return u"%s %s %s" % (self.attribut, self.pattern, self.replace)
|
2015-05-17 21:24:41 +00:00
|
|
|
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
2016-08-05 15:56:34 +00:00
|
|
|
class Ticket(JsonAttributes):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
2016-08-05 15:56:34 +00:00
|
|
|
Bases: :class:`JsonAttributes`
|
2016-07-20 16:28:23 +00:00
|
|
|
|
|
|
|
Generic class for a Ticket
|
|
|
|
"""
|
2015-05-16 21:43:46 +00:00
|
|
|
class Meta:
|
|
|
|
abstract = True
|
2016-07-20 16:28:23 +00:00
|
|
|
#: ForeignKey to a :class:`User`.
|
2015-05-16 21:43:46 +00:00
|
|
|
user = models.ForeignKey(User, related_name="%(class)s")
|
2016-07-20 16:28:23 +00:00
|
|
|
#: A boolean. ``True`` if the ticket has been validated
|
2015-05-16 21:43:46 +00:00
|
|
|
validate = models.BooleanField(default=False)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: The service url for the ticket
|
2015-05-16 21:43:46 +00:00
|
|
|
service = models.TextField()
|
2016-07-20 16:28:23 +00:00
|
|
|
#: ForeignKey to a :class:`ServicePattern`. The :class:`ServicePattern` corresponding to
|
|
|
|
#: :attr:`service`. Use :meth:`ServicePattern.validate` to find it.
|
2015-05-27 19:56:39 +00:00
|
|
|
service_pattern = models.ForeignKey(ServicePattern, related_name="%(class)s")
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Date of the ticket creation
|
2015-05-16 21:43:46 +00:00
|
|
|
creation = models.DateTimeField(auto_now_add=True)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: A boolean. ``True`` if the user has just renew his authentication
|
2015-05-16 21:43:46 +00:00
|
|
|
renew = models.BooleanField(default=False)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: A boolean. Set to :attr:`service_pattern` attribute
|
|
|
|
#: :attr:`ServicePattern.single_log_out` value.
|
2015-05-28 12:02:17 +00:00
|
|
|
single_log_out = models.BooleanField(default=False)
|
2015-05-16 21:43:46 +00:00
|
|
|
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Max duration between ticket creation and its validation. Any validation attempt for the
|
|
|
|
#: ticket after :attr:`creation` + VALIDITY will fail as if the ticket do not exists.
|
2015-06-08 00:51:22 +00:00
|
|
|
VALIDITY = settings.CAS_TICKET_VALIDITY
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Time we keep ticket with :attr:`single_log_out` set to ``True`` before sending SingleLogOut
|
|
|
|
#: requests.
|
2015-06-08 00:51:22 +00:00
|
|
|
TIMEOUT = settings.CAS_TICKET_TIMEOUT
|
|
|
|
|
2016-07-23 16:43:27 +00:00
|
|
|
class DoesNotExist(Exception):
|
2016-07-23 17:12:44 +00:00
|
|
|
"""raised in :meth:`Ticket.get` then ticket prefix and ticket classes mismatch"""
|
2016-07-23 16:43:27 +00:00
|
|
|
pass
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
2015-06-11 21:04:26 +00:00
|
|
|
return u"Ticket-%s" % self.pk
|
2015-05-16 21:43:46 +00:00
|
|
|
|
2016-08-05 15:56:34 +00:00
|
|
|
@staticmethod
|
|
|
|
def send_slos(queryset_list):
|
|
|
|
"""
|
|
|
|
Send SLO requests to each ticket of each queryset of ``queryset_list``
|
|
|
|
|
|
|
|
:param list queryset_list: A list a :class:`Ticket` queryset
|
|
|
|
:return: A list of possibly encoutered :class:`Exception`
|
|
|
|
:rtype: list
|
|
|
|
"""
|
|
|
|
# sending SLO to timed-out validated tickets
|
|
|
|
async_list = []
|
|
|
|
session = FuturesSession(
|
|
|
|
executor=ThreadPoolExecutor(max_workers=settings.CAS_SLO_MAX_PARALLEL_REQUESTS)
|
|
|
|
)
|
|
|
|
errors = []
|
|
|
|
for queryset in queryset_list:
|
|
|
|
for ticket in queryset:
|
|
|
|
ticket.logout(session, async_list)
|
|
|
|
queryset.delete()
|
|
|
|
for future in async_list:
|
|
|
|
if future: # pragma: no branch (should always be true)
|
|
|
|
try:
|
|
|
|
future.result()
|
|
|
|
except Exception as error:
|
|
|
|
errors.append(error)
|
|
|
|
return errors
|
|
|
|
|
2015-05-28 15:30:27 +00:00
|
|
|
@classmethod
|
2015-06-09 20:04:05 +00:00
|
|
|
def clean_old_entries(cls):
|
2015-05-28 15:30:27 +00:00
|
|
|
"""Remove old ticket and send SLO to timed-out services"""
|
|
|
|
# removing old validated ticket and non validated expired tickets
|
|
|
|
cls.objects.filter(
|
|
|
|
(
|
2015-06-12 16:10:52 +00:00
|
|
|
Q(single_log_out=False) & Q(validate=True)
|
|
|
|
) | (
|
2016-03-18 12:22:00 +00:00
|
|
|
Q(validate=False) &
|
|
|
|
Q(creation__lt=(timezone.now() - timedelta(seconds=cls.VALIDITY)))
|
2015-05-28 15:30:27 +00:00
|
|
|
)
|
|
|
|
).delete()
|
2016-06-30 11:55:19 +00:00
|
|
|
queryset = cls.objects.filter(
|
|
|
|
creation__lt=(timezone.now() - timedelta(seconds=cls.TIMEOUT))
|
|
|
|
)
|
2016-08-05 15:56:34 +00:00
|
|
|
for error in cls.send_slos([queryset]):
|
|
|
|
logger.warning("Error durring SLO %s" % error)
|
|
|
|
sys.stderr.write("%r\n" % error)
|
2015-05-28 15:30:27 +00:00
|
|
|
|
2016-06-29 18:59:18 +00:00
|
|
|
def logout(self, session, async_list=None):
|
2015-05-28 00:13:09 +00:00
|
|
|
"""Send a SLO request to the ticket service"""
|
2015-11-14 00:05:53 +00:00
|
|
|
# On logout invalidate the Ticket
|
|
|
|
self.validate = True
|
|
|
|
self.save()
|
2016-06-30 11:55:19 +00:00
|
|
|
if self.validate and self.single_log_out: # pragma: no branch (should always be true)
|
2015-12-13 12:50:29 +00:00
|
|
|
logger.info(
|
|
|
|
"Sending SLO requests to service %s for user %s" % (
|
|
|
|
self.service,
|
|
|
|
self.user.username
|
|
|
|
)
|
|
|
|
)
|
2016-08-05 15:56:34 +00:00
|
|
|
xml = utils.logout_request(self.value)
|
2016-06-29 18:51:58 +00:00
|
|
|
if self.service_pattern.single_log_out_callback:
|
|
|
|
url = self.service_pattern.single_log_out_callback
|
|
|
|
else:
|
|
|
|
url = self.service
|
|
|
|
async_list.append(
|
|
|
|
session.post(
|
|
|
|
url.encode('utf-8'),
|
|
|
|
data={'logoutRequest': xml.encode('utf-8')},
|
|
|
|
timeout=settings.CAS_SLO_TIMEOUT
|
2015-12-13 12:50:29 +00:00
|
|
|
)
|
2016-06-29 18:51:58 +00:00
|
|
|
)
|
2015-05-16 21:43:46 +00:00
|
|
|
|
2016-07-06 11:15:19 +00:00
|
|
|
@staticmethod
|
2016-07-23 16:43:27 +00:00
|
|
|
def get_class(ticket, classes=None):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Return the ticket class of ``ticket``
|
|
|
|
|
|
|
|
:param unicode ticket: A ticket
|
2016-07-23 16:43:27 +00:00
|
|
|
:param list classes: Optinal arguement. A list of possible :class:`Ticket` subclasses
|
2016-07-20 16:28:23 +00:00
|
|
|
:return: The class corresponding to ``ticket`` (:class:`ServiceTicket` or
|
2016-07-23 16:43:27 +00:00
|
|
|
:class:`ProxyTicket` or :class:`ProxyGrantingTicket`) if found among ``classes,
|
|
|
|
``None`` otherwise.
|
2016-07-20 16:28:23 +00:00
|
|
|
:rtype: :obj:`type` or :obj:`NoneType<types.NoneType>`
|
|
|
|
"""
|
2016-07-23 16:43:27 +00:00
|
|
|
if classes is None: # pragma: no cover (not used)
|
|
|
|
classes = [ServiceTicket, ProxyTicket, ProxyGrantingTicket]
|
|
|
|
for ticket_class in classes:
|
2016-07-06 11:15:19 +00:00
|
|
|
if ticket.startswith(ticket_class.PREFIX):
|
|
|
|
return ticket_class
|
|
|
|
|
2016-07-23 16:43:27 +00:00
|
|
|
def username(self):
|
|
|
|
"""
|
|
|
|
The username to send on ticket validation
|
|
|
|
|
|
|
|
:return: The value of the corresponding user attribute if
|
|
|
|
:attr:`service_pattern`.user_field is set, the user username otherwise.
|
|
|
|
"""
|
|
|
|
if self.service_pattern.user_field and self.user.attributs.get(
|
|
|
|
self.service_pattern.user_field
|
|
|
|
):
|
|
|
|
username = self.user.attributs[self.service_pattern.user_field]
|
|
|
|
if isinstance(username, list):
|
|
|
|
# the list is not empty because we wont generate a ticket with a user_field
|
|
|
|
# that evaluate to False
|
|
|
|
username = username[0]
|
|
|
|
else:
|
|
|
|
username = self.user.username
|
|
|
|
return username
|
|
|
|
|
|
|
|
def attributs_flat(self):
|
|
|
|
"""
|
|
|
|
generate attributes list for template rendering
|
|
|
|
|
|
|
|
:return: An list of (attribute name, attribute value) of all user attributes flatened
|
|
|
|
(no nested list)
|
|
|
|
:rtype: :obj:`list` of :obj:`tuple` of :obj:`unicode`
|
|
|
|
"""
|
|
|
|
attributes = []
|
|
|
|
for key, value in self.attributs.items():
|
|
|
|
if isinstance(value, list):
|
|
|
|
for elt in value:
|
|
|
|
attributes.append((key, elt))
|
|
|
|
else:
|
|
|
|
attributes.append((key, value))
|
|
|
|
return attributes
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get(cls, ticket, renew=False, service=None):
|
|
|
|
"""
|
|
|
|
Search the database for a valid ticket with provided arguments
|
|
|
|
|
|
|
|
:param unicode ticket: A ticket value
|
|
|
|
:param bool renew: Is authentication renewal needed
|
|
|
|
:param unicode service: Optional argument. The ticket service
|
|
|
|
:raises Ticket.DoesNotExist: if no class is found for the ticket prefix
|
|
|
|
:raises cls.DoesNotExist: if ``ticket`` value is not found in th database
|
|
|
|
:return: a :class:`Ticket` instance
|
|
|
|
:rtype: Ticket
|
|
|
|
"""
|
|
|
|
# If the method class is the ticket abstract class, search for the submited ticket
|
|
|
|
# class using its prefix. Assuming ticket is a ProxyTicket or a ServiceTicket
|
|
|
|
if cls == Ticket:
|
|
|
|
ticket_class = cls.get_class(ticket, classes=[ServiceTicket, ProxyTicket])
|
|
|
|
# else use the method class
|
|
|
|
else:
|
|
|
|
ticket_class = cls
|
|
|
|
# If ticket prefix is wrong, raise DoesNotExist
|
|
|
|
if cls != Ticket and not ticket.startswith(cls.PREFIX):
|
|
|
|
raise Ticket.DoesNotExist()
|
|
|
|
if ticket_class:
|
|
|
|
# search for the ticket that is not yet validated and is still valid
|
|
|
|
ticket_queryset = ticket_class.objects.filter(
|
|
|
|
value=ticket,
|
|
|
|
validate=False,
|
|
|
|
creation__gt=(timezone.now() - timedelta(seconds=ticket_class.VALIDITY))
|
|
|
|
)
|
|
|
|
# if service is specified, add it the the queryset
|
|
|
|
if service is not None:
|
|
|
|
ticket_queryset = ticket_queryset.filter(service=service)
|
|
|
|
# only require renew if renew is True, otherwise it do not matter if renew is True
|
|
|
|
# or False.
|
|
|
|
if renew:
|
|
|
|
ticket_queryset = ticket_queryset.filter(renew=True)
|
|
|
|
# fetch the ticket ``MultipleObjectsReturned`` is never raised as the ticket value
|
|
|
|
# is unique across the database
|
|
|
|
ticket = ticket_queryset.get()
|
|
|
|
# For ServiceTicket and Proxyticket, mark it as validated before returning
|
|
|
|
if ticket_class != ProxyGrantingTicket:
|
|
|
|
ticket.validate = True
|
|
|
|
ticket.save()
|
|
|
|
return ticket
|
|
|
|
# If no class found for the ticket, raise DoesNotExist
|
|
|
|
else:
|
|
|
|
raise Ticket.DoesNotExist()
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
2015-05-16 21:43:46 +00:00
|
|
|
class ServiceTicket(Ticket):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`Ticket`
|
|
|
|
|
|
|
|
A Service Ticket
|
|
|
|
"""
|
|
|
|
#: The ticket prefix used to differentiate it from other tickets types
|
2015-05-29 17:27:54 +00:00
|
|
|
PREFIX = settings.CAS_SERVICE_TICKET_PREFIX
|
2016-07-20 16:28:23 +00:00
|
|
|
#: The ticket value
|
2015-05-28 13:08:57 +00:00
|
|
|
value = models.CharField(max_length=255, default=utils.gen_st, unique=True)
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
2015-06-11 21:04:26 +00:00
|
|
|
return u"ServiceTicket-%s" % self.pk
|
2015-06-12 16:10:52 +00:00
|
|
|
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
2015-05-16 21:43:46 +00:00
|
|
|
class ProxyTicket(Ticket):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`Ticket`
|
|
|
|
|
|
|
|
A Proxy Ticket
|
|
|
|
"""
|
|
|
|
#: The ticket prefix used to differentiate it from other tickets types
|
2015-05-29 17:27:54 +00:00
|
|
|
PREFIX = settings.CAS_PROXY_TICKET_PREFIX
|
2016-07-20 16:28:23 +00:00
|
|
|
#: The ticket value
|
2015-05-28 13:08:57 +00:00
|
|
|
value = models.CharField(max_length=255, default=utils.gen_pt, unique=True)
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
2015-06-11 21:04:26 +00:00
|
|
|
return u"ProxyTicket-%s" % self.pk
|
2015-06-12 16:10:52 +00:00
|
|
|
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
2015-05-16 21:43:46 +00:00
|
|
|
class ProxyGrantingTicket(Ticket):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`Ticket`
|
|
|
|
|
|
|
|
A Proxy Granting Ticket
|
|
|
|
"""
|
|
|
|
#: The ticket prefix used to differentiate it from other tickets types
|
2015-05-29 17:27:54 +00:00
|
|
|
PREFIX = settings.CAS_PROXY_GRANTING_TICKET_PREFIX
|
2016-07-20 16:28:23 +00:00
|
|
|
#: ProxyGranting ticket are never validated. However, they can be used during :attr:`VALIDITY`
|
|
|
|
#: to get :class:`ProxyTicket` for :attr:`user`
|
2015-06-08 00:51:22 +00:00
|
|
|
VALIDITY = settings.CAS_PGT_VALIDITY
|
2016-07-20 16:28:23 +00:00
|
|
|
#: The ticket value
|
2015-05-28 13:08:57 +00:00
|
|
|
value = models.CharField(max_length=255, default=utils.gen_pgt, unique=True)
|
2015-06-08 00:51:22 +00:00
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
2015-06-11 21:04:26 +00:00
|
|
|
return u"ProxyGrantingTicket-%s" % self.pk
|
2015-05-16 21:43:46 +00:00
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
@python_2_unicode_compatible
|
2015-05-16 21:43:46 +00:00
|
|
|
class Proxy(models.Model):
|
2016-07-20 16:28:23 +00:00
|
|
|
"""
|
|
|
|
Bases: :class:`django.db.models.Model`
|
|
|
|
|
|
|
|
A list of proxies on :class:`ProxyTicket`
|
|
|
|
"""
|
2015-05-16 21:43:46 +00:00
|
|
|
class Meta:
|
|
|
|
ordering = ("-pk", )
|
2016-07-20 16:28:23 +00:00
|
|
|
#: Service url of the PGT used for getting the associated :class:`ProxyTicket`
|
2015-05-16 21:43:46 +00:00
|
|
|
url = models.CharField(max_length=255)
|
2016-07-20 16:28:23 +00:00
|
|
|
#: ForeignKey to a :class:`ProxyTicket`. :class:`Proxy` instances for a
|
|
|
|
#: :class:`ProxyTicket` are accessible thought its :attr:`ProxyTicket.proxies`
|
|
|
|
#: attribute.
|
2015-05-16 21:43:46 +00:00
|
|
|
proxy_ticket = models.ForeignKey(ProxyTicket, related_name="proxies")
|
|
|
|
|
2016-07-04 15:23:11 +00:00
|
|
|
def __str__(self):
|
2015-05-27 19:56:39 +00:00
|
|
|
return self.url
|
2016-07-29 12:33:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
class NewVersionWarning(models.Model):
|
|
|
|
"""
|
|
|
|
Bases: :class:`django.db.models.Model`
|
|
|
|
|
|
|
|
The last new version available version sent
|
|
|
|
"""
|
|
|
|
version = models.CharField(max_length=255)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def send_mails(cls):
|
|
|
|
"""
|
|
|
|
For each new django-cas-server version, if the current instance is not up to date
|
|
|
|
send one mail to ``settings.ADMINS``.
|
|
|
|
"""
|
|
|
|
if settings.CAS_NEW_VERSION_EMAIL_WARNING and settings.ADMINS:
|
|
|
|
try:
|
|
|
|
obj = cls.objects.get()
|
|
|
|
except cls.DoesNotExist:
|
|
|
|
obj = NewVersionWarning.objects.create(version=VERSION)
|
|
|
|
LAST_VERSION = utils.last_version()
|
|
|
|
if LAST_VERSION is not None and LAST_VERSION != obj.version:
|
|
|
|
if utils.decode_version(VERSION) < utils.decode_version(LAST_VERSION):
|
|
|
|
try:
|
|
|
|
send_mail(
|
|
|
|
(
|
|
|
|
'%sA new version of django-cas-server is available'
|
|
|
|
) % settings.EMAIL_SUBJECT_PREFIX,
|
|
|
|
u'''
|
|
|
|
A new version of the django-cas-server is available.
|
|
|
|
|
|
|
|
Your version: %s
|
|
|
|
New version: %s
|
|
|
|
|
|
|
|
Upgrade using:
|
|
|
|
* pip install -U django-cas-server
|
|
|
|
* fetching the last release on
|
|
|
|
https://github.com/nitmir/django-cas-server/ or on
|
|
|
|
https://pypi.python.org/pypi/django-cas-server
|
|
|
|
|
|
|
|
After upgrade, do not forget to run:
|
|
|
|
* ./manage.py migrate
|
|
|
|
* ./manage.py collectstatic
|
|
|
|
and to reload your wsgi server (apache2, uwsgi, gunicord, etc…)
|
|
|
|
|
|
|
|
--\u0020
|
|
|
|
django-cas-server
|
|
|
|
'''.strip() % (VERSION, LAST_VERSION),
|
|
|
|
settings.SERVER_EMAIL,
|
|
|
|
["%s <%s>" % admin for admin in settings.ADMINS],
|
|
|
|
fail_silently=False,
|
|
|
|
)
|
|
|
|
obj.version = LAST_VERSION
|
|
|
|
obj.save()
|
|
|
|
except smtplib.SMTPException as error: # pragma: no cover (should not happen)
|
|
|
|
logger.error("Unable to send new version mail: %s" % error)
|