Backbone.js 和 Django Rest Framework 的注册和认证

Backbone.js and Django Rest Framework registration and authentication

我正在为我的前端使用 backbone.js 创建一个应用程序,为我的后端使用 django-rest-framework。我希望能够注册用户、登录和注销用户,并检查用户是否使用 backbone.

登录

我了解 django 身份验证的工作原理以及 drf 如何使用身份验证,但我不知道如何将其绑定到 backbone。

谁能指出我正确的方向?

我正在使用 django-rest-auth with AngularJS. It provides you a set of REST API endpoints to handle User Registration and Authentication tasks and it integrates perfectly with django-rest-framework and django-allauth

要获取用户信息,你需要调用这个API:

.../rest-auth/user/

默认响应是:

username
first_name
last_name
email

但您可以使用其他信息对其进行扩展。

如果您的所有应用只能通过用户密码访问,请使用 Django 的身份验证系统 https://docs.djangoproject.com/en/1.7/topics/auth/default/#django.contrib.auth.views.login。发表你的看法@login_required.

现在,如果您想通过 ajax 调用让他们登录,请创建一个视图,如下所示:

from django.contrib.auth import authenticate
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def login_ajax(request):
    data = json.loads(request.body.decode("utf-8"))
    user = authenticate(username=data['user'], password=data['pass'])
    if user:      
        return HttpResponse("OK")
    else:
        return HttpResponse("Error", status=401)

稍后,在您的模板上的 JS 上:

$.post( /* url where you mapped the login_ajax view */, { user: "John", pass: "abc123" } )
 .done(function( data ) { alert( "User logged in: " + data );})
 .fail(function( data ) { alert( "User not logged in: " + data );});