Projet

Général

Profil

Télécharger (6,5 ko) Statistiques
| Branche: | Tag: | Révision:

mandayejs / mandayejs / mandaye / views.py @ 7ab17a37

1
# mandayejs - saml reverse proxy
2
# Copyright (C) 2015  Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

    
17
from __future__ import absolute_import
18

    
19
import os
20
import json
21
import logging
22
import urlparse
23
import urllib
24

    
25
from django.conf import settings
26
from django.contrib.auth import views as auth_views
27
from django.contrib.auth import logout as auth_logout
28
from django.contrib.auth.models import User
29
from django.contrib.auth.decorators import login_required
30
from django.contrib import messages
31
from django.forms import PasswordInput
32
from django.forms import models as model_forms
33
from django.http import HttpResponseRedirect, HttpResponse
34
from django.shortcuts import get_object_or_404, render, resolve_url
35
from django.template import RequestContext
36
from django.views.generic.base import TemplateView
37
from django.views.decorators.csrf import csrf_exempt
38
from django.db import IntegrityError
39
from django.utils.translation import ugettext_lazy as _
40
from django.template import RequestContext, Template
41

    
42
from .models import UserCredentials
43
from mandayejs.mandaye.forms import FormFactory
44
from mandayejs.mandaye.utils import exec_phantom, cookie_builder, get_location
45

    
46
logger = logging.getLogger(__name__)
47

    
48
def login(request, *args, **kwargs):
49
    return auth_views.login(request, *args, **kwargs)
50

    
51
def logout(request, *args, **kwargs):
52
    auth_logout(request)
53
    return HttpResponseRedirect('/')
54

    
55

    
56
class Panel(TemplateView):
57
    template_name = 'mandaye/panel.html'
58

    
59
    def get_context_data(self, **kwargs):
60
        context = super(Panel, self).get_context_data(**kwargs)
61
        scripts = getattr(settings, 'SITE_SCRIPTS', [])
62
        static_root_path = getattr(settings, 'SITE_STATIC_ROOT_PATH', '')
63
        context['site_scripts'] = [os.path.join(static_root_path, s) for s in scripts]
64
        context['ca_url'] = getattr(settings, 'SITE_CA_URL', '/')
65
        context['is_linked'] = self.is_account_linked()
66
        return context
67

    
68
    def is_account_linked(self):
69
        """Check if user account is associated
70
        """
71
        try:
72
            user = User.objects.get(username=self.request.user.username)
73
            return user.usercredentials_set.get().linked
74
        except (User.DoesNotExist, UserCredentials.DoesNotExist) as e:
75
            return False
76

    
77

    
78
panel = Panel.as_view()
79

    
80
@login_required
81
def post_login(request, *args, **kwargs):
82
    try:
83
        user = User.objects.get(username=request.user.username)
84
        logger.debug(user)
85
        credentials = UserCredentials.objects.get(
86
                user=user)
87
        logger.debug(credentials)
88
    except (UserCredentials.DoesNotExist,):
89
        return HttpResponseRedirect(resolve_url('associate'))
90

    
91
    context = {}
92
    context['address'] = getattr(settings, 'SITE_HOME_PATH', '/')
93
    return render(request, 'mandaye/post-login.html', context)
94

    
95
@login_required
96
@csrf_exempt
97
def associate(request, *args, **kwargs):
98
    if request.method == 'POST':
99

    
100
        form = FormFactory(request.POST)
101
        if form.is_valid():
102
            credentials, created = UserCredentials.objects.get_or_create(user=request.user)
103
            credentials.locators = form.cleaned_data
104
            credentials.linked = False
105
            credentials.save()        
106

    
107
            return HttpResponseRedirect(resolve_url('post-login'))
108
    else :
109
        form = FormFactory()
110

    
111
    site_static_root = getattr(settings, 'SITE_STATIC_ROOT_PATH', '')
112
    associate_static = getattr(settings, 'SITE_ASSOCIATE_STATIC',
113
                           {'css':'', 'js':''})
114

    
115
    response = render(request, 'mandaye/associate.html', {
116
        'form': form,
117
        'associate_js': os.path.join(site_static_root, associate_static['js']),
118
        'associate_css': os.path.join(site_static_root, associate_static['css'])        
119
    })
120
    return response
121

    
122

    
123
@login_required
124
def dissociate(request, *args, **kwargs):
125
    try:
126
        c_user = UserCredentials.objects.get(
127
                user__username=request.user.username)
128
        c_user.delete()
129
        logger.debug("{} dissacioted".format(c_user.user.username))
130
        response = HttpResponseRedirect('/')
131
        for cookie_key in getattr(settings, 'SITE_AUTH_COOKIE_KEYS', []):
132
            response.delete_cookie(cookie_key)
133
            logger.debug("cookie {} deleted".format(cookie_key))
134
        return response 
135
    except (UserCredentials.DoesNotExist,):
136
        return HttpResponseRedirect(resolve_url('associate'))
137

    
138
@login_required
139
def post_login_do(request, *args, **kwargs):
140
    user = User.objects.get(username=request.user.username)
141
    try:
142
        credentials = user.usercredentials_set.get()
143
    except (UserCredentials.DoesNotExist,):
144
        return HttpResponseRedirect(resolve_url('associate'))
145

    
146
    site_static_root = os.path.join(getattr(settings, 'STATIC_ROOT'), getattr(settings, 'SITE_STATIC_ROOT_PATH', ''))
147
    site_auth_checker = getattr(settings, 'SITE_AUTH_CHECKER', '')
148
    login_info = {
149
        'address': request.build_absolute_uri(settings.SITE_LOGIN_PATH),
150
        'cookies': [],
151
        'locators': [ credentials.to_login_info() ],
152
        'homepath': getattr(settings, 'SITE_HOME_PATH', '/'),
153
        'auth_checker': os.path.join(site_static_root, site_auth_checker)
154
    }
155
    logger.debug(login_info)
156
    result = exec_phantom(login_info)
157
    logger.debug(result)
158

    
159
    if result.get('result') != 'ok':
160
        logger.debug('authentication failed')
161
        logger.debug("redirecting to {}".format(resolve_url('associate')))
162
        credentials.delete()
163
        messages.error(request, _('wrong user credentials'))
164
        url = resolve_url('associate')
165
    else:
166
        credentials.linked = True
167
        credentials.save()
168
        url = getattr(settings, 'SITE_HOME_PATH', '/')
169

    
170
    template = Template('<script type="text/javascript">\
171
                window.top.location = "{{url}}";</script>')
172
    context = RequestContext(request, {'url': url})
173
    response = HttpResponse(template.render(context))
174
    if result.get('headers',None):
175
        response.cookies = cookie_builder(result.get('headers'))
176

    
177
    return response
(6-6/6)