Python MongoEngine用户身份验证(django)
我正在写的django项目中尝试使用MongoEngine。我很难获得(或理解)身份验证后端的工作方式 据我所知,用户对象没有存储在请求中 我让它工作,但我不确定我是否以正确/安全的方式工作。如果有人能看看我的代码,我将不胜感激Python MongoEngine用户身份验证(django),python,django,authentication,mongoengine,Python,Django,Authentication,Mongoengine,我正在写的django项目中尝试使用MongoEngine。我很难获得(或理解)身份验证后端的工作方式 据我所知,用户对象没有存储在请求中 我让它工作,但我不确定我是否以正确/安全的方式工作。如果有人能看看我的代码,我将不胜感激 def login(request): user = authenticate(request.POST['username'],request.POST['password']) if user is not None: request
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')
在my settings.py中,我在文件顶部添加了:
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
SESSION_ENGINE = 'mongoengine.django.sessions'
import mongoengine
mongoengine.connect('project')
不确定您是否看到任何问题,因为您没有提及任何问题,但我使用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')
您说用户未存储在请求中…如果您的意思是它在模板中不可用,则需要在您的设置中添加身份验证模板上下文处理器(除了您已经设置的身份验证\u后端设置之外):
要使用户在登录后附加到后续请求,请设置AuthenticationMiddleware
,用户将成为所有视图中请求的属性:
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
...
)
感谢您的帮助,我让它现在可以正常工作了,需要注意的是,您不应该调用viewlogin
,因为它与实际的登录函数冲突。正确,我复制了您的示例。我写的是为了显示模式谢谢你的指针!从mongoengine.django.auth导入用户可能是有意义的(常规用户必须从django.contrib.auth.models导入,而不是从django.contrib.auth导入),您能提供完整的示例吗?@Burak-这是完整的示例。你被困在哪里?
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
...
)