django授权

时间:2012-08-31 09:45:47

标签: django authentication

需要授权。阅读了几篇文章,阅读所有内置机制,接受并做到这一点。他开始做了。

注册采用模块django-registration,自己编写了登录,使用了lib django.contrib.auth。如下所示:我登录登录页面,似乎一切都很好,但当我转到另一页时,授权奇迹般地消失了。据我了解,授权没有写入会话,我只在登录页面获得认证。

我做了以下事情:

  1. 在登录页面上获得授权。
  2. 将整个User对象录制到session
  3. 在每个页面上,我在页面加载时检查的第一件事是会话数据中是否有User,如果是,请从那里阅读。
  4. 源代码如下:

    def login_user(request):
    state = "Please log in below..."
    username = password = ''
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')
    
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                state = "You're successfully logged in!"
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."
        request.session['user'] = user
        return render(request,'auth.html',{'state':state, 'username': username, 'info':'info'})
    

    和我从session读取的页面:

    @csrf_protect
    def home(request):
        if "user" in request.session:
            user = request.session['user']
        else:
            user = None
        return render_to_response('home.html', {'user_name' : user}, context_instance = RequestContext(request))
    

    但我认为,这是一种非常愚蠢的方式。你能建议一个更合适的方式吗?

2 个答案:

答案 0 :(得分:1)

我不确定你想要达到什么目标。用户登录后,您可以访问request.user.is_authenticated()以在您的视图中检查经过身份验证的用户,或访问request.user用户本身。

答案 1 :(得分:0)

您无需将用户添加到会话中;这是由身份验证中间件自动完成的。

您也不需要手动检查用户;使用login_required decorator

结合使用此功能,您的登录视图将变为:

def login_user(request):
    state = "Please log in below..."
    username = password = ''
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')
    else:
        return redirect('login/')

    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            state = "You're successfully logged in!"
        else:
            state = "Your account is not active, please contact the site admin."
    else:
        state = "Your username and/or password were incorrect."
    return render(request,'auth.html',{'state':state, 'info':'info'})

在你的其他观点中:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@csrf_protect
@login_required
def home(request):
    return render(request, 'home.html')

在您的模板中(来自documentation):

{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}