我正在尝试在我写的django项目中使用MongoEngine。我很难获得(或理解如何)身份验证后端的工作原理。
据我所知,用户对象未存储在请求中。
我有它工作,但我不确定我是否以正确/安全的方式做到这一点。如果有人能查看我的代码,我将不胜感激。
def login(request):
user = authenticate(request.POST['username'],request.POST['password'])
if user is not None:
request.session['user'] = user
if user.is_authenticated:
return HttpResponse(user)
else:
return HttpResponse('login failed')
def new_page(request):
try:
user = request.session['user']
if user.is_authenticated:
return HttpResponse('welcome')
except:
return HttpResponse('need be logged in')
在我的settings.py中,我已添加到文件顶部:
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
SESSION_ENGINE = 'mongoengine.django.sessions'
import mongoengine
mongoengine.connect('project')
答案 0 :(得分:10)
不确定您是否看到任何问题,因为您没有提及任何问题,但我使用mongoengine作为我的auth后端,这就是我将如何处理它:
from django.contrib.auth import login, User
from mongoengine.queryset import DoesNotExist
def login_view(request):
try:
user = User.objects.get(username=request.POST['username'])
if user.check_password(request.POST['password']):
user.backend = 'mongoengine.django.auth.MongoEngineBackend'
login(request, user)
request.session.set_expiry(60 * 60 * 1) # 1 hour timeout
return HttpResponse(user)
else:
return HttpResponse('login failed')
except DoesNotExist:
return HttpResponse('user does not exist')
except Exception
return HttpResponse('unknown error')
您说用户未存储在请求中...如果您的意思是模板中没有这个用户,则需要在您的设置中添加身份验证模板上下文处理器(除了您已设置的AUTHENTICATION_BACKENDS设置) :
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.contrib.auth.context_processors.auth',
...
)
要在登录后让用户附加到后续请求,请设置AuthenticationMiddleware
,并且用户将成为所有视图中request
的属性:
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
...
)