ajax login first step
authorcavaliet
Tue, 19 Aug 2014 18:29:35 +0200
changeset 308 eab6629b5b31
parent 303 88d36ba3f6c9
child 309 c949cb431613
ajax login first step
src/hdabo/templates/registration/login.html
src/hdalab/static/hdalab/js/renkan-manual-save.js
src/hdalab/templates/ajax_identification/ajax_login.html
src/hdalab/templates/ajax_identification/ajax_login_ok.html
src/hdalab/templates/renkan_edit.html
src/hdalab/urls.py
src/hdalab/views/profile.py
--- a/src/hdabo/templates/registration/login.html	Thu Jul 24 16:25:52 2014 +0200
+++ b/src/hdabo/templates/registration/login.html	Tue Aug 19 18:29:35 2014 +0200
@@ -13,7 +13,7 @@
             {% csrf_token %}
             <input type="hidden" name="next" value="{% if next %}{{ next }}{% else %}{% url 'home' %}{% endif %}" />
             {{form.as_p}}
-            <button class="button"type="submit" value="login">{% trans "login" %}</button>
+            <button class="button" type="submit" value="login">{% trans "login" %}</button>
         </form>
         <p>&nbsp;</p>
         <p><a href="{% url 'registration_register' %}">{% trans "Still not a user ? Create an account" %}</a>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hdalab/static/hdalab/js/renkan-manual-save.js	Tue Aug 19 18:29:35 2014 +0200
