MongoEngine User authentication (django)

假装没事ソ 提交于 2019-11-27 11:00:38

问题


I am trying to use MongoEngine in a django project I am writing. I am having difficulty getting (or understanding how) the authentication backend works.

The user object as far as I can tell is not stored in the request.

I have it working but I am not sure if I am doing it in the right/safe way. If someone could look at my code I would be much appreciated.

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')

in my settings.py I have added at the top of the file:

AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend',
)

SESSION_ENGINE = 'mongoengine.django.sessions'

import mongoengine
mongoengine.connect('project')

回答1:


Not sure if you are seeing any issues because you make no mention of any but I use mongoengine for my auth backend and this is how I would handle it:

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')

You say the user is not stored in the request...if you mean it is not available in templates, you need to add the auth template context processor in your settings (in addition to the AUTHENTICATION_BACKENDS setting you have set already):

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'django.contrib.auth.context_processors.auth',
    ...
)

To make the user attached to subsequent requests after login, set the AuthenticationMiddleware and the user will be an attribute of the request in all your views:

MIDDLEWARE_CLASSES = (
...
    'django.contrib.auth.middleware.AuthenticationMiddleware',
...
)


来源:https://stackoverflow.com/questions/7492775/mongoengine-user-authentication-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!