Django点滴(三)---用户认证

来源:互联网 发布:网络安全教育考试 编辑:程序博客网 时间:2024/05/29 08:16

https://docs.djangoproject.com/en/dev/topics/auth/default/

启用中间件和模块

在settings.py中, MIDDLEWARE_CLASSES启用SessionMiddlewareAuthenticationMiddleware ;同时,INSTALLED_APPS启用'django.contrib.auth''django.contrib.contenttypes'


用户对象

启用相应中间件和模块并syncdb以后,Django就在数据库中为User对象创建了表。甚至可以用/admin页面(只要你启用了的话)来管理User。
>>> from django.contrib.auth.models import User>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')# At this point, user is a User object that has already been saved# to the database. You can continue to change its attributes# if you want to change other fields.>>> user.last_name = 'Lennon'>>> user.save()
>>> u = User.objects.get(username__exact='john')>>> u.set_password('new password')>>> u.save()

Django自动会为密码加密,可以用下列方式来验证某个用户。
from django.contrib.auth import authenticateuser = authenticate(username='john', password='secret')if user is not None:    # the password verified for the user    if user.is_active:        print("User is valid, active and authenticated")    else:        print("The password is valid, but the account has been disabled!")else:    # the authentication system was unable to verify the username and password    print("The username and password were incorrect.")


权限

用户可以加入某个权限组(Group),或者单独指定多个权限。默认
myuser.groups = [group_list]myuser.groups.add(group, group, ...)myuser.groups.remove(group, group, ...)myuser.groups.clear()myuser.user_permissions = [permission_list]myuser.user_permissions.add(permission, permission, ...)myuser.user_permissions.remove(permission, permission, ...)myuser.user_permissions.clear()

新增某类权限
from django.contrib.auth.models import Group, Permissionfrom django.contrib.contenttypes.models import ContentTypecontent_type = ContentType.objects.get(app_label='myapp', model='BlogPost')permission = Permission.objects.create(codename='can_publish',                                       name='Can Publish Posts',                                       content_type=content_type)
判断用户是否拥有某个权限
 user.has_perm('foo.add_bar')

在Web请求里面进行验证

登入某个用户,并自动创建Session。

from django.contrib.auth import authenticate, logindef my_view(request):    username = request.POST['username']    password = request.POST['password']    user = authenticate(username=username, password=password)    if user is not None:        if user.is_active:            login(request, user)            # Redirect to a success page.        else:            # Return a 'disabled account' error message    else:        # Return an 'invalid login' error message.
登出。

from django.contrib.auth import logoutdef logout_view(request):    logout(request)    # Redirect to a success page.
限制未登录用户。
from django.shortcuts import redirectdef my_view(request):    if not request.user.is_authenticated():        return redirect('/login/?next=%s' % request.path)    # ...

强制要求验证,使用注解。可以指定要跳转的登陆URL,并在url.py中适当配置。


from django.contrib.auth.decorators import login_required@login_required(login_url='/accounts/login/')def my_view(request):    user = request.user
还可以对登录要求一些规则验证或者权限验证,不符合就跳回登录URL。

from django.contrib.auth.decorators import user_passes_testdef email_check(user):    return '@example.com' in user.email@user_passes_test(email_check, login_url='/login/')def my_view(request):    ...
from django.contrib.auth.decorators import permission_required@permission_required('polls.can_vote', login_url='/loginpage/')def my_view(request):    ...

在模板中使用

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

{% if perms.foo %}    <p>You have permission to do something in the foo app.</p>    {% if perms.foo.can_vote %}        <p>You can vote!</p>    {% endif %}    {% if perms.foo.can_drive %}        <p>You can drive!</p>    {% endif %}{% else %}    <p>You don't have permission to do anything in the foo app.</p>{% endif %}