我有一些非常简单的东西,我把它扔在了一起。我有一个像这样的小形式:
<form id="loginForm" action>
<input name="email_address" type="text" placeholder="Email">
<input name="password" type="password">
<a id="loginButton">Login</a>
</form>
我的JavaScript执行以下操作:
$("#loginButton").click(function(){
$.post("/login/",$("#loginForm").serialize(), function(data) {
console.log("login.");
});
});
我编写了一个自定义Django身份验证后端:
from my.custom.project.models import User
class MyBackend:
def authenticate(self, email_address=None, password=None):
print "Trying to auth"
try:
return User.objects.get(email_address=email_address, password=password)
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
我在settings.py
中配置了这样的内容:
AUTHENTICATION_BACKENDS = (
"my.custom.project.auth.MyBackend",
)
在/login/
路径的实际视图中,这是我的内容:
from django.contrib import auth
def login(request):
print "Trying to auth..."
email_address = request.POST['email_address']
password = request.POST['password']
user = auth.authenticate(email_address=email_address, password=password)
if user != None:
auth.login(request, user)
direct_to_template(request, "my/login/template.json")
这是我的网址:
from django.conf.urls.defaults import *
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
admin.autodiscover()
urlpatterns = staticfiles_urlpatterns
urlpatterns += patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^admin/doc', include('django.contrib.admindocs.urls')),
)
urlpatterns += patterns('my.project.views',
(r'^$', 'root'),
(r'^login/?$', 'login'),
(r'^logout/?$', 'logout'),
)
谁能看到我在这里做错了什么?我在Django服务器输出中获得的只有:
[16/Sep/2011 20:17:47] "POST /login/ HTTP/1.1" 403 2326
我服用疯狂的药吗?我忽略了什么?
答案 0 :(得分:2)
这完全是因为Django内置的CSRF系统:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
答案 1 :(得分:1)
嗯,你做的一件事是
from django.contrib.auth import authenticate,login,logout
然后重新定义登录
def login(request):
然后再次调用另一个,这是不可达的(由您自己的登录功能覆盖)。
login(request, user)
虽然不确定是否会导致错误。
答案 2 :(得分:0)
另外,该行:
return User.objects.get(email_address=email_address, password=password)
表示用户记录按原样以明文形式存储密码。事实上,它存储了密码的盐渍哈希,因此您可能需要自己实现所有这些功能。