Django's authentication and authorization

I. Overview of authentication and authorization

DjangoThere is a built-in authorization system. He used to process user, group, and permission-based cookieconversation systems. DjangoAuthorization 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. DjangoBuilt-in permissions system include the following:

  1. user.
  2. Authority.
  3. Grouping.
  4. You can configure a password hashing system.
  5. A pluggable back office systems.

Use authorization system:

Once you have created a default in djangothe 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

  1. django.contrib.auth: Authorization framework includes a core, and most of the model definition.
  2. django.contrib.contenttypes: Content TypeThe system can be used to model and associated rights.

Middleware:

  1. SessionMiddleware: To manage session.
  2. AuthenticationMiddleware: Used to process the current sessionassociated with the user.

Second, the user object

User Model

UserModel is a core part of the framework. His full path is django.contrib.auth.models.User. The following for this Userto be a simple understanding of objects:

Field:

Built-in Usermodel has the following fields:

  1. 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!
  2. first_name: Crooked nuts first_name, in 30 characters or less. It can be empty.
  3. last_name: Crooked nuts last_name, in 150 characters or less. It can be empty.
  4. email:mailbox. It can be empty.
  5. password:password. After after the hash code.
  6. groups: Grouping. A user can belong to a plurality of packets, a packet may have multiple users. groupsThis field is with Groupthe relationship between a many to many.
  7. user_permissions: Permissions. A user can have multiple permission, a permission can be multiple users all use. And Permissionbelongs to a relationship of many to many.
  8. is_staff: Is it possible to enter adminthe site. Whether it is on behalf of employees.
  9. is_active: Whether it is available. For some of the data you want to delete the account, we set this value Falseon it, not really deleted from the database.
  10. is_superuser: Whether it is super administrator. If you are a super administrator, you have all the rights of the entire site.
  11. last_login: Time of the last login.
  12. date_joined: The time of account creation.

Basic Usage User Model:

Create a user:

By create_usercan 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 passwordfield, and by invoking the need set_passwordto 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:

DjangoThe verification system has helped us to achieve a login authentication function. Through django.contrib.auth.authenticatecan be realized. This method is only through usernameand passwordfor 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:

DjangoBuilt-in Useralthough 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 Djangoare 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 Personclass, inherited from him User, and in Metathe setting proxy=True, indicating that this is only Usera proxy model. He will not affect the original Userstructure 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 Userto get all the data in this model.

2. one foreign key:

If you are a user authentication method authenticateis no other requirement it is to use usernameand passwordto 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 UserExtensionmodel, and she and Userthe model one to one binding, after our new field is added to UserExtensionthe. And also wrote a signal processing method accepts save the model, as long as the Usercall savemethod, it will create a UserExtensionand Userbinding.

3. inherited from AbstractUser:

For authenticatenot satisfied and do not want to modify the original Usersome 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.Userthe parent class. For example, we want the original Userto add a base model on telephoneand schoolfields. 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 settingsthe configured AUTH_USER_MODEL=youapp.User.

Because this way undermines the original table structure User model, it must be the first time migratebefore it is first defined.

4. inherited from the AbstractBaseUsermodel:

If you want to modify the default authentication mode for the original and Userdo 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 Djangoonly recommended for better understanding. Proceed as follows:

  1. 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 passwordand last_loginare AbstractBaseUseralready adding Well, we inherited directly on it. Then we add the field we want. For example email, username, telephoneand so on. This can be achieved in the field you want. But because we rewrite User, so it should be possible simulation Usermodel:

    • USERNAME_FIELD: Used to describe Usera string model name of the field, as the unique identifier. If not modified, it will be used USERNAMEas a unique field.
    • REQUIRED_FIELDS: A list of field names, for when by createsuperusercreating 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.
  2. Redefined UserManager: We also need to define your own UserManager, because the default UserManagerused when creating the user is usernameand passwordthen we asked to be replaced telephone. 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) 
  3. In the new creation of Userthe model, also you need to settingsconfigure in. Configuration AUTH_USER_MODEL='appname.User'.

  4. How to use this custom model: for example, since we have a Articlemodel, you need to reference this foreign key Usermodel, it can be referenced in two ways.
    The first is directly Userimported 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 Userabstracts, use settings.AUTH_USER_MODELto 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)
  5. 注意Because this way undermines the original table structure User model, it must be the first time migratebefore it is first defined. 

Third, and group permissions

And group permissions

Login, logout and login restrictions:

log in

In use authenticateafter verification, if the verification is passed. Then returns an userobject to get the userobject, you can use django.contrib.auth.loginto 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.logoutbe realized. He will clean out the user's sessiondata.

Login restrictions:

Sometimes, a view function is required after login to access. Then we can django.contrib.auth.decorators.login_requiredto 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:

DjangoBuilt-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 migratecommand, view the database of auth_permissionall the permissions table.

Which codenamerepresents the name of the authority. nameIt 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 Metawell 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.Permissionexamples. This model contains three fields name, codenameand content_typewherein the content_typerepresentation that permissionis belongs appto which under models. With Permissionpermission 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. UserManagement between model and permissions can be managed in the following ways:

  1. myuser.user_permissions.set(permission_list): Given directly to a list of permissions.
  2. myuser.user_permissions.add(permission,permission,...): One to add permissions.
  3. myuser.user_permissions.remove(permission,permission,...): Delete one by one authority.
  4. myuser.user_permissions.clear(): Clear permission.
  5. myuser.has_perm('<app_name>.<codename>'): To determine whether it has certain privileges. Rights argument is a string, the format is app_name.codename.
  6. myuser.get_all_permissons(): Get all the permissions.

Permissions limited decorator:

Use django.contrib.auth.decorators.permission_requiredcan 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 400error. 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.Groupmodel, each user group owned idand nametwo fields, the model is mapped to a database auth_grouptable.

Grouping operations:

  1. Group.object.create(group_name): Create a grouping.
  2. 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.
  3. user.groups: All packets on a user. Many relationship.

Usage rights in the template:

In the settings.TEMPLATES.OPTIONS.context_processorscase, because adding a django.contrib.auth.context_processors.authcontext processor, so the template can be directly permsall rights to acquire users. Sample code is as follows:


Guess you like

Origin www.cnblogs.com/fisherbook/p/11068601.html