Customizing authentication in Django (定制DJango权限功能)记忆的线索

原文:https://docs.djangoproject.com/en/1.6/topics/auth/customizing/

Customizing authentication in Django

The authentication that comes with Django is good enough for most common cases, but you may have needs not met by the out-of-the-box defaults. To customize authentication to your projects needs involves understanding what points of the provided system are extensible or replaceable. This document provides details about how the auth system can be customized.

★ DJango 自带的权限系统能满足一般的需求,但是当你需要扩展更多时,你需要了解哪些是能扩展和替换的。这篇文章会让你了解如何定制 django 的 auth 系统。

Authentication backends provide an extensible system for when a username and password stored with the User model need to be authenticated against a different service than Django’s default.

★ Django 权限支持后台 是可扩展的,尤其当带有 username 和 password 需要鉴定权限的 User模型和 Django 自带的默认权限系统有冲突时。

You can give your models custom permissions that can be checked through Django’s authorization system.

★ 可以把自己定制的权限规则通过 Django 的权限系统应用到 models 上。

You can extend the default User model, or substitute a completely customized model.

★ 可以扩展默认的 User model 或者完全实现一个定制的模型。

Other authentication sources

There may be times you have the need to hook into another authentication source – that is, another source of usernames and passwords or authentication methods.

★ 你可能不只一次想把其它的权限资源整合到Django权限系统里 

For example, your company may already have an LDAP setup that stores a username and password for every employee. It’d be a hassle for both the network administrator and the users themselves if users had separate accounts in LDAP and the Django-based applications.

★ 例如,你的公司的用户已经有一个LDAP账户,如果已存的LDAP账户和Django的账户分离,这是一个麻烦事。 

So, to handle situations like this, the Django authentication system lets you plug in other authentication sources. You can override Django’s default database-based scheme, or you can use the default system in tandem with other systems.

★ 所以,处理这种情况,Django 权限系统允许植入其它的权限资源。可以继承Django默认的基于数据库的模式,或者你可以让默认的权限系统和其它系统协同工作。 

See the authentication backend reference for information on the authentication backends included with Django.

★ 请参考 authentication backend reference (Django 默认权限系统的API)

Specifying authentication backends   ★ 这一小节是讲 Django 所定制的权限的工作原理(还需要好好理解)

Behind the scenes, Django maintains a list of “authentication backends” that it checks for authentication. When somebody callsdjango.contrib.auth.authenticate() – as described in How to log a user in – Django tries authenticating across all of its authentication backends. If the first authentication method fails, Django tries the second one, and so on, until all backends have been attempted.

★ DJango 维护一个 “权限后台支持” 的列表。当调用 django.contrib.auth.authenticate() 时,正如在 How to log a user in 里描述的,Django 试图执行所有的权限后台方法,如果第一个权限方法失败了,Django 会尝试第二个,直到所有的后台被尝试过了。

The list of authentication backends to use is specified in the AUTHENTICATION_BACKENDS setting. This should be a tuple of Python path names that point to Python classes that know how to authenticate. These classes can be anywhere on your Python path.

★ 权限后台方法列表在 AUTHENTICATION_BACKENDS 里设置,这其实就是一个 Python path 元组,在这个元组里存放的是鉴定权限的 Python 类。 这些类可以存放在你的任何 Python path里。

By default, AUTHENTICATION_BACKENDS is set to:     ★ 默认的配置

('django.contrib.auth.backends.ModelBackend',)

That’s the basic authentication backend that checks the Django users database and queries the built-in permissions. It does not provide protection against brute force attacks via any rate limiting mechanism. You may either implement your own rate limiting mechanism in a custom auth backend, or use the mechanisms provided by most Web servers.

★ 这是基本的权限后台检查,只是检查了 DJango users 的db 和 查找 内建的权限。 它不提供对粗鲁的攻击和任何限速机制的检查。 你或许需要在定制的权限系统后端自己实现一个限速机制,或者使用大多数web服务器已经提供的。

