Django Authentication System

User

默认属性

1
2
3
4
5
username
password
email
first_name
last_name

Diagram

所属方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
is_anonymous():
    永远返回False.用来将User对象和AnonymousUser(未登录的匿名用户)对象作区分用的识别方法。通常,最好用
is_authenticated()方法。

  is_authenticated():
    永远返回True。该方法不代表该用户有任何的许可,也不代表该用户是active的,而只是表明该用户提供了正确的username和password。

  get_full_name():
    返回一个字符串,是first_name和last_name中间加一个空格组成。

  set_password(raw_password):
    调用该方法时候传入一个明文密码,该方法会进行hash转换。该方法调用之后并不会保存User对象。

  check_password(raw_password):
    如果传入的明文密码是正确的返回True。该方法和set_password是一对,也会考虑hash转换。

  set_unusable_password():
    将用户设置为没有密码的状态。调用该方法后,check_password()方法将会永远返回false。但是如果,调用set_password()方法重新设置密码后,该方法将会失效,has_usable_password()也会返回True

  has_usable_password():
    在调用set_unusable_password()方法之后,该方法返回False,正常情况下返回True

  get_group_permissions(obj=None):
    返回该用户通过组所拥有的许可(字符串列表每一个代表一个许可)。obj如果指定,将会返回关于该对象的许可,而不是模型。

  get_all_permissions(obj=None):
    返回该用户所拥有的所有的许可,包括通过组的和通过用户赋予的许可。

  has_perm(perm,obj=None):
    如果用户有传入的perm,则返回True。perm可以是一个格式为:'<app label>.<permission codename>'的字符串。如果User对象为inactive,该方法永远返回False。和前面一样,如果传入obj,则判断该用户对于这个对象是否有这个许可。

  has_perms(perm_list,obj=None):
    和has_perm一样,不同的地方是第一个参数是一个perm列表,只有用户拥有传入的每一个perm,返回值才是True

  has_module_perms(package_name):
    传入的是Django app label,按照'<app label>.<permission codename>'格式。当用户拥有该app label下面所有的perm时,返回值为True。如果用户为inactive,返回值永远为False

  email_user(subject,message,from_email=None):
    发送一封邮件给这个用户,依靠的当然是该用户的email属性。如果from_email不提供的话,Django会使用settings中的DEFAULT_FROM_EMAIL发送。

  get_profile():
    返回一个和Site相关的profile对象,用来存储额外的用户信息。这个返回值会在另一片博文中详细描述。

创建管理员用户

1
python manage.py createsuperuser --username=joe --email=joe@example.com

修改User Ojbect的密码

方式一:代码

1
2
3
u = User.objects.get(username='john')
u.set_password('new password')
u.save()

方式二:后台管理

登陆自带的后台管理系统修改用户密码

注意:用户修改密码后,根据自己系统的设计,可能需要更新session,否则可能会遇到Session invalidation on password change

验证用户

默认验证用户方法

django.contrib.auth.backends.ModelBackend

1
2
3
4
5
6
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
# A backend authenticated the credentials
else:
# No backend authenticated the credentials

如果验证不通过,系统抛出PermissionDenied异常


自定义验证


Permissions and Authorization

用户权限类型

  1. Access to view the “add” form and add an object is limited to users with the “add” permission for that type of object.

  2. Access to view the change list, view the “change” form and change an object is limited to users with the “change” permission for that type of object.

  3. Access to delete an object is limited to users with the “delete” permission for that type of object.

Permissions can be set not only per type of object, but also per specific object instance.

By using the has_add_permission(), has_change_permission() and has_delete_permission() methods provided by the ModelAdmin class, it is possible to customize permissions for different object instances of the same type.

User Fields

User objects have two many-to-many fields: groups and user_permissions.

访问这两个属性字段的方法如下:

1
2
3
4
5
6
7
8
9
myuser.groups.set([group_list])
myuser.groups.add(group, group, ...)
myuser.groups.remove(group, group, ...)
myuser.groups.clear()

myuser.user_permissions.set([permission_list])
myuser.user_permissions.add(permission, permission, ...)
myuser.user_permissions.remove(permission, permission, ...)
myuser.user_permissions.clear()

默认权限列表

当在setting.py的INSTALLED_APPS添加django.contrib.auth时,执行命令**python manager.py migrate后,系统将为每个Model默认生成3种权限:add,change and delete。

注:python manager.py migrate,创建Model权限列表时,会发出 post_migrate 信号。


Groups

django.contrib.auth.models.Group models are a generic way of categorizing users so you can apply permissions, or some other label, to those users.

A user can belong to any number of groups.

用户的Group权限

A user in a group automatically has the permissions granted to that group. For example, if the group Site editors has the permission can_edit_home_page, any user in that group will have that permission.

简单来说,隶属用户组的用户,自然拥有该用户组所拥有的权限。


Model

自定义权限

To create custom permissions for a given model object, use the permissions model Meta attribute.

示例代码1 Meta

在Task自带的权限外,添加额外的权限属性

1
2
3
4
5
6
7
8
class Task(models.Model):
...
class Meta:
permissions = (
("view_task", "Can see available tasks"),
("change_task_status", "Can change the status of tasks"),
("close_task", "Can remove a task by setting its status as closed"),
)

检查用户权限代码

1
2
# codename 查看数据库auth_permission表
user.has_perm('<app label>.<permission codename>')

示例代码2 program

创建一个permission权限属性对象,然后使用 user/group 对象添加这个权限属性对象。

create the can_publish permission for a BlogPost model in myapp:

1
2
3
4
5
6
7
8
9
10
from myapp.models import BlogPost
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.create(
codename='can_publish',
name='Can Publish Posts',
content_type=content_type,
)

The permission can then be assigned to a User via its user_permissions attribute or to a Group via its permissions attribute.