无需重定向的Ajax Django登录/身份验证 [英] Ajax Django Login/Authentication without re-direct

查看:46
本文介绍了无需重定向的Ajax Django登录/身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立类似于StackOverflow的身份验证设置,在该设置中,除非有一些需要进行身份验证的特权操作(在此之前不要打扰用户),否则正常浏览永远不会受到影响.

I am trying to have an authentication set-up similar to that of StackOverflow, where the normal browsing is never affected unless there are some privileged actions which requires authentication (Do not bother users until then).

如果未登录,则应为登录",如果已登录,则应为"UserName".

It should be as "Log In" if not logged in or "UserName" if logged in.

base.html(来自fallr.net)的相关部分(由index.html扩展)如下:

The relevant part of base.html (from fallr.net) (extended by index.html) looks like :

            <script type="text/javascript">
            //<![CDATA[

            $(document).ready(function(){

            var methods = {

            forms : function(){
            var login = function(){
            var user = $(this).children('form').children('input[type="text"]').val();
            var pass = $(this).children('form').children('input[type="password"]').val();
            var dataString = '&username=' + $('input[name=username]').val() + '&password=' + $('input[name=password]').val();
            if(user.length < 1 || pass.length < 1){
            alert('Invalid!\nPlease fill all required forms');
            } else {
            alert('username: '+user+'\npassword: '+pass);
            $.ajax({
            type: "POST",
            url: "/login",
            dataType: "html",
            data: {
            username : user,
            password : pass,
            csrfmiddlewaretoken : '{{ csrf_token }}'
            },
            success: function(json){alert (json.server_response);},
            error: function(xhr,errmsg,err) { alert(xhr.status + ": " + xhr.responseText); }
            });
            $.fallr('hide');
            return false;
            }
            }

            $.fallr('show', {
            icon        : 'secure',
            width       : '320px',
            content     : '<h4>Sign in</h4>'
            + '<form>'
            +     '<input name="username" placeholder="username" type="text"/'+'>'
            +     '<input name="password" placeholder="password" type="password"/'+'>'
            + '</form>',
            buttons : {
            button1 : {text: 'Submit', onclick: login},
            button4 : {text: 'Cancel'}
            }
            });
            }
            };

            //button trigger
            $('a[href^="#fallr-"]').click(function(){
            var id = $(this).attr('href').substring(7);
            methods[id].apply(this,[this]);
            return false;
            });

            // syntax highlighter
            hljs.tabReplace = '    ';
            hljs.initHighlightingOnLoad();
            });

            //]]>
            </script>

urls.py如下:

The urls.py looks like :

            from django.conf.urls import patterns, include, url
            #from triplanner.views import *


            # Uncomment the next two lines to enable the admin:
            # from django.contrib import admin
            # admin.autodiscover()

            urlpatterns = patterns('',
            url(r'^$', main_page),
            url(r'^login$',ajax_login),                 
            url(r'^login/$','django.contrib.auth.views.login'),
            url(r'^logout/$', logout_page),

            # our application page
            url(r'^account/',include('tripapp.urls')),              
            )

此外,'^ login/$'是用于学习的先前实现,我想将其替换为Ajax登录.

Also, '^login/$' is the previous implementation for learning which I want to replace with Ajax login.

还有我的views.py:

And my views.py:

            # -*- coding: utf-8 -*-
            from django.contrib.auth import logout
            from django.http import HttpResponseRedirect
            from django.shortcuts import render_to_response
            from django.contrib.auth import authenticate, login
            #from django.http import HttpResponse
            from django.template import RequestContext
            #from django.utils import simplejson



            def main_page(request):
            return render_to_response('index.html', context_instance=RequestContext(request))


            def logout_page(request):
            """
            Log users out and redirect them to the main page
            """
            logout(request)
            return HttpResponseRedirect('/')


            def ajax_login(request):
            """  
            This view logs a user in using the POST data.
            """

            if request.method == 'POST':
            print request.POST['username']
            username = request.POST['username']
            password = request.POST['password']
            print username
            print password
            user = authenticate(username=username, password=password)
            if (not user is None) and (user.is_active):
            login(request, user)
            response_dict = {}
            response_dict.update({'server_response': username})
            #return HttpResponse(simplejson.dumps(response_dict),mimetype='applicaion/javascript')
            return render_to_response('index.html',{'username' : user}, context_instance=RequestContext(request))
            # Set Session Expiry to 0 if user clicks "Remember Me"
            #if not request.POST.get('rem', None):
            #   request.session.set_expiry(0)
            #data = username
            else:
            return render_to_response('index.html', context_instance=RequestContext(request))

我收到403错误,例如"[[20/Aug/2013 00:29:20]"POST/HTTP/1.1" 403 2294"

I am getting a 403 Error like "[20/Aug/2013 00:29:20] "POST / HTTP/1.1" 403 2294"

更新NUMBER 1 :

使用urls.py,views.py和javascript更改后,我可以获得200响应,但是它提供了警告窗口,提示未定义并警告我从创建对话框中阻止此页面"

With the changed urls.py, views.py and javascript I am able to get a 200 response, but it gives alert window saying undefined and alerting me "Prevent this page from creatng dialog boxes"

推荐答案

我使用的方法是使用 Tastypie api层,需要对API进行身份验证.如果API调用由于身份验证而失败,则客户端可以请求用户通过ajax登录方法登录.

The approach I use is to have a Tastypie api layer and require authentication for the APIs. If the API call fails because of authentication, the client can request the user to log-in via the ajax login method.

您可以使用要点

这篇关于无需重定向的Ajax Django登录/身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