The order of AUTHENTICATION_BACKENDS matters, so if the same username and password is valid in multiple backends, Django will stop processing at the first positive match.

★ AUTHENTICATION_BACKENDS 的顺序很重要,所以当同一个 username 和 password 在多个后端合法时,Django 会终止于第一个匹配的。

Note

Once a user has authenticated, Django stores which backend was used to authenticate the user in the user’s session, and re-uses the same backend for the duration of that session whenever access to the currently authenticated user is needed. This effectively means that authentication sources are cached on a per-session basis, so if you change AUTHENTICATION_BACKENDS, you’ll need to clear out session data if you need to force users to re-authenticate using different methods. A simple way to do that is simply to execute Session.objects.all().delete().

★ 当 user 通过了权限系统的检查时,Django 会在 session 里缓存,并在 session 有效期内使权限有效。所以当改变 AUTHENTICATION_BACKENDS 的时候,需要清除 session 数据并强制users用不同的方法再认证。一个简单的办法就是调用 Session.objects.all().delete() 

New in Django 1.6:

If a backend raises a PermissionDenied exception, authentication will immediately fail. Django won’t check the backends that follow.  ★ 在 v1.6 里,如果权限后端抛出 PermissionDenied 的一场,Django 会立刻终止权限的验证。

Writing an authentication backend

An authentication backend is a class that implements two required methods: get_user(user_id) and authenticate(**credentials), as well as a set of optional permission related authorization methods.

★ 权限验证后端是一个类,这个类需要两个方法,get_user(user_id) 和 authenticate(**credentials) ,以及其它非必须的可选的 authorization 方法。 

The get_user method takes a user_id – which could be a username, database ID or whatever, but has to be the primary key of your User object – and returns a User object.

★ get_user 方法需要一个 user_id 参数,这个参数必须是 User 对象的主键。 get_user 方法要返回一个 User 对象。 

The authenticate method takes credentials as keyword arguments. Most of the time, it’ll just look like this: ★ authenticate 方法以 credentials 为参数

class MyBackend(object):
    def authenticate(self, username=None, password=None):
        # Check the username/password and return a User.
        ...

But it could also authenticate a token, like so:  ★ authenticate 方法也可以接受一个 token 为参数 

class MyBackend(object):
    def authenticate(self, token=None):
        # Check the token and return a User.
        ...

Either way, authenticate should check the credentials it gets, and it should return a User object that matches those credentials, if the credentials are valid. If they’re not valid, it should return None.

★ authenticate 应该检查 得到的 credentials 参数,如果检查通过返回一个 User 对象,如果不通过,返回一个 None 

The Django admin system is tightly coupled to the Django User object described at the beginning of this document. For now, the best way to deal with this is to create a Django User object for each user that exists for your backend (e.g., in your LDAP directory, your external SQL database, etc.) You can either write a script to do this in advance, or your authenticate method can do it the first time a user logs in.

★ Django admin 系统和 Django 的 User 对象紧密相关。目前为止,最好处理这个问题的方式就是为每个创建一个 Django User 对象。可以写一个脚本进一步处理,或者当 user 第一次 logs in 时在 authenticate 方法里处理。下面是一个例子。 

Here’s an example backend that authenticates against a username and password variable defined in your settings.py file and creates a Django User object the first time a user authenticates:

from django.conf import settings
from django.contrib.auth.models import User, check_password

class SettingsBackend(object):
    """
    Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name, and a hash of the password. For example:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
    """

    def authenticate(self, username=None, password=None):
        login_valid = (settings.ADMIN_LOGIN == username)
        pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
        if login_valid and pwd_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. Note that we can set password
                # to anything, because it won't be checked; the password
                # from settings.py will.
                user = User(username=username, password='get from settings.py')
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

Handling authorization in custom backends  ★ 这个小节主要讲了三种特殊的用户所拥有的权限

Custom auth backends can provide their own permissions.   ★ 定制的 auth 后端能提供自己的权限 

The user model will delegate permission lookup functions (get_group_permissions()get_all_permissions()has_perm(), andhas_module_perms()) to any authentication backend that implements these functions.   ★ user model 会把权限查找方法委托给任何实现了这些方法的权限后端 

