]> git.0d.be Git - mandayejs.git/commitdiff
play login sequence and get session cookie via phantomjs
authorFrédéric Péters <fpeters@entrouvert.com>
Sun, 22 Mar 2015 17:01:37 +0000 (18:01 +0100)
committerFrédéric Péters <fpeters@entrouvert.com>
Sun, 22 Mar 2015 17:03:24 +0000 (18:03 +0100)
It's currently hardwired for redmine, and will take hardcoded values from the
settings file (MANDAYE_USERNAME, MANDAYE_PASSWORD).

do_login.js [new file with mode: 0644]
mandayejs/settings.py
mandayejs/static/mandaye.post.js [new file with mode: 0644]
mandayejs/templates/mandaye/post-login.html
mandayejs/urls.py
mandayejs/views.py

diff --git a/do_login.js b/do_login.js
new file mode 100644 (file)
index 0000000..acfa188
--- /dev/null
@@ -0,0 +1,20 @@
+var page = require('webpage').create();
+var system = require('system');
+
+var input = JSON.parse(system.stdin.read(2000)); // no .readAll()...
+
+page.open(input.address, function() {
+  page.onLoadFinished = function() {
+    console.log(JSON.stringify({'result': 'ok', 'cookies': page.cookies}));
+    phantom.exit();
+  }
+  page.evaluate(function(input) {
+    if ($(input.username_locator).length == 0) {
+      console.log(JSON.stringify({'result': 'ok', 'cookies': page.cookies}));
+      phantom.exit();
+    }
+    $(input.username_locator).val(input.username_value);
+    $(input.password_locator).val(input.password_value);
+    $(input.username_locator).parents('form').find('input[type=submit]').click();
+  }, input);
+});
index ef003250474b639cf9f134da04deaf1a4c1aaa29..1ebe3c1dbb5bc55702c3dee4bcb2cfe40bd1f4cc 100644 (file)
@@ -8,6 +8,8 @@ For the full list of settings and their values, see
 https://docs.djangoproject.com/en/1.7/ref/settings/
 """
 
+from django.conf import global_settings
+
 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
 import os
 BASE_DIR = os.path.dirname(os.path.dirname(__file__))
@@ -36,6 +38,7 @@ INSTALLED_APPS = (
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
+    'gadjo',
 )
 
 MIDDLEWARE_CLASSES = (
@@ -82,6 +85,10 @@ USE_TZ = True
 
 STATIC_URL = '/_mandaye/static/'
 
+# Serve xstatic files, required for gadjo
+STATICFILES_FINDERS = global_settings.STATICFILES_FINDERS + \
+            ('gadjo.finders.XStaticFinder',)
+
 STATICFILES_DIRS = (
     os.path.join(BASE_DIR, 'mandayejs', 'static'),
 )
@@ -90,4 +97,10 @@ TEMPLATE_DIRS = (
     os.path.join(BASE_DIR, 'mandayejs', 'templates'),
 )
 
+LOGIN_URL = 'auth_login'
 LOGIN_REDIRECT_URL = 'post-login'
+
+local_settings_file = os.environ.get('MANDAYEJS_SETTINGS_FILE',
+        os.path.join(os.path.dirname(__file__), 'local_settings.py'))
+if os.path.exists(local_settings_file):
+    execfile(local_settings_file)
diff --git a/mandayejs/static/mandaye.post.js b/mandayejs/static/mandaye.post.js
new file mode 100644 (file)
index 0000000..479e4c7
--- /dev/null
@@ -0,0 +1,5 @@
+$(function() {
+  $('#post-login-frame').on('load', function() {
+    window.location = '/';
+  });
+});
index 012639ebcc552e413cc4087b6afc0175e5c605de..65f72c589ab001c23c270c2e8c92bef2179705dd 100644 (file)
@@ -1,5 +1,13 @@
+{% load gadjo staticfiles %}
 <html>
+<head>
+  <script src="{% xstatic 'jquery' 'jquery.min.js' %}"></script>
+  <script src="{% static 'mandaye.post.js' %}"></script>
+</head>
 <body>
-  post login
+       Please wait...
+ <br/>
+ <iframe id="post-login-frame" src="{% url 'post-login-do' %}" style="display: none;">
+ </iframe>
 </body>
 </html>
index 73961cb7076c09b5be03543e240f272ea5e68537..60a82f4ae5d7ee3a6abf9457e7f325805e5ce9bb 100644 (file)
@@ -6,6 +6,7 @@ urlpatterns = patterns('',
     url(r'^_mandaye/login/$', 'mandayejs.views.login', name='auth_login'),
     url(r'^_mandaye/logout/$', 'mandayejs.views.logout', name='auth_logout'),
     url(r'^_mandaye/post-login/$', 'mandayejs.views.post_login', name='post-login'),
+    url(r'^_mandaye/post-login-do/$', 'mandayejs.views.post_login_do', name='post-login-do'),
 
     url(r'^_mandaye/admin/', include(admin.site.urls)),
 )
index 7123067296eee4a177da4992ddd7bbe0bba0e632..fff1d9428d5c5492a92efff710397da97fa1ee7b 100644 (file)
@@ -1,5 +1,12 @@
+import json
+import os
+import subprocess
+import urlparse
+
+from django.conf import settings
 from django.contrib.auth import views as auth_views
 from django.contrib.auth import logout as auth_logout
+from django.contrib.auth.decorators import login_required
 from django.http import HttpResponseRedirect
 from django.views.generic.base import TemplateView
 
@@ -21,4 +28,42 @@ panel = Panel.as_view()
 class PostLogin(TemplateView):
     template_name = 'mandaye/post-login.html'
 
-post_login = PostLogin.as_view()
+    def get_context_data(self, **kwargs):
+        context = super(PostLogin, self).get_context_data(**kwargs)
+        context['address'] = self.request.build_absolute_uri('/login'),
+        return context
+
+post_login = login_required(PostLogin.as_view())
+
+def post_login_do(request, *args, **kwargs):
+    # XXX: this should come from both configuration (address and locators) and
+    # user database (credentials)
+    login_info = {
+            'username_locator': '#username',
+            'username_value': settings.MANDAYE_USERNAME,
+            'password_locator': '#password',
+            'password_value': settings.MANDAYE_PASSWORD,
+            'address': request.build_absolute_uri('/login'),
+            'cookies': [],
+    }
+    phantom = subprocess.Popen(['/usr/bin/phantomjs',
+        '--ignore-ssl-errors=yes',
+        '--ssl-protocol=any',
+        os.path.join(settings.BASE_DIR, 'do_login.js')],
+        close_fds=True,
+        stdin=subprocess.PIPE,
+        stdout=subprocess.PIPE)
+    stdout, stderr = phantom.communicate(json.dumps(login_info))
+    result = json.loads(stdout)
+    if result.get('result') != 'ok':
+        return HttpResponseRedirect('/')
+    response = HttpResponseRedirect('/')
+    for cookie in result.get('cookies'):
+        response.set_cookie(
+                key=cookie.get('name'),
+                value=cookie.get('value'),
+                path=cookie.get('path'),
+                secure=cookie.get('secure'),
+                httponly=cookie.get('httponly'),
+                )
+    return response