aboutsummaryrefslogtreecommitdiff
path: root/app/dispatch/middleware.py
blob: a3b9ec6cc6ec3727dc4f4c52050c286602597b92 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from django.http import HttpResponseRedirect
from django.conf import settings
import re
from django.core.urlresolvers import reverse, reverse_lazy

EXEMPT_URLS = [
        reverse('login'),
        reverse('logout'),
    ]
EXEMPT_REGEX = re.compile('^/accounts/.*$')

if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URLS += settings.LOGIN_EXEMPT_URLS

"""
Middleware that requires a user to be authenticated to view any page other
than LOGIN_URL. Exemptions to this requirement can optionally be specified
in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
you can copy from your urls.py).

Requires authentication middleware and template context processors to be
loaded. You'll get an error if they aren't.
"""
class LoginRequiredMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if not request.user or not request.user.is_authenticated():
            path = request.path_info
            # Check for any regex matches
            reg = EXEMPT_REGEX.match(path)

            if path not in EXEMPT_URLS and reg is None:
                login_uri = '%s?next=%s' % (settings.LOGIN_URL, request.path_info)
                return HttpResponseRedirect(login_uri)
        else:
            # I don't really like this but I don't really see a better 
            # way of checking for this
            try: 
                identity = request.user.identity
            except:
                allowed_paths  = [ reverse('identity_create', kwargs={'user_id': request.user.pk}) ]
                allowed_paths.extend(EXEMPT_URLS)
                print(allowed_paths)
                if request.path_info not in allowed_paths:
                    return HttpResponseRedirect(allowed_paths[0])

        return self.get_response(request)