The permissions given to the user will be the superset of all permissions returned by all backends. That is, Django grants a permission to a user that any one backend grants.

★ 赋予给 user 的权限会是所有被后端返回权限中的超级权限。 也就是说   TODO

The simple backend above could implement permissions for the magic admin fairly simply:

class SettingsBackend(object):
    ...
    def has_perm(self, user_obj, perm, obj=None):
        if user_obj.username == settings.ADMIN_LOGIN:
            return True
        else:
            return False

This gives full permissions to the user granted access in the above example. Notice that in addition to the same arguments given to the associated django.contrib.auth.models.User functions, the backend auth functions all take the user object, which may be an anonymous user, as an argument.

A full authorization implementation can be found in the ModelBackend class in django/contrib/auth/backends.py, which is the default backend and queries the auth_permission table most of the time. If you wish to provide custom behavior for only part of the backend API, you can take advantage of Python inheritance and subclass ModelBackend instead of implementing the complete API in a custom backend.

Authorization for anonymous users

An anonymous user is one that is not authenticated i.e. they have provided no valid authentication details. However, that does not necessarily mean they are not authorized to do anything. At the most basic level, most Web sites authorize anonymous users to browse most of the site, and many allow anonymous posting of comments etc.

★ 游客用户是没有被认证的用户,但这不意味着他们没有合法的权限。在大多数情况下,大多数web网站允许游客访问其大部分页面,甚至许多网站允许游客发帖子 

Django’s permission framework does not have a place to store permissions for anonymous users. However, the user object passed to an authentication backend may be an django.contrib.auth.models.AnonymousUser object, allowing the backend to specify custom authorization behavior for anonymous users. This is especially useful for the authors of re-usable apps, who can delegate all questions of authorization to the auth backend, rather than needing settings, for example, to control anonymous access.

★ Django 默认的权限框架没有存放游客权限的地方,然而,允许通过 django.contrib.auth.models.AnonymousUser 定制游客的权限。这对于一些应用尤其有用。

Authorization for inactive users

An inactive user is a one that is authenticated but has its attribute is_active set to False. However this does not mean they are not authorized to do anything. For example they are allowed to activate their account.

★ 不活跃的用户是那些已经通过身份认证(username,password),但是 is_active 属性被设置成 False 的user。然而这不意味着他们没有做任何事情的权限。例如只给他们访问自己账户的权利。 

The support for anonymous users in the permission system allows for a scenario where anonymous users have permissions to do something while inactive authenticated users do not.

★ 在权限系统中,对游客用户的支持是为了这样的情况: 游客用户有某种权限,而 inactive 用户没有这种权限。

Do not forget to test for the is_active attribute of the user in your own backend permission methods.

★ 别忘了检查 user 的 is_active 属性 

Handling object permissions

Django’s permission framework has a foundation for object permissions, though there is no implementation for it in the core. That means that checking for object permissions will always return False or an empty list (depending on the check performed). An authentication backend will receive the keyword parameters obj and user_obj for each object related authorization method and can return the object level permission as appropriate.  ★ Django 的权限框架为 object 权限建立了“根基”  TODO ??

Custom permissions

To create custom permissions for a given model object, use the permissions model Meta attribute.  ★ 为一个 model 对象定制权限,在 model 的 Meta 属性里使用 permissions 

This example Task model creates three custom permissions, i.e., actions users can or cannot do with Task instances, specific to your application:

★ 例子里的 Task model 创建了三个定制的权限,对于 Task model 的实例用户可以或不可以做的

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"),
        )

The only thing this does is create those extra permissions when you run manage.py syncdb. Your code is in charge of checking the value of these permissions when a user is trying to access the functionality provided by the application (viewing tasks, changing the status of tasks, closing tasks.) Continuing the above example, the following checks if a user may view tasks:

★ 这样做唯一的用处是当你运行命令 manage.py syncdb 时,创建了额外的权限。当用户试图访问app提供的功能时,代码负责检查这些权限的值。  

