From bbff7f7750483d5d856720889b098291b7dec239 Mon Sep 17 00:00:00 2001 From: Josue Kouka Date: Tue, 22 Dec 2015 17:06:44 +0100 Subject: [PATCH] association failure handled (#9415) --- mandayejs/do_login.js | 10 ++- mandayejs/locale/fr/LC_MESSAGES/django.mo | Bin 746 -> 0 bytes mandayejs/locale/fr/LC_MESSAGES/django.po | 20 +++-- .../migrations/0006_usercredentials_linked.py | 20 +++++ mandayejs/mandaye/models.py | 6 +- mandayejs/mandaye/templates/mandaye/associate.html | 7 ++ .../mandaye/templates/mandaye/post-login.html | 4 - mandayejs/mandaye/utils.py | 18 ++++- mandayejs/mandaye/views.py | 86 ++++++++++++--------- .../vincennes/static/css/vincennes_associate.css | 10 +++ 10 files changed, 132 insertions(+), 49 deletions(-) delete mode 100644 mandayejs/locale/fr/LC_MESSAGES/django.mo create mode 100644 mandayejs/mandaye/migrations/0006_usercredentials_linked.py diff --git a/mandayejs/do_login.js b/mandayejs/do_login.js index cbdbccc..e91a722 100644 --- a/mandayejs/do_login.js +++ b/mandayejs/do_login.js @@ -34,10 +34,16 @@ page.onResourceReceived = function(response){ page.open(input.address, function() { page.onLoadFinished = function() { page.render('login.png'); - console.log(JSON.stringify({'result': 'ok', 'cookies': page.cookies, 'headers': headers_list, 'url': page.frameUrl})); + uri = page.evaluate(function(){ + return window.location.pathname; + }); + if (uri !== input.homepath){ + console.log(JSON.stringify({'result': 'failure', 'reason': 'authentication failed'})); + phantom.exit(); + } + console.log(JSON.stringify({'result': 'ok', 'cookies': page.cookies, 'headers': headers_list, 'url': page.frameUrl, 'uri': uri})); phantom.exit(); } - page.injectJs('static/js/jquery.min.js'); page.evaluate(function(input) { var locators = input.locators; for ( var i=0; i < locators.length; i++ ) { diff --git a/mandayejs/locale/fr/LC_MESSAGES/django.mo b/mandayejs/locale/fr/LC_MESSAGES/django.mo deleted file mode 100644 index 0aaff44a93730a392238914c0618629c82b9d855..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 746 zcmY+BJ#Q015QYyhUl$~#1W{3J35quOEJ31k9Obaj!Q#%g{1FL6vpFxvM(15?cP}CZ zKZ1gemV&=Pi;$p&o`RB|7V)la*~&=Iy*s0s-S;%VHY@Kv#0_u{yaXHI190&T+yvjj zUGNk5;16&!f5BDo4_pJ4OAFnAo`OxVh5Fme3w;N@gZv}Z-SZiG3;Gp$8~Ou!9r_!J zQ4ccD-5V9)!oB0-3UD6g!HiLvV3vEU6FFC|(N&||KRP%H97#KYkMT4i3coYN6!(~u-l_h{@a?7j*a`09FX8a-Cu5sYcf@mWNJEFZSP`j gxw?x*!wam5msq3Wn3mF|+9i`OpVs*qE5ro#|LNbu@c;k- diff --git a/mandayejs/locale/fr/LC_MESSAGES/django.po b/mandayejs/locale/fr/LC_MESSAGES/django.po index 10c38e5..1837b95 100644 --- a/mandayejs/locale/fr/LC_MESSAGES/django.po +++ b/mandayejs/locale/fr/LC_MESSAGES/django.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2015-12-17 17:16+0000\n" +"POT-Creation-Date: 2015-12-23 14:02+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -22,6 +22,12 @@ msgstr "" msgid "locators" msgstr "selecteurs" +#: mandayejs/mandaye/models.py:25 +#, fuzzy +#| msgid "associate" +msgid "associated" +msgstr "associer mon compte" + #: mandayejs/mandaye/templates/mandaye/panel.html:10 msgid "dissociate" msgstr "dissocier mon compte" @@ -31,18 +37,22 @@ msgstr "dissocier mon compte" msgid "associate" msgstr "associer mon compte" -#: mandayejs/mandaye/views.py:56 +#: mandayejs/mandaye/views.py:60 msgid "login" msgstr "se connecter" -#: mandayejs/mandaye/views.py:57 +#: mandayejs/mandaye/views.py:61 msgid "logout" msgstr "se déconnecter" -#: mandayejs/mandaye/views.py:100 +#: mandayejs/mandaye/views.py:108 +msgid "wrong user credentials" +msgstr "codes d'accès invalides" + +#: mandayejs/mandaye/views.py:111 msgid "submit" msgstr "valider" -#: mandayejs/mandaye/views.py:101 +#: mandayejs/mandaye/views.py:112 msgid "associate your account" msgstr "associer mon compte" diff --git a/mandayejs/mandaye/migrations/0006_usercredentials_linked.py b/mandayejs/mandaye/migrations/0006_usercredentials_linked.py new file mode 100644 index 0000000..1149a8d --- /dev/null +++ b/mandayejs/mandaye/migrations/0006_usercredentials_linked.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('mandaye', '0005_auto_20151126_1413'), + ] + + operations = [ + migrations.AddField( + model_name='usercredentials', + name='linked', + field=models.BooleanField(default=True, verbose_name='associated'), + preserve_default=True, + ), + ] diff --git a/mandayejs/mandaye/models.py b/mandayejs/mandaye/models.py index 65c5939..fe6ffcf 100644 --- a/mandayejs/mandaye/models.py +++ b/mandayejs/mandaye/models.py @@ -22,12 +22,16 @@ from django.utils.translation import ugettext_lazy as _ class UserCredentials(models.Model): user = models.ForeignKey('auth.User') locators = JSONField(_('locators'), default={}, blank=True) + linked = models.BooleanField(_('associated'), default=True, blank=True) class Meta: unique_together = ('user',) def __str__(self): - return self.user.email + return self.user.get_full_name() or self.user.email or self.user.username def to_login_info(self): return {'#'+k : v for k,v in self.locators.items() if k != 'csrfmiddlewaretoken' } + + def is_linked(self,): + return self.linked diff --git a/mandayejs/mandaye/templates/mandaye/associate.html b/mandayejs/mandaye/templates/mandaye/associate.html index 67478dd..f5492da 100644 --- a/mandayejs/mandaye/templates/mandaye/associate.html +++ b/mandayejs/mandaye/templates/mandaye/associate.html @@ -9,6 +9,13 @@

{{ associate|capfirst }}

+ {%if messages %} +
    + {%for message in messages%} +
  • {{message}}
  • + {%endfor%} +
+ {%endif%}
{% csrf_token %} {{ form.as_p }} diff --git a/mandayejs/mandaye/templates/mandaye/post-login.html b/mandayejs/mandaye/templates/mandaye/post-login.html index f3435ac..81dfeaa 100644 --- a/mandayejs/mandaye/templates/mandaye/post-login.html +++ b/mandayejs/mandaye/templates/mandaye/post-login.html @@ -2,10 +2,6 @@ - - Please wait... diff --git a/mandayejs/mandaye/utils.py b/mandayejs/mandaye/utils.py index c2070a6..b146cd8 100644 --- a/mandayejs/mandaye/utils.py +++ b/mandayejs/mandaye/utils.py @@ -13,14 +13,28 @@ # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . - - +import os +import json +import subprocess from django.conf import settings import urlparse from Cookie import SimpleCookie +def exec_phantom(data): + phantom = subprocess.Popen(['/usr/bin/phantomjs', + '--ignore-ssl-errors=yes', + '--ssl-protocol=any', + '--cookies-file=cookies.txt', + os.path.join(settings.BASE_DIR, 'mandayejs', 'do_login.js')], + close_fds=True, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE) + stdout, stderr = phantom.communicate(json.dumps(data)) + result = json.loads(stdout) + return result + def cookie_builder(headers): """Build Cookies from list of headers """ diff --git a/mandayejs/mandaye/views.py b/mandayejs/mandaye/views.py index 07a17e5..2a99098 100644 --- a/mandayejs/mandaye/views.py +++ b/mandayejs/mandaye/views.py @@ -14,10 +14,11 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from __future__ import absolute_import + import os import json import logging -import subprocess import urlparse import urllib @@ -26,6 +27,7 @@ from django.contrib.auth import views as auth_views from django.contrib.auth import logout as auth_logout from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required +from django.contrib import messages from django.forms import PasswordInput from django.forms import models as model_forms from django.http import HttpResponseRedirect, HttpResponse @@ -35,10 +37,13 @@ from django.views.generic.base import TemplateView from django.views.decorators.csrf import csrf_exempt from django.db import IntegrityError from django.utils.translation import ugettext_lazy as _ +from django.template import RequestContext, Template from .models import UserCredentials from mandayejs.mandaye.forms import FormFactory -from mandayejs.mandaye.utils import cookie_builder, get_location +from mandayejs.mandaye.utils import exec_phantom, cookie_builder, get_location + +logger = logging.getLogger(__name__) def login(request, *args, **kwargs): return auth_views.login(request, *args, **kwargs) @@ -63,10 +68,11 @@ class Panel(TemplateView): def is_account_linked(self): """Check if user account is associated """ - try: - UserCredentials.objects.get(user=self.request.user) - return True - except : + try: + User = get_user_model() + user = User.objects.get(username=self.request.user.username) + return user.usercredentials_set.get().linked + except: return False @@ -75,8 +81,12 @@ panel = Panel.as_view() @login_required def post_login(request, *args, **kwargs): try: + user = get_user_model().objects.get(username=request.user.username) + logger.debug(user) credentials = UserCredentials.objects.get( - user=request.user) + user=user, + linked=True) + logger.debug(credentials) except UserCredentials.DoesNotExist: return HttpResponseRedirect(resolve_url('associate')) @@ -88,14 +98,15 @@ def post_login(request, *args, **kwargs): @csrf_exempt def associate(request, *args, **kwargs): if request.POST: - credentials = UserCredentials() - credentials.user = request.user + credentials, created = UserCredentials.objects.get_or_create(user=request.user) credentials.locators = request.POST + credentials.linked = True + credentials.save() form = FormFactory(request.POST, auto_id=True, locators=settings.SITE_LOCATORS) else: form = FormFactory(auto_id=True, locators=settings.SITE_LOCATORS) if not form.is_valid(): - return render(request, 'mandaye/associate.html', { + response = render(request, 'mandaye/associate.html', { 'form': form, 'submit': _('submit'), 'associate': _('associate your account'), @@ -103,20 +114,19 @@ def associate(request, *args, **kwargs): 'SITE_ASSOCIATE_STATIC', {'css':'', 'js':''}) }) - try: - credentials.save() - except (IntegrityError,) as e: - pass - + return response + return HttpResponseRedirect(resolve_url('post-login')) @login_required def dissociate(request, *args, **kwargs): try: - User = get_user_model() - User.objects.get(username=request.user).delete() + c_user = UserCredentials.objects.get( + user__username=request.user.username) + c_user.linked = False + c_user.save() return HttpResponseRedirect(resolve_url('mellon_logout')) - except (User.DoesNotExist,) as e: + except: return HttpResponseRedirect(resolve_url('associate')) @login_required @@ -125,25 +135,31 @@ def post_login_do(request, *args, **kwargs): login_info = { 'address': request.build_absolute_uri(settings.SITE_LOGIN_PATH), 'cookies': [], - 'locators': [ credentials.to_login_info() ] + 'locators': [ credentials.to_login_info() ], + 'homepath': getattr(settings, 'SITE_HOME_PATH', '/') } + logger.debug(login_info) result = exec_phantom(login_info) + logger.debug(result) if result.get('result') != 'ok': - return HttpResponseRedirect('/') - location = get_location(result.get('url','/')) - response = HttpResponseRedirect(location) - response.cookies = cookie_builder(result.get('headers')) + logger.debug('authentication failed') + User = get_user_model() + user = User.objects.get(username=request.user.username) + c_user = user.usercredentials_set.get() + c_user.linked = False + c_user.save() + logger.debug("redirecting to {}".format(resolve_url('associate'))) + messages.error(request, _('wrong user credentials')) + url = resolve_url('associate') + else: + url = getattr(settings, 'SITE_HOME_PATH', '/') + + template = Template('') + context = RequestContext(request, {'url': url}) + response = HttpResponse(template.render(context)) + if result.get('headers',None): + response.cookies = cookie_builder(result.get('headers')) + return response -def exec_phantom(data): - phantom = subprocess.Popen(['/usr/bin/phantomjs', - '--ignore-ssl-errors=yes', - '--ssl-protocol=any', - '--cookies-file=cookies.txt', - os.path.join(settings.BASE_DIR,'mandayejs/do_login.js')], - close_fds=True, - stdin=subprocess.PIPE, - stdout=subprocess.PIPE) - stdout, stderr = phantom.communicate(json.dumps(data)) - result = json.loads(stdout) - return result diff --git a/mandayejs/sites/vincennes/static/css/vincennes_associate.css b/mandayejs/sites/vincennes/static/css/vincennes_associate.css index 730891a..0585f4a 100644 --- a/mandayejs/sites/vincennes/static/css/vincennes_associate.css +++ b/mandayejs/sites/vincennes/static/css/vincennes_associate.css @@ -13,6 +13,16 @@ h1 { font-size: x-small; } +.messages { + font-size: small; + text-align: left; + postion: relative; + margin-left: 90px; + color: red; +} + +.messages li { list-style-type: none } + .errorlist { font-size: small; text-align: left; -- 2.6.4