models.py 12.1 KB
Newer Older
Valentin Samir's avatar
Valentin Samir committed
1
# ⁻*- coding: utf-8 -*-
Valentin Samir's avatar
Valentin Samir committed
2
3
4
5
6
7
8
9
10
11
# 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.
#
# (c) 2015 Valentin Samir
Valentin Samir's avatar
Valentin Samir committed
12
"""models for the app"""
Valentin Samir's avatar
Valentin Samir committed
13
from . import default_settings
Valentin Samir's avatar
Valentin Samir committed
14
15
16
17
18

from django.conf import settings
from django.db import models
from django.contrib import messages
from picklefield.fields import PickledObjectField
Valentin Samir's avatar
Valentin Samir committed
19
from django.utils.translation import ugettext as _
Valentin Samir's avatar
Valentin Samir committed
20
21
22
23
24
25

import re
import os
import time
import random
import string
Valentin Samir's avatar
Valentin Samir committed
26
27
28

from concurrent.futures import ThreadPoolExecutor
from requests_futures.sessions import FuturesSession
Valentin Samir's avatar
Valentin Samir committed
29

Valentin Samir's avatar
Valentin Samir committed
30
31
from . import utils

Valentin Samir's avatar
Valentin Samir committed
32
def _gen_ticket(prefix):
Valentin Samir's avatar
Valentin Samir committed
33
34
35
36
37
38
39
40
41
    """Generate a ticket with prefix `prefix`"""
    return '%s-%s' % (
        prefix,
        ''.join(
            random.choice(
                string.ascii_letters + string.digits
            ) for _ in range(settings.CAS_ST_LEN)
        )
    )
Valentin Samir's avatar
Valentin Samir committed
42
43

def _gen_st():
Valentin Samir's avatar
Valentin Samir committed
44
    """Generate a Service Ticket"""
Valentin Samir's avatar
Valentin Samir committed
45
46
47
    return _gen_ticket('ST')

def _gen_pt():
Valentin Samir's avatar
Valentin Samir committed
48
    """Generate a Proxy Ticket"""
Valentin Samir's avatar
Valentin Samir committed
49
50
51
    return _gen_ticket('PT')

def _gen_pgt():
Valentin Samir's avatar
Valentin Samir committed
52
    """Generate a Proxy Granting Ticket"""
Valentin Samir's avatar
Valentin Samir committed
53
54
    return _gen_ticket('PGT')

Valentin Samir's avatar
Valentin Samir committed
55
56
57
def gen_pgtiou():
    """Generate a Proxy Granting Ticket IOU"""
    return _gen_ticket('PGTIOU')
Valentin Samir's avatar
Valentin Samir committed
58
59

class User(models.Model):
Valentin Samir's avatar
Valentin Samir committed
60
    """A user logged into the CAS"""
Valentin Samir's avatar
Valentin Samir committed
61
62
63
64
65
66
67
68
    username = models.CharField(max_length=30, unique=True)
    attributs = PickledObjectField()
    date = models.DateTimeField(auto_now_add=True, auto_now=True)

    def __unicode__(self):
        return self.username

    def logout(self, request):
Valentin Samir's avatar
Valentin Samir committed
69
        """Sending SSO request to all services the user logged in"""
Valentin Samir's avatar
Valentin Samir committed
70
71
        async_list = []
        session = FuturesSession(executor=ThreadPoolExecutor(max_workers=10))
72
        for ticket in ServiceTicket.objects.filter(user=self, validate=True):
Valentin Samir's avatar
Valentin Samir committed
73
            async_list.append(ticket.logout(request, session))
Valentin Samir's avatar
Valentin Samir committed
74
            ticket.delete()
75
        for ticket in ProxyTicket.objects.filter(user=self, validate=True):
Valentin Samir's avatar
Valentin Samir committed
76
            async_list.append(ticket.logout(request, session))
Valentin Samir's avatar
Valentin Samir committed
77
            ticket.delete()
78
        for ticket in ProxyGrantingTicket.objects.filter(user=self, validate=True):
Valentin Samir's avatar
Valentin Samir committed
79
            async_list.append(ticket.logout(request, session))
Valentin Samir's avatar
Valentin Samir committed
80
            ticket.delete()
Valentin Samir's avatar
Valentin Samir committed
81
        for future in async_list:
82
83
84
85
86
87
88
89
90
            if future:
                try:
                    future.result()
                except Exception as error:
                    messages.add_message(
                        request,
                        messages.WARNING,
                        _(u'Error during service logout %r') % error
                    )