user.has_perm('app.view_task')

Extending the existing User model

There are two ways to extend the default User model without substituting your own model. If the changes you need are purely behavioral, and don’t require any change to what is stored in the database, you can create a proxy model based on User. This allows for any of the features offered by proxy models including default ordering, custom managers, or custom model methods.

★ 两种方式扩展默认的 User。如果你需要增加的功能仅仅是形式上的,而不需要任何对数据库存放的数据的改变,那么可以使用代理模式。如此可以利用代理模式提供的任何便利,包括默认顺序,定制的 Manager,定制的 model 方法等等。

If you wish to store information related to User, you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user. For example you might create an Employee model:

★ 如果想存储和 User 有关的信息,可以使用 one-to-one relationship,关联一个有额外信息的模块上。这种一对一的模块通常被称作“侧写”模块,它存放的可能是和权限无关的User的信息。比如下面的例子:

from django.contrib.auth.models import User

class Employee(models.Model):
    user = models.OneToOneField(User)
    department = models.CharField(max_length=100)

Assuming an existing Employee Fred Smith who has both a User and Employee model, you can access the related information using Django’s standard related model conventions:

>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department

To add a profile model’s fields to the user page in the admin, define an InlineModelAdmin (for this example, we’ll use a StackedInline) in your app’s admin.py and add it to a UserAdmin class which is registered with the User class:   ★ 为 admin 里的 user 页面增加侧写模块里的属性信息,要定义 InlineModelAdmin(例如,使用 StackedInline),并把它添加到为User类提供支持的 UserAdmin 类里。

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

from my_user_profile_app.models import Employee

# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class EmployeeInline(admin.StackedInline):
    model = Employee
    can_delete = False
    verbose_name_plural = 'employee'

# Define a new User admin
class UserAdmin(UserAdmin):
    inlines = (EmployeeInline, )

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

These profile models are not special in any way - they are just Django models that happen to have a one-to-one link with a User model. As such, they do not get auto created when a user is created, but a django.db.models.signals.post_save could be used to create or update related models as appropriate.

★ 侧写模块没有任何特殊之处,他们只是拥有和User 模块一对一关系的 Django 模块。因此,当 user 被创建时侧写信息不会自动生成,使用 django.db.models.signals.post_save 方法可以创建或更新相关的模块。 

Note that using related models results in additional queries or joins to retrieve the related data, and depending on your needs substituting the User model and adding the related fields may be your better option. However existing links to the default User model within your project’s apps may justify the extra database load.

★ 要注意的是,使用相关的模块导致增加了额外的查找和额外的检索代码,并且取决于要替代 User 模块的需求的类型,增加额外的 fields 或许是更好的选择。 

Deprecated in Django 1.5:

Deprecated since version 1.5: With the introduction of custom User models, the use of AUTH_PROFILE_MODULE to define a single profile model is no longer supported. See the Django 1.5 release notes for more information.

★ 这个功能在 v1.5 时已经废弃了 

Prior to 1.5, a single profile model could be specified site-wide with the setting AUTH_PROFILE_MODULE with a string consisting of the following items, separated by a dot:

  1. The name of the application (case sensitive) in which the user profile model is defined (in other words, the name which was passed to manage.py startapp to create the application).
  2. The name of the model (not case sensitive) class.

For example, if the profile model was a class named UserProfile and was defined inside an application named accounts, the appropriate setting would be:

AUTH_PROFILE_MODULE = 'accounts.UserProfile'

When a user profile model has been defined and specified in this manner, each User object will have a method – get_profile() – which returns the instance of the user profile model associated with that User.

The method get_profile() does not create a profile if one does not exist.

Substituting a custom User model

New in Django 1.5.

Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.

★ 如果想实现默认权限系统不支持的验证功能,例如,用 email 地址验证用户而非用户名。

Django allows you to override the default User model by providing a value for the AUTH_USER_MODEL setting that references a custom model:

AUTH_USER_MODEL = 'myapp.MyUser'

