I. Overview of authentication and authorization
Django
There is a built-in authorization system. He used to process user, group, and permission-based cookie
conversation systems. Django
Authorization authentication and authorization system comprises two parts. Verification is to verify that the user is who he claims to be (such as user name and password authentication, role validation), is authorized to give him the appropriate permissions. Django
Built-in permissions system include the following:
- user.
- Authority.
- Grouping.
- You can configure a password hashing system.
- A pluggable back office systems.
Use authorization system:
Once you have created a default in django
the project, in fact, it has been integrated authorization system. Which part of that is associated with the authorization system configuration yet. The following make a simple list:
INSTALLED_APPS
:
django.contrib.auth
: Authorization framework includes a core, and most of the model definition.django.contrib.contenttypes
:Content Type
The system can be used to model and associated rights.
Middleware:
SessionMiddleware
: To managesession
.AuthenticationMiddleware
: Used to process the currentsession
associated with the user.
Second, the user object
User Model
User
Model is a core part of the framework. His full path is django.contrib.auth.models.User
. The following for this User
to be a simple understanding of objects:
Field:
Built-in User
model has the following fields:
username
: username. 150 characters or less. It may contain numbers and English characters, as well as_
,@
,+
,.
and-
character. It can not be blank and must be unique!first_name
: Crooked nutsfirst_name
, in 30 characters or less. It can be empty.last_name
: Crooked nutslast_name
, in 150 characters or less. It can be empty.email
:mailbox. It can be empty.password
:password. After after the hash code.groups
: Grouping. A user can belong to a plurality of packets, a packet may have multiple users.groups
This field is withGroup
the relationship between a many to many.user_permissions
: Permissions. A user can have multiple permission, a permission can be multiple users all use. AndPermission
belongs to a relationship of many to many.is_staff
: Is it possible to enteradmin
the site. Whether it is on behalf of employees.is_active
: Whether it is available. For some of the data you want to delete the account, we set this valueFalse
on it, not really deleted from the database.is_superuser
: Whether it is super administrator. If you are a super administrator, you have all the rights of the entire site.last_login
: Time of the last login.date_joined
: The time of account creation.
Basic Usage User Model:
Create a user:
By create_user
can quickly create a user method. This method must be passed username
, email
, password
. Sample code is as follows:
from django.contrib.auth.models import User
user = User.objects.create_user('zhiliao','[email protected]','111111') # 此时user对象已经存储到数据库中了。当然你还可以继续使用user对象进行一些修改 user.last_name = 'abc' user.save()
Create a super user:
There are two ways to create a super-user. The first way is to use the code. Create a super user in code with the ordinary user to create very similar, just use create_superuser
. Sample code is as follows:
from django.contrib.auth.models import User
User.objects.create_superuser('admin','[email protected]','111111')
Command line can also passed. Command is as follows:
python manage.py createsuperuser
Later you will be prompted to enter a user name, email and password.
change Password:
Because the password is encrypted and need to go through in order to go in the store. So if you want to change the password, you can not directly modify the password
field, and by invoking the need set_password
to achieve the purpose of modifying the password. Sample code is as follows:
from django.contrib.auth.models import User
user = User.objects.get(pk=1)
user.set_password('新的密码')
user.save()
Login authentication:
Django
The verification system has helped us to achieve a login authentication function. Through django.contrib.auth.authenticate
can be realized. This method is only through username
and password
for authentication. Sample code is as follows:
from django.contrib.auth import authenticate
user = authenticate(username='zhiliao', password='111111')
# 如果验证通过了,那么就会返回一个user对象。 if user is not None: # 执行验证通过后的代码 else: # 执行验证没有通过的代码。
Extended user model:
Django
Built-in User
although models have been strong enough. But sometimes still can not meet our needs. For example, when a user logs in verification, he uses a user name as verification, we sometimes need to be verified by the mobile phone number or email. For example, we also want to add some new fields. So this time we need to extend the user model. Extended User model has a number of ways. Here we look at each case.
1. Set Proxy model:
If you Django
are satisfied with the field provided, and a method of verification, there is no need to change. But just need to add some method of operation in his original foundation. It is recommended to use this way. Sample code is as follows:
class Person(User):
class Meta: proxy = True def get_blacklist(self): return self.objects.filter(is_active=False)
In the above, we define a Person
class, inherited from him User
, and in Meta
the setting proxy=True
, indicating that this is only User
a proxy model. He will not affect the original User
structure of the model in a database table. If you later want to easily access all the blacklist of people, then you can Person.get_blacklist()
you can get to. And User.objects.all()
and Person.objects.all()
in fact it is equivalent. Because they are from User
to get all the data in this model.
2. one foreign key:
If you are a user authentication method authenticate
is no other requirement it is to use username
and password
to complete. But want to add a new field on the basis of the original model, you can use one-way foreign keys. Sample code is as follows:
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver from django.db.models.signals import post_save class UserExtension(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='extension') birthday = models.DateField(null=True,blank=True) school = models.CharField(max_length=100) @receiver(post_save,sender=User) def create_user_extension(sender,instance,created,**kwargs): if created: UserExtension.objects.create(user=instance) else: instance.extension.save()
Defined above, a UserExtension
model, and she and User
the model one to one binding, after our new field is added to UserExtension
the. And also wrote a signal processing method accepts save the model, as long as the User
call save
method, it will create a UserExtension
and User
binding.
3. inherited from AbstractUser
:
For authenticate
not satisfied and do not want to modify the original User
some of the fields on the object, but want to add some fields, you can inherit directly from this time django.contrib.auth.models.AbstractUser
, in fact, this class is django.contrib.auth.models.User
the parent class. For example, we want the original User
to add a base model on telephone
and school
fields. Sample code is as follows:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser): telephone = models.CharField(max_length=11,unique=True) school = models.CharField(max_length=100) # 指定telephone作为USERNAME_FIELD,以后使用authenticate # 函数验证的时候,就可以根据telephone来验证 # 而不是原来的username USERNAME_FIELD = 'telephone' REQUIRED_FIELDS = [] # 重新定义Manager对象,在创建user的时候使用telephone和 # password,而不是使用username和password objects = UserManager() class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self,telephone,password,**extra_fields): if not telephone: raise ValueError("请填入手机号码!") user = self.model(telephone=telephone,*extra_fields) user.set_password(password) user.save() return user def create_user(self,telephone,password,**extra_fields): extra_fields.setdefault('is_superuser',False) return self._create_user(telephone,password) def create_superuser(self,telephone,password,**extra_fields): extra_fields['is_superuser'] = True return self._create_user(telephone,password)
Then in settings
the configured AUTH_USER_MODEL=youapp.User
.
Because this way undermines the original table structure User model, it must be the first time migrate
before it is first defined.
4. inherited from the AbstractBaseUser
model:
If you want to modify the default authentication mode for the original and User
do not want some of the fields on the model, you can customize a model, then inherit from AbstractBaseUser
, and then add the fields you want. In this way would be more trouble, it is best to determine their Django
only recommended for better understanding. Proceed as follows:
-
Create the model. Sample code is as follows:
class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=150) telephone = models.CharField(max_length=11,unique=True) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'telephone' REQUIRED_FIELDS = [] objects = UserManager() def get_full_name(self): return self.username def get_short_name(self): return self.username
Where
password
andlast_login
areAbstractBaseUser
already adding Well, we inherited directly on it. Then we add the field we want. For exampleemail
,username
,telephone
and so on. This can be achieved in the field you want. But because we rewriteUser
, so it should be possible simulationUser
model:USERNAME_FIELD
: Used to describeUser
a string model name of the field, as the unique identifier. If not modified, it will be usedUSERNAME
as a unique field.REQUIRED_FIELDS
: A list of field names, for when bycreatesuperuser
creating a user management command prompt.is_active
: A Boolean value that is used to identify the user currently available.get_full_name()
: Get the complete name.get_short_name()
: A relatively short user name.
-
Redefined
UserManager
: We also need to define your ownUserManager
, because the defaultUserManager
used when creating the user isusername
andpassword
then we asked to be replacedtelephone
. Sample code is as follows:class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self,telephone,password,**extra_fields): if not telephone: raise ValueError("请填入手机号码!") user = self.model(telephone=telephone,*extra_fields) user.set_password(password) user.save() return user def create_user(self,telephone,password,**extra_fields): extra_fields.setdefault('is_superuser',False) return self._create_user(telephone,password) def create_superuser(self,telephone,password,**extra_fields): extra_fields['is_superuser'] = True return self._create_user(telephone,password)
-
In the new creation of
User
the model, also you need tosettings
configure in. ConfigurationAUTH_USER_MODEL='appname.User'
. -
How to use this custom model: for example, since we have a
Article
model, you need to reference this foreign keyUser
model, it can be referenced in two ways.
The first is directlyUser
imported into the current file. Sample code is as follows:from django.db import models from myauth.models import User class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE)
This way is feasible. But in order to better use, it is recommended or the
User
abstracts, usesettings.AUTH_USER_MODEL
to represent. Sample code is as follows:from django.db import models from django.conf import settings class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
-
注意
Because this way undermines the original table structure User model, it must be the first timemigrate
before it is first defined.
Third, and group permissions
And group permissions
Login, logout and login restrictions:
log in
In use authenticate
after verification, if the verification is passed. Then returns an user
object to get the user
object, you can use django.contrib.auth.login
to log on. Sample code is as follows:
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active: login(request, user)
Logout:
Cancellation, or Log. We can django.contrib.auth.logout
be realized. He will clean out the user's session
data.
Login restrictions:
Sometimes, a view function is required after login to access. Then we can django.contrib.auth.decorators.login_required
to achieve a decorator. Sample code is as follows:
from django.contrib.auth.decorators import login_required
# 在验证失败后,会跳转到/accounts/login/这个url页面
@login_required(login_url='/accounts/login/')
def my_view(request): pass
Permissions:
Django
Built-in function rights. His authority is said to be the model for the table or level. For example, data on whether a model can be CRUD operations. He could not for the data level, such as on a table in certain pieces of data can be CRUD operations (If you want to achieve the level of data, consider using django-guardian
). After you create a model for this model there are three default permissions are add / delete / change /. Can execute complete migrate
command, view the database of auth_permission
all the permissions table.
Which codename
represents the name of the authority. name
It indicates the role of this authority.
Add permissions by defining the model:
If we want to add new privileges, such as permission to view a model, then we can define the model when Meta
well defined. Sample code is as follows:
class Article(models.Model):
title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) class Meta: permissions = ( ('view_article','can view article'), )
Add permissions by the code:
Permissions are django.contrib.auth.Permission
examples. This model contains three fields name
, codename
and content_type
wherein the content_type
representation that permission
is belongs app
to which under models
. With Permission
permission to create the model code as follows:
from django.contrib.auth.models import Permission,ContentType
from .models import Article
content_type = ContentType.objects.get_for_model(Article)
permission = Permission.objects.create(name='可以编辑的权限',codename='edit_article',content_type=content_type)
User and rights management:
Authority itself is only a data, and the user must bind, can play a role. User
Management between model and permissions can be managed in the following ways:
myuser.user_permissions.set(permission_list)
: Given directly to a list of permissions.myuser.user_permissions.add(permission,permission,...)
: One to add permissions.myuser.user_permissions.remove(permission,permission,...)
: Delete one by one authority.myuser.user_permissions.clear()
: Clear permission.myuser.has_perm('<app_name>.<codename>')
: To determine whether it has certain privileges. Rights argument is a string, the format isapp_name.codename
.myuser.get_all_permissons()
: Get all the permissions.
Permissions limited decorator:
Use django.contrib.auth.decorators.permission_required
can be very easy to check whether the user has the authority, if you have, then you can enter to view the specified function, if you do not have, it will report a 400
error. Sample code is as follows:
from django.contrib.auth.decorators import permission_required
@permission_required('front.view_article')
def my_view(request): pass
Grouping:
There are a lot of authority, there is a minimum of three permissions model, if some users have the same privileges, then repeat every time added. This time group can help us solve this problem, we can classify some rights, then added to a packet, and then later add the user needs to give these rights to the group, the management is better a. We are using the packet django.contrib.auth.models.Group
model, each user group owned id
and name
two fields, the model is mapped to a database auth_group
table.
Grouping operations:
Group.object.create(group_name)
: Create a grouping.-
group.permissions
: Permissions on a packet. Many relationship.group.permissions.add
: Add permissions.group.permissions.remove
: Remove permissions.group.permissions.clear
: Clear all permissions.user.get_group_permissions()
: Get Permissions groups the user belongs.
-
user.groups
: All packets on a user. Many relationship.
Usage rights in the template:
In the settings.TEMPLATES.OPTIONS.context_processors
case, because adding a django.contrib.auth.context_processors.auth
context processor, so the template can be directly perms
all rights to acquire users. Sample code is as follows: