Projet

Général

Profil

« Précédent | Suivant » 

Révision cb28f217

Ajouté par Josué Kouka il y a environ 6 ans

change app settings module structure (#22037)

Voir les différences:

mandayejs/applications.py
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 unicode_literals
18

  
19
import os
20
from importlib import import_module
21

  
22
from django.conf import settings
23
from django.conf.urls import patterns, url
24
from django.http import Http404
25
from django.core.exceptions import ImproperlyConfigured
26
from django.core.urlresolvers import resolve
27
from django.utils.text import slugify
28

  
29

  
30
def get_app_settings():
31
    module_name, app_settings = tuple(settings.SITE_APP.rsplit('.', 1))
32
    module = import_module(module_name)
33
    return getattr(module, app_settings)()
34

  
35

  
36
def app_web_services(request, path):
37
    app = get_app_settings()
38
    if hasattr(app, 'urlpatterns'):
39
        view, args, kwargs = resolve(request.path, urlconf=app)
40
        return view(request, *args, **kwargs)
41
    raise Http404
42

  
43

  
44
# App Settings
45
class AppSettingsMeta(type):
46

  
47
    REQUIRED_KEYS = [
48
        'SITE_LOGIN_PATH',
49
        'SITE_LOCATORS',
50
        'SITE_AUTH_CHECKER',
51
        'SITE_AUTH_COOKIE_KEYS',
52
    ]
53

  
54
    def __new__(cls, name, bases, dct):
55
        if name != 'AppSettings':
56
            if AppSettings in bases:  # Avoid checking keys for inherited classes
57

  
58
                missing_key = set(cls.REQUIRED_KEYS).difference(set(dct.keys())) or None
59
                if missing_key:
60
                    raise ImproperlyConfigured('{} is mandatory'.format(missing_key.pop()))
61

  
62
                if not set(('SITE_FORCE_REDIRECT_URL', 'SITE_FORCE_REDIRECT_LOCATOR')).intersection(set(dct.keys())):
63
                    raise ImproperlyConfigured(
64
                        'one of these settings ({}) must be defined'
65
                        .format(('SITE_FORCE_REDIRECT_URL', 'SITE_FORCE_REDIRECT_LOCATOR')))
66

  
67
                # Default form submit element
68
                if not dct.get('SITE_FORM_SUBMIT_ELEMENT', None):
69
                    dct['SITE_FORM_SUBMIT_ELEMENT'] = 'input[type=submit], button'
70

  
71
        return super(AppSettingsMeta, cls).__new__(cls, name, bases, dct)
72

  
73

  
74
class AppSettings(object):
75
    __metaclass__ = AppSettingsMeta
76

  
77
    def __getattribute__(self, name):
78
        value = getattr(settings, name, None)
79
        if value is not None:
80
            return value
81
        return super(AppSettings, self).__getattribute__(name)
82

  
83
    def get_name(self):
84
        name = getattr(settings, 'SITE_APP_NAME', None)
85
        if name:
86
            return name
87
        return type(self).__name__
88

  
89
    def get_slug(self):
90
        return slugify(type(self).__name__)
91

  
92

  
93
# Test App Settings
94
class Test(AppSettings):
95
    SITE_LOGIN_PATH = '/'
96
    SITE_LOCATORS = [
97
        {
98
            'id': '#login',
99
            'label': 'Login',
100
            'name': 'login',
101
            'kind': 'string',
102
        },
103
        {
104
            'id': '#password',
105
            'label': 'Password',
106
            'name': 'password',
107
            'kind': 'password'
108
        }
109
    ]
110
    SITE_AUTH_CHECKER = 'js/test/auth.checker.js'
111
    SITE_AUTH_COOKIE_KEYS = ['test']
112
    SITE_FORCE_REDIRECT_URL = '/whatever'
113

  
114

  
115
# Duonet App Settings
116
class Duonet(AppSettings):
117
    SITE_LOGIN_PATH = '/'
118
    SITE_LOCATORS = [
119
        {
120
            'id': '#txtNomFoyer',
121
            'label': 'Nom de famille',
122
            'name': 'txtNomFoyer',
123
            'kind': 'string',
124
            'required': True,
125
            'help': '',
126
        },
127
        {
128
            'id': '#txtDateNaissance',
129
            'label': 'Date de naissance',
130
            'name': 'txtDateNaissance',
131
            'kind': 'date',
132
            'required': True,
133
            'help': 'exemple 16/06/2008'
134
        },
135
        {
136
            'id': '#txtCode',
137
            'label': 'Mot de passe',
138
            'name': 'txtCode',
139
            'kind': 'password',
140
            'required': True,
141
            'help': ''
142
        },
143
    ]
144
    SITE_AUTH_CHECKER = 'duonet/js/auth.checker.js'
145
    SITE_AUTH_COOKIE_KEYS = [
146
        'ASP.NET_SessionId',
147
    ]
148
    SITE_APP_SCRIPTS = [
149
        'duonet/js/duonet.js',
150
    ]
151

  
152
    SITE_FORCE_REDIRECT_URL = '/Connect.aspx'
153

  
154
    SITE_FORM_SUBMIT_ELEMENT = 'input[type=submit]'
155

  
156
    SITE_LOGOUT_LOCATOR = '#lnkDisconnect'
157

  
158

  
159
# Archimed App Settings
160
class Archimed(AppSettings):
161
    SITE_LOGIN_PATH = '/'
162
    SITE_LOCATORS = [
163
        {
164
            'id': '#carte',
165
            'label': 'Identifiant',
166
            'name': 'carte',
167
            'kind': 'string',
168
            'required': True,
169
            'help': '',
170
        },
171
        {
172
            'id': '#code',
173
            'label': 'Mot de passe',
174
            'name': 'code',
175
            'kind': 'password',
176
            'required': True,
177
            'help': ''
178
        },
179
    ]
180
    SITE_AUTH_CHECKER = 'archimed/js/auth.checker.js'
181
    SITE_AUTH_COOKIE_KEYS = [
182
        'S_ARCHIMED_CRYSTAL_AUTH'
183
    ]
184

  
185
    SITE_APP_SCRIPTS = [
186
        'archimed/js/archimed.js'
187
    ]
188

  
189
    SITE_FORCE_REDIRECT_LOCATOR = '.connectBox'
190

  
191
    SITE_WS_ENDPOINT = {
192
        'account_details': '/DEFAULT/Ermes/Services/ILSClient.svc/RetrieveAccount',
193
    }
194

  
195
    urlpatterns = patterns(
196
        '',
197
        url(
198
            r'account/(?P<username>\w+)/$',
199
            'mandayejs.views.archimed_account_details',
200
            name='archimed-account-details'),
201
    )
202

  
203
    SITE_LOGOUT_LOCATOR = '.account_logoff'
204

  
205

  
206
# Arpege App Settings
207
class Arpege(AppSettings):
208
    SITE_LOGIN_PATH = '/index.do'
209
    SITE_LOCATORS = [
210
        {
211
            'id': '#cdfmll',
212
            'label': 'Code famille',
213
            'name': 'cdfmll',
214
            'kind': 'string',
215
            'required': True,
216
            'help': '',
217
        },
218
        {
219
            'id': '#mtdpss',
220
            'label': 'Mot de passe',
221
            'name': 'mtdpss',
222
            'kind': 'password',
223
            'required': True,
224
            'help': '',
225
        }
226
    ]
227
    SITE_AUTH_CHECKER = 'arpege/js/auth.checker.js'
228
    SITE_AUTH_COOKIE_KEYS = [
229
        'JSESSIONID',
230
    ]
231

  
232
    SITE_APP_SCRIPTS = [
233
        'arpege/js/arpege.js',
234
    ]
235

  
236
    SITE_FORCE_REDIRECT_LOCATOR = '.formulaire'
237

  
238
    SITE_LOGOUT_LOCATOR = '#espace-login form input[type=submit]'
239

  
240

  
241
class Imuse(AppSettings):
242
    SITE_LOGIN_PATH = 'extranet/login/gen_index_groupe.php?nav=autre'
243

  
244
    SITE_LOCATORS = [
245
        {
246
            'id': '#INDEX_USER_ID',
247
            'label': 'Identifiant',
248
            'name': 'INDEX_USER_ID',
249
            'kind': 'string',
250
            'required': True,
251
            'help': ''
252
        },
253
        {
254
            'id': '#INDEX_USER_PWD',
255
            'label': 'Mot de passe',
256
            'name': 'INDEX_USER_PWD',
257
            'kind': 'password',
258
            'required': True,
259
            'help': ''
260
        }
261
    ]
262

  
263
    SITE_AUTH_CHECKER = 'imuse/js/auth.checker.js'
264

  
265
    SITE_AUTH_COOKIE_KEYS = [
266
        'iMuse-extranet'
267
    ]
268

  
269
    SITE_FORCE_REDIRECT_LOCATOR = '#INDEX_TBL_LOGIN'
270

  
271
    SITE_FORM_SUBMIT_ELEMENT = '#INDEX_BT_LOGIN'
272

  
273

  
274
class Sezhame(AppSettings):
275
    SITE_LOGIN_PATH = '/sezhame/page/connexion-abonne?destination=user'
276

  
277
    SITE_LOCATORS = [
278
        {
279
            'id': '#edit-user',
280
            'label': 'Numero de cqrte',
281
            'name': 'edit-user',
282
            'kind': 'string',
283
            'required': True,
284
            'help': ''
285
        },
286
        {
287
            'id': '#edit-password',
288
            'label': 'Mot de passe',
289
            'name': 'edit-password',
290
            'kind': 'password',
291
            'required': True,
292
            'help': ''
293
        }
294
    ]
295

  
296
    SITE_AUTH_CHECKER = 'sezhame/js/auth.checker.js'
297

  
298
    SITE_AUTH_COOKIE_KEYS = [
299
        'SESSf36da25307ad6240a58ddd4f4b138952',
300
        'ASPSESSIONIDQSDRASTR'
301
    ]
302

  
303
    SITE_FORCE_REDIRECT_LOCATOR = '#dk-opac15-login-form'
304

  
305

  
306
class Teamnet(AppSettings):
307
    SITE_LOGIN_PATH = '/auth/teamnetauth'
308

  
309
    SITE_LOCATORS = [
310
        {
311
            'id': '#login',
312
            'label': 'Mon identifiant',
313
            'name': 'login',
314
            'kind': 'string',
315
            'required': True,
316
            'help': ''
317
        },
318
        {
319
            'id': '#mdp',
320
            'label': 'Mon mot de passe',
321
            'name': 'mdp',
322
            'kind': 'password',
323
            'required': True,
324
            'help': ''
325
        }
326
    ]
327

  
328
    SITE_FORM_SUBMIT_ELEMENT = "input[type=submit][value='Me connecter']"
329

  
330
    SITE_AUTH_CHECKER = 'teamnet/js/auth.checker.js'
331

  
332
    SITE_AUTH_COOKIE_KEYS = [
333
        'JSESSIONID',
334
    ]
335

  
336
    SITE_FORCE_REDIRECT_LOCATOR = '#loginForm'
337

  
338
    SITE_LOGOUT_LOCATOR = ".infoUtilisateur[alt=Deconnexion]"
mandayejs/applications/__init__.py
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 unicode_literals
18

  
19
import os
20
from importlib import import_module
21

  
22
from django.conf import settings
23
from django.conf.urls import patterns, url
24
from django.http import Http404
25
from django.core.exceptions import ImproperlyConfigured
26
from django.core.urlresolvers import resolve
27
from django.utils.text import slugify
28

  
29

  
30
def get_app_settings():
31
    module_name, app_settings = tuple(settings.SITE_APP.rsplit('.', 1))
32
    module = import_module(module_name)
33
    return getattr(module, app_settings)()
34

  
35

  
36
def app_web_services(request, path):
37
    app = get_app_settings()
38
    if hasattr(app, 'urlpatterns'):
39
        view, args, kwargs = resolve(request.path, urlconf=app)
40
        return view(request, *args, **kwargs)
41
    raise Http404
42

  
43

  
44
# App Settings
45
class AppSettingsMeta(type):
46

  
47
    REQUIRED_KEYS = [
48
        'SITE_LOGIN_PATH',
49
        'SITE_LOCATORS',
50
        'SITE_AUTH_CHECKER',
51
        'SITE_AUTH_COOKIE_KEYS',
52
    ]
53

  
54
    def __new__(cls, name, bases, dct):
55
        if name != 'AppSettings':
56
            if AppSettings in bases:  # Avoid checking keys for inherited classes
57

  
58
                missing_key = set(cls.REQUIRED_KEYS).difference(set(dct.keys())) or None
59
                if missing_key:
60
                    raise ImproperlyConfigured('{} is mandatory'.format(missing_key.pop()))
61

  
62
                if not set(('SITE_FORCE_REDIRECT_URL', 'SITE_FORCE_REDIRECT_LOCATOR')).intersection(set(dct.keys())):
63
                    raise ImproperlyConfigured(
64
                        'one of these settings ({}) must be defined'
65
                        .format(('SITE_FORCE_REDIRECT_URL', 'SITE_FORCE_REDIRECT_LOCATOR')))
66

  
67
                # Default form submit element
68
                if not dct.get('SITE_FORM_SUBMIT_ELEMENT', None):
69
                    dct['SITE_FORM_SUBMIT_ELEMENT'] = 'input[type=submit], button'
70

  
71
        return super(AppSettingsMeta, cls).__new__(cls, name, bases, dct)
72

  
73

  
74
class AppSettings(object):
75
    __metaclass__ = AppSettingsMeta
76

  
77
    def __getattribute__(self, name):
78
        value = getattr(settings, name, None)
79
        if value is not None:
80
            return value
81
        return super(AppSettings, self).__getattribute__(name)
82

  
83
    def get_name(self):
84
        name = getattr(settings, 'SITE_APP_NAME', None)
85
        if name:
86
            return name
87
        return type(self).__name__
88

  
89
    def get_slug(self):
90
        return slugify(type(self).__name__)
91

  
92

  
93
# Test App Settings
94
class Test(AppSettings):
95
    SITE_LOGIN_PATH = '/'
96
    SITE_LOCATORS = [
97
        {
98
            'id': '#login',
99
            'label': 'Login',
100
            'name': 'login',
101
            'kind': 'string',
102
        },
103
        {
104
            'id': '#password',
105
            'label': 'Password',
106
            'name': 'password',
107
            'kind': 'password'
108
        }
109
    ]
110
    SITE_AUTH_CHECKER = 'js/test/auth.checker.js'
111
    SITE_AUTH_COOKIE_KEYS = ['test']
112
    SITE_FORCE_REDIRECT_URL = '/whatever'
113

  
114

  
115
# Duonet App Settings
116
class Duonet(AppSettings):
117
    SITE_LOGIN_PATH = '/'
118
    SITE_LOCATORS = [
119
        {
120
            'id': '#txtNomFoyer',
121
            'label': 'Nom de famille',
122
            'name': 'txtNomFoyer',
123
            'kind': 'string',
124
            'required': True,
125
            'help': '',
126
        },
127
        {
128
            'id': '#txtDateNaissance',
129
            'label': 'Date de naissance',
130
            'name': 'txtDateNaissance',
131
            'kind': 'date',
132
            'required': True,
133
            'help': 'exemple 16/06/2008'
134
        },
135
        {
136
            'id': '#txtCode',
137
            'label': 'Mot de passe',
138
            'name': 'txtCode',
139
            'kind': 'password',
140
            'required': True,
141
            'help': ''
142
        },
143
    ]
144
    SITE_AUTH_CHECKER = 'duonet/js/auth.checker.js'
145
    SITE_AUTH_COOKIE_KEYS = [
146
        'ASP.NET_SessionId',
147
    ]
148
    SITE_APP_SCRIPTS = [
149
        'duonet/js/duonet.js',
150
    ]
151

  
152
    SITE_FORCE_REDIRECT_URL = '/Connect.aspx'
153

  
154
    SITE_FORM_SUBMIT_ELEMENT = 'input[type=submit]'
155

  
156
    SITE_LOGOUT_LOCATOR = '#lnkDisconnect'
157

  
158

  
159
# Archimed App Settings
160
class Archimed(AppSettings):
161
    SITE_LOGIN_PATH = '/'
162
    SITE_LOCATORS = [
163
        {
164
            'id': '#carte',
165
            'label': 'Identifiant',
166
            'name': 'carte',
167
            'kind': 'string',
168
            'required': True,
169
            'help': '',
170
        },
171
        {
172
            'id': '#code',
173
            'label': 'Mot de passe',
174
            'name': 'code',
175
            'kind': 'password',
176
            'required': True,
177
            'help': ''
178
        },
179
    ]
180
    SITE_AUTH_CHECKER = 'archimed/js/auth.checker.js'
181
    SITE_AUTH_COOKIE_KEYS = [
182
        'S_ARCHIMED_CRYSTAL_AUTH'
183
    ]
184

  
185
    SITE_APP_SCRIPTS = [
186
        'archimed/js/archimed.js'
187
    ]
188

  
189
    SITE_FORCE_REDIRECT_LOCATOR = '.connectBox'
190

  
191
    SITE_WS_ENDPOINT = {
192
        'account_details': '/DEFAULT/Ermes/Services/ILSClient.svc/RetrieveAccount',
193
    }
194

  
195
    urlpatterns = patterns(
196
        '',
197
        url(
198
            r'account/(?P<username>\w+)/$',
199
            'mandayejs.applications.views.archimed_account_details',
200
            name='archimed-account-details'),
201
    )
202

  
203
    SITE_LOGOUT_LOCATOR = '.account_logoff'
204

  
205

  
206
# Arpege App Settings
207
class Arpege(AppSettings):
208
    SITE_LOGIN_PATH = '/index.do'
209
    SITE_LOCATORS = [
210
        {
211
            'id': '#cdfmll',
212
            'label': 'Code famille',
213
            'name': 'cdfmll',
214
            'kind': 'string',
215
            'required': True,
216
            'help': '',
217
        },
218
        {
219
            'id': '#mtdpss',
220
            'label': 'Mot de passe',
221
            'name': 'mtdpss',
222
            'kind': 'password',
223
            'required': True,
224
            'help': '',
225
        }
226
    ]
227
    SITE_AUTH_CHECKER = 'arpege/js/auth.checker.js'
228
    SITE_AUTH_COOKIE_KEYS = [
229
        'JSESSIONID',
230
    ]
231

  
232
    SITE_APP_SCRIPTS = [
233
        'arpege/js/arpege.js',
234
    ]
235

  
236
    SITE_FORCE_REDIRECT_LOCATOR = '.formulaire'
237

  
238
    SITE_LOGOUT_LOCATOR = '#espace-login form input[type=submit]'
239

  
240

  
241
class Imuse(AppSettings):
242
    SITE_LOGIN_PATH = 'extranet/login/gen_index_groupe.php?nav=autre'
243

  
244
    SITE_LOCATORS = [
245
        {
246
            'id': '#INDEX_USER_ID',
247
            'label': 'Identifiant',
248
            'name': 'INDEX_USER_ID',
249
            'kind': 'string',
250
            'required': True,
251
            'help': ''
252
        },
253
        {
254
            'id': '#INDEX_USER_PWD',
255
            'label': 'Mot de passe',
256
            'name': 'INDEX_USER_PWD',
257
            'kind': 'password',
258
            'required': True,
259
            'help': ''
260
        }
261
    ]
262

  
263
    SITE_AUTH_CHECKER = 'imuse/js/auth.checker.js'
264

  
265
    SITE_AUTH_COOKIE_KEYS = [
266
        'iMuse-extranet'
267
    ]
268

  
269
    SITE_FORCE_REDIRECT_LOCATOR = '#INDEX_TBL_LOGIN'
270

  
271
    SITE_FORM_SUBMIT_ELEMENT = '#INDEX_BT_LOGIN'
272

  
273

  
274
class Sezhame(AppSettings):
275
    SITE_LOGIN_PATH = '/sezhame/page/connexion-abonne?destination=user'
276

  
277
    SITE_LOCATORS = [
278
        {
279
            'id': '#edit-user',
280
            'label': 'Numero de cqrte',
281
            'name': 'edit-user',
282
            'kind': 'string',
283
            'required': True,
284
            'help': ''
285
        },
286
        {
287
            'id': '#edit-password',
288
            'label': 'Mot de passe',
289
            'name': 'edit-password',
290
            'kind': 'password',
291
            'required': True,
292
            'help': ''
293
        }
294
    ]
295

  
296
    SITE_AUTH_CHECKER = 'sezhame/js/auth.checker.js'
297

  
298
    SITE_AUTH_COOKIE_KEYS = [
299
        'SESSf36da25307ad6240a58ddd4f4b138952',
300
        'ASPSESSIONIDQSDRASTR'
301
    ]
302

  
303
    SITE_FORCE_REDIRECT_LOCATOR = '#dk-opac15-login-form'
304

  
305

  
306
class Teamnet(AppSettings):
307
    SITE_LOGIN_PATH = '/auth/teamnetauth'
308

  
309
    SITE_LOCATORS = [
310
        {
311
            'id': '#login',
312
            'label': 'Mon identifiant',
313
            'name': 'login',
314
            'kind': 'string',
315
            'required': True,
316
            'help': ''
317
        },
318
        {
319
            'id': '#mdp',
320
            'label': 'Mon mot de passe',
321
            'name': 'mdp',
322
            'kind': 'password',
323
            'required': True,
324
            'help': ''
325
        }
326
    ]
327

  
328
    SITE_FORM_SUBMIT_ELEMENT = "input[type=submit][value='Me connecter']"
329

  
330
    SITE_AUTH_CHECKER = 'teamnet/js/auth.checker.js'
331

  
332
    SITE_AUTH_COOKIE_KEYS = [
333
        'JSESSIONID',
334
    ]
335

  
336
    SITE_FORCE_REDIRECT_LOCATOR = '#loginForm'
337

  
338
    SITE_LOGOUT_LOCATOR = ".infoUtilisateur[alt=Deconnexion]"
mandayejs/applications/views.py
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 logging
20
import requests
21

  
22
from django.contrib.auth.models import User
23
from rest_framework import status
24
from rest_framework.views import APIView
25
from rest_framework.response import Response
26

  
27
from mandayejs.mandaye.models import UserCredentials
28
from mandayejs.applications import get_app_settings
29

  
30

  
31
class ArchimedAccountDetails(APIView):
32
    """Archimed user's account details
33
    """
34

  
35
    def dispatch(self, request, *args, **kwargs):
36
        response = super(ArchimedAccountDetails, self).dispatch(request, *args, **kwargs)
37
        if response.status_code == 200:
38
            response.data = {'data': response.data, 'err': 0}
39
        else:
40
            response.data = {'data': None, 'err': 1, 'err_desc': response.data}
41
        return response
42

  
43
    def get(self, request, *args, **kwargs):
44
        logger = logging.getLogger(__name__)
45
        app_settings = get_app_settings()
46
        ws_uri = request.build_absolute_uri(
47
            app_settings.SITE_WS_ENDPOINT['account_details'])
48

  
49
        # mellon truncates username to 30 characters
50
        # thus the passed username must be truncated to 30 characters
51
        # for searching purpose.
52
        username = kwargs['username'][:30]
53

  
54
        try:
55
            user = User.objects.get(username=username)
56
        except (User.DoesNotExist,):
57
            return Response('User %s does not exist' % username, status=status.HTTP_404_NOT_FOUND)
58

  
59
        try:
60
            credentials = UserCredentials.objects.get(user=user)
61
        except (UserCredentials.DoesNotExist,):
62
            return Response('User %s is not associated' % username, status=status.HTTP_404_NOT_FOUND)
63

  
64
        login_url = request.build_absolute_uri(
65
            '/DEFAULT/Ermes/Recherche/logon.svc/logon')
66

  
67
        with requests.Session() as session:
68
            login_info = credentials.to_login_info(decrypt=True)
69
            login_info = {'username': login_info['#carte'], 'password': login_info['#code']}
70
            response = session.post(login_url, data=login_info)
71
            logger.debug("Archimed login response {}".format(response.json()))
72
            if not response.json()['success']:
73
                return Response('Authentication failed', status=status.HTTP_401_UNAUTHORIZED)
74

  
75
            content = {
76
                'codeConfig': '',
77
                'xslPath': 'Services/LectorShortAccount.xslt'
78
            }
79
            response = session.post(ws_uri, json=content)
80
            logger.debug("Archimed ws response  {}".format(response.json()))
81
        return Response(response.json())
82

  
83

  
84
archimed_account_details = ArchimedAccountDetails.as_view()
mandayejs/views.py
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 logging
20
import requests
21

  
22
from django.contrib.auth.models import User
23
from rest_framework import status
24
from rest_framework.views import APIView
25
from rest_framework.response import Response
26

  
27
from mandayejs.mandaye.models import UserCredentials
28
from mandayejs.applications import get_app_settings
29

  
30

  
31
class ArchimedAccountDetails(APIView):
32
    """Archimed user's account details
33
    """
34

  
35
    def dispatch(self, request, *args, **kwargs):
36
        response = super(ArchimedAccountDetails, self).dispatch(request, *args, **kwargs)
37
        if response.status_code == 200:
38
            response.data = {'data': response.data, 'err': 0}
39
        else:
40
            response.data = {'data': None, 'err': 1, 'err_desc': response.data}
41
        return response
42

  
43
    def get(self, request, *args, **kwargs):
44
        logger = logging.getLogger(__name__)
45
        app_settings = get_app_settings()
46
        ws_uri = request.build_absolute_uri(
47
            app_settings.SITE_WS_ENDPOINT['account_details'])
48

  
49
        # mellon truncates username to 30 characters
50
        # thus the passed username must be truncated to 30 characters
51
        # for searching purpose.
52
        username = kwargs['username'][:30]
53

  
54
        try:
55
            user = User.objects.get(username=username)
56
        except (User.DoesNotExist,):
57
            return Response('User %s does not exist' % username, status=status.HTTP_404_NOT_FOUND)
58

  
59
        try:
60
            credentials = UserCredentials.objects.get(user=user)
61
        except (UserCredentials.DoesNotExist,):
62
            return Response('User %s is not associated' % username, status=status.HTTP_404_NOT_FOUND)
63

  
64
        login_url = request.build_absolute_uri(
65
            '/DEFAULT/Ermes/Recherche/logon.svc/logon')
66

  
67
        with requests.Session() as session:
68
            login_info = credentials.to_login_info(decrypt=True)
69
            login_info = {'username': login_info['#carte'], 'password': login_info['#code']}
70
            response = session.post(login_url, data=login_info)
71
            logger.debug("Archimed login response {}".format(response.json()))
72
            if not response.json()['success']:
73
                return Response('Authentication failed', status=status.HTTP_401_UNAUTHORIZED)
74

  
75
            content = {
76
                'codeConfig': '',
77
                'xslPath': 'Services/LectorShortAccount.xslt'
78
            }
79
            response = session.post(ws_uri, json=content)
80
            logger.debug("Archimed ws response  {}".format(response.json()))
81
        return Response(response.json())
82

  
83

  
84
archimed_account_details = ArchimedAccountDetails.as_view()
tests/test_archimed.py
29 29
]
30 30

  
31 31

  
32
@mock.patch('mandayejs.views.requests.Session.post')
32
@mock.patch('mandayejs.applications.views.requests.Session.post')
33 33
@mock.patch('mandayejs.applications.get_app_settings')
34 34
def test_archimed_ws(mocked_get_app_settings, mocked_requests_post):
35 35
    mocked_get_app_settings.return_value = Archimed

Formats disponibles : Unified diff