This dotted pair describes the name of the Django app (which must be in your INSTALLED_APPS), and the name of the Django model that you wish to use as your User model.

★ 通过给 AUTH_USER_MODEL 赋值来覆盖默认的 User model。 引号里是具体形式。 

Warning

Changing AUTH_USER_MODEL has a big effect on your database structure. It changes the tables that are available, and it will affect the construction of foreign keys and many-to-many relationships. If you intend to set AUTH_USER_MODEL, you should set it before running manage.py syncdb for the first time.  ★ 改变 AUTH_USER_MODEL 会给数据库带来重大改变 

If you have an existing project and you want to migrate to using a custom User model, you may need to look into using a migration tool like South to ease the transition.  

Referencing the User model

If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different User model.

★ 如果直接引用 User 类作为外键,那么当 AUTH_USER_MODEL 改变的时候会导致程序发生异常。 

get_user_model()

Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active User model – the custom User model if one is specified, or User otherwise.

★ 应该用 django.contrib.auth.get_user_model()  方法而 不是直接引用 User 类。

When you define a foreign key or many-to-many relations to the User model, you should specify the custom model using the AUTH_USER_MODEL setting. For example:   ★ 应该引用 settings 里配置的 AUTH_USER_MODEL 

from django.conf import settings
from django.db import models

class Article(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL)

Specifying a custom User model

Model design considerations

Think carefully before handling information not directly related to authentication in your custom User Model.

It may be better to store app-specific user information in a model that has a relation with the User model. That allows each app to specify its own user data requirements without risking conflicts with other apps. On the other hand, queries to retrieve this related information will involve a database join, which may have an effect on performance.

Django expects your custom User model to meet some minimum requirements.   ★ Django 期待定制的 User 至少满足的规则如下

  1. Your model must have an integer primary key.    ★ 定制的 model 必须有一个整数主键 
  2. Your model must have a single unique field that can be used for identification purposes. This can be a username, an email address, or any other unique attribute.  ★ 必须有一个唯一的域用作身份认证
  3. Your model must provide a way to address the user in a “short” and “long” form. The most common interpretation of this would be to use the user’s given name as the “short” identifier, and the user’s full name as the “long” identifier. However, there are no constraints on what these two methods return - if you want, they can return exactly the same value.

The easiest way to construct a compliant custom User model is to inherit from AbstractBaseUserAbstractBaseUser provides the core implementation of a User model, including hashed passwords and tokenized password resets. You must then provide some key implementation details:

★ 定制 User 模块最简单的方法就是继承 AbstractBaseUser. AbstractBaseUser 提供了User 的核心功能,包括密码哈希化等等。

class  models. CustomUser
USERNAME_FIELD

A string describing the name of the field on the User model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier. The field must be unique (i.e., have unique=True set in its definition).    ★ 一个给 User 做身份认证的字符串,它通常是 username, email address 或者 其它的唯一标识符。

In the following example, the field identifier is used as the identifying field:

class MyUser(AbstractBaseUser):
    identifier = models.CharField(max_length=40, unique=True)
    ...
    USERNAME_FIELD = 'identifier'
REQUIRED_FIELDS

A list of the field names that will be prompted for when creating a user via the createsuperuser management command. The user will be prompted to supply a value for each of these fields. It must include any field for which blank is False or undefined and may include additional fields you want prompted for when a user is created interactively. However, it will not work for ForeignKey fields. REQUIRED_FIELDS has no effect in other parts of Django, like creating a user in the admin.

★ 当用 createsuperuser 命令来交互式地创建 user 时所提示的东西。它不适用于外键。

For example, here is the partial definition for a User model that defines two required fields - a date of birth and height:

class MyUser(AbstractBaseUser):
    ...
    date_of_birth = models.DateField()
    height = models.FloatField()
    ...
    REQUIRED_FIELDS = ['date_of_birth', 'height']

Note   ★ 不用把 USERNAME_FIELD 和 password 添加进去,因为他们总被提示

REQUIRED_FIELDS must contain all required fields on your User model, but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.

is_active