@@ -0,0 +1,83 @@
+/* Saves the Full JSON once */
+
+Rkns.jsonIOSaveOnClick = function(_renkan, _opts) {
+    var _proj = _renkan.project,
+        _saveWarn = false,
+        _onLeave = function() {
+            return "Project not saved";
+        };
+    if (typeof _opts.http_method === "undefined") {
+        _opts.http_method = 'POST';
+    }
+    var _load = function() {
+        var getdata = {},
+            rx = /id=([^&#?=]+)/,
+            matches = document.location.hash.match(rx);
+        if (matches) {
+            getdata.id = matches[1];
+        }
+        Rkns.$.ajax({
+            url: _opts.url,
+            data: getdata,
+            success: function(_data) {
+                _proj.set(_data, {validate: true});
+            	_renkan.renderer.autoScale();
+            }
+        });
+    };
+    var _save = function() {
+        _proj.set("saved_at", new Date());
+        var _data = _proj.toJSON();
+        Rkns.$.ajax({
+            type: _opts.http_method,
+            url: _opts.url,
+            contentType: "application/json",
+            data: JSON.stringify(_data),
+            success: function(data, textStatus, jqXHR) {
+                console.log("RMS success !");
+                $(window).off("beforeunload", _onLeave);
+                _saveWarn = false;
+                //document.location.hash = "#id=" + data.id;
+                //$(".Rk-Notifications").text("Saved as "+document.location.href).fadeIn().delay(2000).fadeOut();
+            }
+        });
+    };
+    var _checkLeave = function() {
+        var title = _proj.get("title");
+        if (title && _proj.get("nodes").length) {
+            $(".Rk-Save-Button").removeClass("disabled");
+        } else {
+            $(".Rk-Save-Button").addClass("disabled");
+        }
+        if (title) {
+            $(".Rk-PadTitle").css("border-color","#333333");
+        }
+        if (!_saveWarn) {
+            _saveWarn = true;
+            $(window).on("beforeunload", _onLeave);
+        }
+    };
+    _load();
+    _proj.on("add:nodes add:edges add:users change", function(_model) {
+        _model.on("change remove", function(_model) {
+            _checkLeave();
+        });
+        _checkLeave();
+    });
+    _renkan.renderer.save = function() {
+        console.log("RMS _renkan.renderer.save _opts.user_authenticated = ", _opts.user_authenticated);
+        if(_opts.user_authenticated==true){
+            if ($(".Rk-Save-Button").hasClass("disabled")) {
+                if (!_proj.get("title")) {
+                    $(".Rk-PadTitle").css("border-color","#ff0000");
+                }
+            } else {
+                _save();
+            }
+        }
+        else{
+            //$(".Rk-Notifications").text("Connecte-toi bordel !").fadeIn().delay(2000).fadeOut();
+            dialog.dialog( "open" );
+        }
+    };
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hdalab/templates/ajax_identification/ajax_login.html	Tue Aug 19 18:29:35 2014 +0200
@@ -0,0 +1,16 @@
+{% load i18n %}
+<div class="register">
+    {% if form.errors %}
+    <p class="error">{% trans "Sorry, that's not a valid username or password." %}</p>
+    {% endif %}
+    <form action="{% url 'ajax_login' %}" method='post' id="login-form">
+        {% csrf_token %}
+        <input type="hidden" name="next" value="{% url 'ajax_login_ok' %}" />
+        {{form.as_p}}
+        <button class="button" type="submit" value="login">{% trans "login" %}</button>
+    </form>
+    <p>&nbsp;</p>
+    <p><a target="_blank" href="{% url 'registration_register' %}">{% trans "Still not a user ? Create an account" %}</a>
+    <p><a target="_blank" href="{% url 'auth_password_reset' %}">{% trans "Forgot password ?" %}</a>
+</div>
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hdalab/templates/ajax_identification/ajax_login_ok.html	Tue Aug 19 18:29:35 2014 +0200
@@ -0,0 +1,5 @@
+<div class="ok">OK</div>
+<div class="username">
+	<li><a href="{% url 'profile_home' %}">{{ user.username }}</a></li>
+	<li><a href="{% url 'logout' %}?next={% url 'home' %}">{% trans "Log out" %}</a></li>
+</div>
\ No newline at end of file
--- a/src/hdalab/templates/renkan_edit.html	Thu Jul 24 16:25:52 2014 +0200
+++ b/src/hdalab/templates/renkan_edit.html	Tue Aug 19 18:29:35 2014 +0200
@@ -5,6 +5,7 @@
 
 {% block css_import %}
 {{block.super}}
+        <link rel="stylesheet" type="text/css" href="{% static 'hdalab/css/ui-lightness/jquery-ui-1.10.4.min.css' %}" />
         <link rel="stylesheet" type="text/css" href="{% static 'hdalab/css/additionnal_renkan.css' %}" />
         <link rel="stylesheet" type="text/css" href="{% static 'renkanmanager/lib/renkan/css/renkan.css' %}" />
         <style type="text/css">
@@ -26,6 +27,7 @@
 
 {% block js_import %}
 {{block.super}}
+        <script src="{% static 'renkanmanager/lib/jquery-ui-1.10.4.min.js' %}"></script>
         <script src="{% static 'renkanmanager/lib/jquery.mousewheel.min.js' %}"></script>
         <script src="{% static 'renkanmanager/lib/underscore-min.js' %}"></script>
         <script src="{% static 'renkanmanager/lib/backbone.js' %}"></script>
@@ -38,11 +40,12 @@
         </script>
         <script src="{% static 'renkanmanager/lib/require.js' %}"></script>
         <script src="{% static 'renkanmanager/lib/renkan/renkan.js' %}"></script>
+        <script src="{% static 'hdalab/js/renkan-manual-save.js ' %}"></script>
         <script type="text/javascript">
-        
+            var io_options = {}, dialog=false;
             function startRenkan(){
                 var _renkan = new Rkns.Renkan({
-                    snapshot_mode: true,
+                    manual_save: true,
                     static_url : "{% static 'renkanmanager/lib/renkan/' %}",
                     search: [
                         {
@@ -83,17 +86,53 @@
                        node_fill_color: false*/
                     language: "fr"
                 });
-                Rkns.jsonIOSaveOnClick(_renkan, {
-                    url: "{% url 'renkan_get_put' %}" + window.location.search
+                
+                io_options = { url: "{% url 'renkan_get_put' %}" + window.location.search, user_authenticated: {% if request.user.is_authenticated %}true{% else %}false{% endif %} };
+                Rkns.jsonIOSaveOnClick(_renkan, io_options);
+            };
+            
+            $(function() {
+                var form;
+                
+                dialog = $( "#dialog-form" ).dialog({
+                    autoOpen: false,
+                    height: 300,
+                    width: 350,
+                    modal: true
                 });
-            };
+                
+                function manageLoginForm(e, form){
+                    e.preventDefault();
+                    f = $(form);
+                    $.ajax({
+                        type: f.attr("method"),
+                        url: f.attr("action"),
+                        data: f.serialize(),
+                        success: function(data, textStatus, jqXHR) {
+                            $("#dialog-form").html(data);
+                            // in case, login failed, we reassign the behaviour
+                            form = dialog.find( "form" ).on( "submit", function( event ) {
+                                manageLoginForm(event, this);
+                            });
+                        }
+                    });
+                }
+                
+                form = dialog.find( "form" ).on( "submit", function( event ) {
+                    manageLoginForm(event, this);
+                });
+            });
+            
         </script>
 {% endblock %}
 
 {% block main_content %}
+<div id="dialog-form" title="Identification">
+	{% include 'ajax_identification/ajax_login.html' %}
+</div>
 <div class="rnk-wrapper">
   <div class="rnk-container">
     <div id="renkan"></div>
   </div>
-</div>    
+</div>
 {% endblock %}
\ No newline at end of file
--- a/src/hdalab/urls.py	Thu Jul 24 16:25:52 2014 +0200
+++ b/src/hdalab/urls.py	Tue Aug 19 18:29:35 2014 +0200
@@ -39,6 +39,8 @@
     url(r'^renkan/delete/(?P<rk_id>.*)$', login_required(HdalabRenkanDelete.as_view()), name='renkan_delete'),
     url(r'^profile/$', login_required(ProfileHome.as_view()), name='profile_home'),
     url(r'^renkan/public/$', RenkanPublicList.as_view(), name='renkan_public_list'),
+    url(r'^ajaxlogin/$', "hdalab.views.profile.ajax_login", name='ajax_login'),
+    url(r'^ajaxloginok/$', TemplateView.as_view(template_name="ajax_identification/ajax_login_ok.html"), name='ajax_login_ok'),
 
 )
 
--- a/src/hdalab/views/profile.py	Thu Jul 24 16:25:52 2014 +0200
+++ b/src/hdalab/views/profile.py	Tue Aug 19 18:29:35 2014 +0200
@@ -4,11 +4,24 @@
 
 @author: tc
 '''
+
+
 from datetime import datetime
+from django.conf import settings
+from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login
+from django.contrib.auth.forms import AuthenticationForm
+from django.contrib.sites.models import get_current_site
+from django.core.urlresolvers import reverse
 from django.db.models import Q
 from django.http import HttpResponse
+from django.http import HttpResponseRedirect
 from django.shortcuts import get_object_or_404, redirect
-from django.views.decorators.csrf import csrf_exempt
+from django.shortcuts import resolve_url
+from django.template.response import TemplateResponse
+from django.utils.http import is_safe_url
+from django.views.decorators.cache import never_cache
+from django.views.decorators.csrf import csrf_exempt, csrf_protect
+from django.views.decorators.debug import sensitive_post_parameters
 from django.views.generic import TemplateView, View
 from hdabo.models import Tag
 from hdalab.models.renkan import HdalabRenkan
@@ -20,8 +33,8 @@
 import uuid
 
 
+
 import logging
-from django.core.urlresolvers import reverse
 logger = logging.getLogger(__name__)
 
 
@@ -80,6 +93,9 @@
             if rk.owner!=self.request.user:
                 raise Exception("You are not allowed to edit this renkan")
         
+        form = AuthenticationForm(self.request)
+        context["form"] = form
+        
         return context
 
 
@@ -252,4 +268,47 @@
         if "next" in request.GET:
             return redirect(request.GET["next"])
         return redirect(reverse('profile_home'))
+
+
+
+# Function copied from django.contrib.auth.views to simplify ajax login
+@sensitive_post_parameters()
+@csrf_protect
+@never_cache
+def ajax_login(request, template_name='ajax_identification/ajax_login.html',
+          redirect_field_name=REDIRECT_FIELD_NAME,
+          authentication_form=AuthenticationForm,
+          current_app=None, extra_context=None):
+    """
+    Displays the login form and handles the login action.
+    """
+    redirect_to = request.REQUEST.get(redirect_field_name, '')
+
+    if request.method == "POST":
+        form = authentication_form(request, data=request.POST)
+        if form.is_valid():
+
+            # Ensure the user-originating redirection url is safe.
+            if not is_safe_url(url=redirect_to, host=request.get_host()):
+                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
+
+            # Okay, security check complete. Log the user in.
+            auth_login(request, form.get_user())
+
+            return HttpResponseRedirect(redirect_to)
+    else:
+        form = authentication_form(request)
+
+    current_site = get_current_site(request)
+
+    context = {
+        'form': form,
+        redirect_field_name: redirect_to,
+        'site': current_site,
+        'site_name': current_site.name,
+    }
+    if extra_context is not None:
+        context.update(extra_context)
+    return TemplateResponse(request, template_name, context,
+                            current_app=current_app)
     
\ No newline at end of file