Valentin Samir's avatar
Valentin Samir committed
91
92
93
94
95
96
97
98
99
100
101
102
103

    def get_ticket(self, ticket_class, service, service_pattern, renew):
        """
           Generate a ticket using `ticket_class` for the service
           `service` matching `service_pattern` and asking or not for
           authentication renewal with `renew
        """
        attributs = dict(
            (a.name, a.replace if a.replace else a.name) for a in service_pattern.attributs.all()
        )
        replacements = dict(
            (a.name, (a.pattern, a.replace)) for a in service_pattern.replacements.all()
        )
Valentin Samir's avatar
Valentin Samir committed
104
        service_attributs = {}
Valentin Samir's avatar
Valentin Samir committed
105
106
107
108
109
110
111
112
113
114
115
116
        for (key, value) in self.attributs.items():
            if key in attributs:
                if key in replacements:
                    value = re.sub(replacements[key][0], replacements[key][1], value)
                service_attributs[attributs[key]] = value
        ticket = ticket_class.objects.create(
            user=self,
            attributs=service_attributs,
            service=service,
            renew=renew,
            service_pattern=service_pattern
        )
Valentin Samir's avatar
Valentin Samir committed
117
        ticket.save()
Valentin Samir's avatar
Valentin Samir committed
118
119
120
        return ticket

    def get_service_url(self, service, service_pattern, renew):
Valentin Samir's avatar
Valentin Samir committed
121
122
        """Return the url to which the user must be redirected to
        after a Service Ticket has been generated"""
Valentin Samir's avatar
Valentin Samir committed
123
        ticket = self.get_ticket(ServiceTicket, service, service_pattern, renew)
Valentin Samir's avatar
Valentin Samir committed
124
125
126
        url = utils.update_url(service, {'ticket':ticket.value})
        return url

Valentin Samir's avatar
Valentin Samir committed
127
class BadUsername(Exception):
Valentin Samir's avatar
Valentin Samir committed
128
129
    """Exception raised then an non allowed username
    try to get a ticket for a service"""
Valentin Samir's avatar
Valentin Samir committed
130
131
    pass
class BadFilter(Exception):
Valentin Samir's avatar
Valentin Samir committed
132
133
    """"Exception raised then a user try
    to get a ticket for a service and do not reach a condition"""
Valentin Samir's avatar
Valentin Samir committed
134
    pass
Valentin Samir's avatar
Valentin Samir committed
135

Valentin Samir's avatar
Valentin Samir committed
136
class UserFieldNotDefined(Exception):
Valentin Samir's avatar
Valentin Samir committed
137
138
    """Exception raised then a user try to get a ticket for a service
    using as username an attribut not present on this user"""
Valentin Samir's avatar
Valentin Samir committed
139
140
    pass
class ServicePattern(models.Model):
Valentin Samir's avatar
Valentin Samir committed
141
    """Allowed services pattern agains services are tested to"""
Valentin Samir's avatar
Valentin Samir committed
142
143
144
145
    class Meta:
        ordering = ("pos", )

    pos = models.IntegerField(default=100)
Valentin Samir's avatar
Valentin Samir committed
146
147
148
149
150
151
152
    name = models.CharField(
        max_length=255,
        unique=True,
        blank=True,
        null=True,
        help_text="Un nom pour le service"
    )
Valentin Samir's avatar
Valentin Samir committed
153
    pattern = models.CharField(max_length=255, unique=True)
Valentin Samir's avatar
Valentin Samir committed
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    user_field = models.CharField(
        max_length=255,
        default="",
        blank=True,
        help_text="Nom de l'attribut transmit comme username, vide = login"
    )
    restrict_users = models.BooleanField(
        default=False,
        help_text="Limiter les utilisateur autorisé a se connecté a ce service à celle ci-dessous"
    )
    proxy = models.BooleanField(
        default=False,
        help_text="Un ProxyGrantingTicket peut être délivré au service pour " \
        "s'authentifier en temps que l'utilisateur sur d'autres services"
    )
Valentin Samir's avatar
Valentin Samir committed
169
170
171
172
    single_sign_out = models.BooleanField(
        default=False,
        help_text="Activer le SSO sur le service"
    )
Valentin Samir's avatar
Valentin Samir committed
173
174
175
176
177

    def __unicode__(self):
        return u"%s: %s" % (self.pos, self.pattern)

    def check_user(self, user):
Valentin Samir's avatar
Valentin Samir committed
178
        """Check if `user` if allowed to use theses services"""
Valentin Samir's avatar
Valentin Samir committed
179
        if self.restrict_users and not self.usernames.filter(value=user.username):
Valentin Samir's avatar
Valentin Samir committed
180
            raise BadUsername()