A boolean attribute that indicates whether the user is considered “active”. This attribute is provided as an attribute on AbstractBaseUser defaulting to True. How you choose to implement it will depend on the details of your chosen auth backends. See the documentation of the is_active attribute on the built-in user model for details.

★ is_active 是一个判断当前用户是否有效的布尔值,在 AbstractBaseUser 里默认为 True。

get_full_name()

A longer formal identifier for the user. A common interpretation would be the full name of the user, but it can be any string that identifies the user.

get_short_name()

A short, informal identifier for the user. A common interpretation would be the first name of the user, but it can be any string that identifies the user in an informal way. It may also return the same value as django.contrib.auth.models.User.get_full_name().

The following methods are available on any subclass of AbstractBaseUser:

class  models. AbstractBaseUser
get_username()

Returns the value of the field nominated by USERNAME_FIELD.

is_anonymous()

Always returns False. This is a way of differentiating from AnonymousUser objects. Generally, you should prefer using is_authenticated() to this method.

is_authenticated()

Always returns True. This is a way to tell if the user has been authenticated. This does not imply any permissions, and doesn’t check if the user is active - it only indicates that the user has provided a valid username and password.

★ 这个方法不检查权限,只确保用户名和密码合法。

set_password( raw_password)

Sets the user’s password to the given raw string, taking care of the password hashing. Doesn’t save the AbstractBaseUser object.

When the raw_password is None, the password will be set to an unusable password, as if set_unusable_password() were used.

Changed in Django 1.6:

In Django 1.4 and 1.5, a blank string was unintentionally stored as an unsable password as well.

check_password( raw_password)

Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.)

Changed in Django 1.6:

In Django 1.4 and 1.5, a blank string was unintentionally considered to be an unusable password, resulting in this method returningFalse for such a password.

set_unusable_password()

Marks the user as having no password set. This isn’t the same as having a blank string for a password. check_password() for this user will never return True. Doesn’t save the AbstractBaseUser object.

You may need this if authentication for your application takes place against an existing external source such as an LDAP directory.

has_usable_password()

Returns False if set_unusable_password() has been called for this user.

You should also define a custom manager for your User model. If your User model defines usernameemailis_staff,is_activeis_superuserlast_login, and date_joined fields the same as Django’s default User, you can just install Django’s UserManager; however, if your User model defines different fields, you will need to define a custom manager that extends BaseUserManager providing two additional methods:   ★ 如果定义了和默认 User 不用的属性信息,就要实现自己的 UserManager。 UserManager 要继承 BaseUserManager 方法,并提供两个额外的方法。

class  models. CustomUserManager
create_user( *username_field*password=None**other_fields)

The prototype of create_user() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_user should be defined as:

def create_user(self, email, date_of_birth, password=None):
    # create user here
    ...
create_superuser( *username_field*password**other_fields)

The prototype of create_superuser() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_superuser should be defined as:

def create_superuser(self, email, date_of_birth, password):
    # create superuser here
    ...

Unlike create_user()create_superuser() must require the caller to provide a password.

BaseUserManager provides the following utility methods:

class  models. BaseUserManager
normalize_email( email)

classmethod that normalizes email addresses by lowercasing the domain portion of the email address.

get_by_natural_key( username)

Retrieves a user instance using the contents of the field nominated by USERNAME_FIELD.

make_random_password( length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')

Returns a random password with the given length and given string of allowed characters. Note that the default value ofallowed_chars doesn’t contain letters that can cause user confusion, including:

  • ilI, and 1 (lowercase letter i, lowercase letter L, uppercase letter i, and the number one)
  • oO, and 0 (lowercase letter o, uppercase letter o, and zero)

Extending Django’s default User

If you’re entirely happy with Django’s User model and you just want to add some additional profile information, you can simply subclass django.contrib.auth.models.AbstractUser and add your custom profile fields. This class provides the full implementation of the default User as an abstract model.

★ 如果满意 Django 自带的 User 模块,只是增加一些额外的信息,那么继承 django.contrib.auth.models.AbstractUser 添加额外的属性是最好的选择。这个类提供了默认的 User 信息。

Custom users and the built-in auth forms

As you may expect, built-in Django’s forms and views make certain assumptions about the user model that they are working with.

If your user model doesn’t follow the same assumptions, it may be necessary to define a replacement form, and pass that form in as part of the configuration of the auth views.

★ 内建的 Django forms 和 views 假定了一些 user 模块必须实现的规则。如果定制的 user 模块不遵循这些假设的话,很有必要重写一个 form。

  • UserCreationForm

    Depends on the User model. Must be re-written for any custom user model.  ★ 取决 User 模块,定制 User 模块必须重写

  • UserChangeForm

    Depends on the User model. Must be re-written for any custom user model.  ★ 取决 User 模块,定制的 User 模块必须重写 

  • AuthenticationForm

    Works with any subclass of AbstractBaseUser, and will adapt to use the field defined in USERNAME_FIELD.   ★ 和任何继承自 AbstractBaseUser 类的子类协同工作 

  • PasswordResetForm

    Assumes that the user model has an integer primary key, has a field named email that can be used to identify the user, and a boolean field named is_active to prevent password resets for inactive users.

  • SetPasswordForm

    Works with any subclass of AbstractBaseUser

    ★ 匹配任何 AbstractBaseUser 的子类

  • PasswordChangeForm

    Works with any subclass of AbstractBaseUser

    ★ 同上

  • AdminPasswordChangeForm

    Works with any subclass of AbstractBaseUser

    ★ 同上

Custom users and django.contrib.admin

If you want your custom User model to also work with Admin, your User model must define some additional attributes and methods. These methods allow the admin to control access of the User to admin content:

class  models. CustomUser
is_staff

Returns True if the user is allowed to have access to the admin site.

★ user 允许访问网站返回 True

is_active

Returns True if the user account is currently active.

has_perm(perm, obj=None):

Returns True if the user has the named permission. If obj is provided, the permission needs to be checked against a specific object instance.

has_module_perms(app_label):

Returns True if the user has permission to access models in the given app.

You will also need to register your custom User model with the admin. If your custom User model extendsdjango.contrib.auth.models.AbstractUser, you can use Django’s existing django.contrib.auth.admin.UserAdmin class. However, if your User model extends AbstractBaseUser, you’ll need to define a custom ModelAdmin class. It may be possible to subclass the default django.contrib.auth.admin.UserAdmin; however, you’ll need to override any of the definitions that refer to fields on django.contrib.auth.models.AbstractUser that aren’t on your custom User class.

Custom users and permissions

To make it easy to include Django’s permission framework into your own User class, Django provides PermissionsMixin. This is an abstract model you can include in the class hierarchy for your User model, giving you all the methods and database fields necessary to support Django’s permission model.

PermissionsMixin provides the following methods and attributes:

class  models. PermissionsMixin
is_superuser

Boolean. Designates that this user has all permissions without explicitly assigning them.

get_group_permissions( obj=None)

Returns a set of permission strings that the user has, through his/her groups.

If obj is passed in, only returns the group permissions for this specific object.

get_all_permissions( obj=None)

Returns a set of permission strings that the user has, both through group and user permissions.

If obj is passed in, only returns the permissions for this specific object.

has_perm( permobj=None)

Returns True if the user has the specified permission, where perm is in the format "<app label>.<permission codename>"(see permissions). If the user is inactive, this method will always return False.

If obj is passed in, this method won’t check for a permission for the model, but for this specific object.

has_perms( perm_listobj=None)

Returns True if the user has each of the specified permissions, where each perm is in the format"<app label>.<permission codename>". If the user is inactive, this method will always return False.

If obj is passed in, this method won’t check for permissions for the model, but for the specific object.

has_module_perms( package_name)

Returns True if the user has any permissions in the given package (the Django app label). If the user is inactive, this method will always return False.

ModelBackend

If you don’t include the PermissionsMixin, you must ensure you don’t invoke the permissions methods onModelBackendModelBackend assumes that certain fields are available on your user model. If your User model doesn’t provide those fields, you will receive database errors when you check permissions.

Custom users and Proxy models

One limitation of custom User models is that installing a custom User model will break any proxy model extending User. Proxy models must be based on a concrete base class; by defining a custom User model, you remove the ability of Django to reliably identify the base class.

If your project uses proxy models, you must either modify the proxy to extend the User model that is currently in use in your project, or merge your proxy’s behavior into your User subclass.

Custom users and signals

Another limitation of custom User models is that you can’t use django.contrib.auth.get_user_model() as the sender or target of a signal handler. Instead, you must register the handler with the resulting User model. See Signals for more information on registering and sending signals.

Custom users and testing/fixtures

If you are writing an application that interacts with the User model, you must take some precautions to ensure that your test suite will run regardless of the User model that is being used by a project. Any test that instantiates an instance of User will fail if the User model has been swapped out. This includes any attempt to create an instance of User with a fixture.

To ensure that your test suite will pass in any project configuration, django.contrib.auth.tests.utils defines a@skipIfCustomUser decorator. This decorator will cause a test case to be skipped if any User model other than the default Django user is in use. This decorator can be applied to a single test, or to an entire test class.

Depending on your application, tests may also be needed to be added to ensure that the application works with any user model, not just the default User model. To assist with this, Django provides two substitute user models that can be used in test suites:

class  tests.custom_user. CustomUser

A custom user model that uses an email field as the username, and has a basic admin-compliant permissions setup

class  tests.custom_user. ExtensionUser

A custom user model that extends django.contrib.auth.models.AbstractUser, adding a date_of_birth field.

You can then use the @override_settings decorator to make that test run with the custom User model. For example, here is a skeleton for a test that would test three possible User models – the default, plus the two User models provided by auth app:

from django.contrib.auth.tests.utils import skipIfCustomUser
from django.contrib.auth.tests.custom_user import CustomUser, ExtensionUser
from django.test import TestCase
from django.test.utils import override_settings


class ApplicationTestCase(TestCase):
    @skipIfCustomUser
    def test_normal_user(self):
        "Run tests for the normal user model"
        self.assertSomething()

    @override_settings(AUTH_USER_MODEL='auth.CustomUser')
    def test_custom_user(self):
        "Run tests for a custom user model with email-based authentication"
        self.assertSomething()

    @override_settings(AUTH_USER_MODEL='auth.ExtensionUser')
    def test_extension_user(self):
        "Run tests for a simple extension of the built-in User."
        self.assertSomething()
Changed in Django 1.6:

In Django 1.5, it wasn’t necessary to explicitly import the test User models.

A full example   ★ 一个完整的例子

Here is an example of an admin-compliant custom user app. This user model uses an email address as the username, and has a required date of birth; it provides no permission checking, beyond a simple admin flag on the user account. This model would be compatible with all the built-in auth forms and views, except for the User creation forms. This example illustrates how most of the components work together, but is not intended to be copied directly into projects for production use.

This code would all live in a models.py file for a custom authentication app:

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)


class MyUserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            date_of_birth=date_of_birth,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, date_of_birth, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(email,
            password=password,
            date_of_birth=date_of_birth
        )
        user.is_admin = True
        user.save(using=self._db)
        return user


class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['date_of_birth']

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    # On Python 3: def __str__(self):
    def __unicode__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

Then, to register this custom User model with Django’s admin, the following code would be required in the app’s admin.py file:

from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from customauth.models import MyUser


class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = MyUser
        fields = ('email', 'date_of_birth')

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = MyUser
        fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]


class MyUserAdmin(UserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'date_of_birth', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('date_of_birth',)}),
        ('Permissions', {'fields': ('is_admin',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'date_of_birth', 'password1', 'password2')}
        ),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()

# Now register the new UserAdmin...
admin.site.register(MyUser, MyUserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)

Finally, specify the custom model as the default user model for your project using the AUTH_USER_MODEL setting in yoursettings.py:

AUTH_USER_MODEL = 'customauth.MyUser'


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值