Valentin Samir's avatar
Valentin Samir committed
181
182
183
        for filtre in self.filters.all():
            if isinstance(user.attributs[filtre.attribut], list):
                attrs = user.attributs[filtre.attribut]
Valentin Samir's avatar
Valentin Samir committed
184
            else:
Valentin Samir's avatar
Valentin Samir committed
185
186
187
                attrs = [user.attributs[filtre.attribut]]
            for value in attrs:
                if re.match(filtre.pattern, str(value)):
Valentin Samir's avatar
Valentin Samir committed
188
189
                    break
            else:
Valentin Samir's avatar
Valentin Samir committed
190
191
192
193
194
                raise BadFilter('%s do not match %s %s' % (
                    filtre.pattern,
                    filtre.attribut,
                    user.attributs[filtre.attribut]
                ))
Valentin Samir's avatar
Valentin Samir committed
195
196
197
198
199
200
201
        if self.user_field and not user.attributs.get(self.user_field):
            raise UserFieldNotDefined()
        return True


    @classmethod
    def validate(cls, service):
Valentin Samir's avatar
Valentin Samir committed
202
203
204
205
206
        """Check if a Service Patern match `service` and
        return it, else raise `ServicePattern.DoesNotExist`"""
        for service_pattern in cls.objects.all().order_by('pos'):
            if re.match(service_pattern.pattern, service):
                return service_pattern
Valentin Samir's avatar
Valentin Samir committed
207
208
        raise cls.DoesNotExist()

Valentin Samir's avatar
Valentin Samir committed
209
210
class Username(models.Model):
    """A list of allowed usernames on a service pattern"""
Valentin Samir's avatar
Valentin Samir committed
211
212
    value = models.CharField(max_length=255)
    service_pattern = models.ForeignKey(ServicePattern, related_name="usernames")
Valentin Samir's avatar
Valentin Samir committed
213

Valentin Samir's avatar
Valentin Samir committed
214
215
216
    def __unicode__(self):
        return self.value

Valentin Samir's avatar
Valentin Samir committed
217
class ReplaceAttributName(models.Model):
Valentin Samir's avatar
Valentin Samir committed
218
    """A list of replacement of attributs name for a service pattern"""
Valentin Samir's avatar
Valentin Samir committed
219
    class Meta:
Valentin Samir's avatar
Valentin Samir committed
220
        unique_together = ('name', 'replace', 'service_pattern')
Valentin Samir's avatar
Valentin Samir committed
221
222
223
224
225
226
227
228
229
230
    name = models.CharField(
        max_length=255,
        help_text=u"nom d'un attributs à transmettre au service"
    )
    replace = models.CharField(
        max_length=255,
        blank=True,
        help_text=u"nom sous lequel l'attribut sera présenté " \
        u"au service. vide = inchangé"
    )
Valentin Samir's avatar
Valentin Samir committed
231
232
233
234
235
236
237
238
239
    service_pattern = models.ForeignKey(ServicePattern, related_name="attributs")

    def __unicode__(self):
        if not self.replace:
            return self.name
        else:
            return u"%s → %s" % (self.name, self.replace)

class FilterAttributValue(models.Model):
Valentin Samir's avatar
Valentin Samir committed
240
241
242
243
244
245
246
247
248
    """A list of filter on attributs for a service pattern"""
    attribut = models.CharField(
        max_length=255,
        help_text=u"Nom de l'attribut devant vérifier pattern"
    )
    pattern = models.CharField(
        max_length=255,
        help_text=u"Une expression régulière"
    )
Valentin Samir's avatar
Valentin Samir committed
249
250
251
252
253
254
    service_pattern = models.ForeignKey(ServicePattern, related_name="filters")

    def __unicode__(self):
        return u"%s %s" % (self.attribut, self.pattern)

class ReplaceAttributValue(models.Model):
Valentin Samir's avatar
Valentin Samir committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    """Replacement to apply on attributs values for a service pattern"""
    attribut = models.CharField(
        max_length=255,
        help_text=u"Nom de l'attribut dont la valeur doit être modifié"
    )
    pattern = models.CharField(
        max_length=255,
        help_text=u"Une expression régulière de ce qui doit être modifié"
    )
    replace = models.CharField(
        max_length=255,
        blank=True,
        help_text=u"Par quoi le remplacer, les groupes sont capturé par \\1, \\2 …"
    )
Valentin Samir's avatar
Valentin Samir committed
269
270
271
272
    service_pattern = models.ForeignKey(ServicePattern, related_name="replacements")

    def __unicode__(self):
        return u"%s %s %s" % (self.attribut, self.pattern, self.replace)
Valentin Samir's avatar
Valentin Samir committed
273
274


Valentin Samir's avatar
Valentin Samir committed
275
class Ticket(models.Model):
Valentin Samir's avatar
Valentin Samir committed
276
    """Generic class for a Ticket"""
Valentin Samir's avatar
Valentin Samir committed
277
278
279
280
281
282
    class Meta:
        abstract = True
    user = models.ForeignKey(User, related_name="%(class)s")
    attributs = PickledObjectField()
    validate = models.BooleanField(default=False)
    service = models.TextField()
Valentin Samir's avatar
Valentin Samir committed
283
    service_pattern = models.ForeignKey(ServicePattern, related_name="%(class)s")
Valentin Samir's avatar
Valentin Samir committed
284
285
286
287
    creation = models.DateTimeField(auto_now_add=True)
    renew = models.BooleanField(default=False)

    def __unicode__(self):
Valentin Samir's avatar
Valentin Samir committed
288
        return u"Ticket(%s, %s)" % (self.user, self.service)
Valentin Samir's avatar
Valentin Samir committed
289

Valentin Samir's avatar
Valentin Samir committed
290
    def logout(self, request, session):
Valentin Samir's avatar
Valentin Samir committed
291
        """Send a SSO request to the ticket service"""
Valentin Samir's avatar
Valentin Samir committed
292
        if self.validate and self.service_pattern.single_sign_out:
Valentin Samir's avatar
Valentin Samir committed
293
294
295
296
            xml = """<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
     ID="%(id)s" Version="2.0" IssueInstant="%(datetime)s">
    <saml:NameID xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"></saml:NameID>
    <samlp:SessionIndex>%(ticket)s</samlp:SessionIndex>
Valentin Samir's avatar
Valentin Samir committed
297
298
299
300
301
302
  </samlp:LogoutRequest>""" % \
            {
                'id' : os.urandom(20).encode("hex"),
                'datetime' : int(time.time()),
                'ticket': self.value
            }
Valentin Samir's avatar
Valentin Samir committed
303
304
            headers = {'Content-Type': 'text/xml'}
            try:
Valentin Samir's avatar
Valentin Samir committed
305
306
307
308
309
310
311
312
313
314
315
316
                return session.post(
                    self.service.encode('utf-8'),
                    data=xml.encode('utf-8'),
                    headers=headers
                )
            except Exception as error:
                messages.add_message(
                    request,
                    messages.WARNING,
                    _(u'Error during service logout %(service)s:\n%(error)s') %
                    {'service': self.service, 'error':error}
                )
Valentin Samir's avatar
Valentin Samir committed
317
318

class ServiceTicket(Ticket):
Valentin Samir's avatar
Valentin Samir committed
319
    """A Service Ticket"""
Valentin Samir's avatar
Valentin Samir committed
320
    value = models.CharField(max_length=255, default=_gen_st, unique=True)
Valentin Samir's avatar
Valentin Samir committed
321
322
    def __unicode__(self):
        return u"ServiceTicket(%s, %s, %s)" % (self.user, self.value, self.service)
Valentin Samir's avatar
Valentin Samir committed
323
class ProxyTicket(Ticket):
Valentin Samir's avatar
Valentin Samir committed
324
    """A Proxy Ticket"""
Valentin Samir's avatar
Valentin Samir committed
325
    value = models.CharField(max_length=255, default=_gen_pt, unique=True)
Valentin Samir's avatar
Valentin Samir committed
326
327
    def __unicode__(self):
        return u"ProxyTicket(%s, %s, %s)" % (self.user, self.value, self.service)
Valentin Samir's avatar
Valentin Samir committed
328
class ProxyGrantingTicket(Ticket):
Valentin Samir's avatar
Valentin Samir committed
329
    """A Proxy Granting Ticket"""
Valentin Samir's avatar
Valentin Samir committed
330
    value = models.CharField(max_length=255, default=_gen_pgt, unique=True)
Valentin Samir's avatar
Valentin Samir committed
331
332
    def __unicode__(self):
        return u"ProxyGrantingTicket(%s, %s, %s)" % (self.user, self.value, self.service)
Valentin Samir's avatar
Valentin Samir committed
333
334

class Proxy(models.Model):
Valentin Samir's avatar
Valentin Samir committed
335
    """A list of proxies on `ProxyTicket`"""
Valentin Samir's avatar
Valentin Samir committed
336
337
338
339
340
    class Meta:
        ordering = ("-pk", )
    url = models.CharField(max_length=255)
    proxy_ticket = models.ForeignKey(ProxyTicket, related_name="proxies")

Valentin Samir's avatar
Valentin Samir committed
341
342
343
    def __unicode__(self):
        return self.url