django authentication and authorization system

0.5 Overview

Django has a built-in authorization system. He used to process user, group, permissions, and cookie-based session system. 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 and include the following aspects:

1 user.
2 . Permissions.
3 . Grouping.
4 . You can configure a password hashing system.
Background Management System 5. a pluggable.

Use the built-in system: default in after creating a django 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 Type systems can be used to model and associated rights. 
Middleware:
     1 SessionMiddleware:. To manage the session.
    2. AuthenticationMiddleware: the current user session and used to process the associated

1. about the nature of authentication and authorization

  Essentially the presence of user data in the database and the data submitted through forms up to do compared for equality. The role of certification is to determine the identity of the user, such as whether the company's employees, whether or not a registered user. The role of authority to determine what the user can do, such as whether a user can browse consulting fee, if the back-end system for the employees if so, whether you can modify edit some files.

2.django built-in verification system ----- auth

(1) authenticate (incoming user name and password to log the user to achieve, and verify a user returns after the success of the object)

(2) login (complete specific login process)

   This function takes a HttpRequest object, and a User object authenticated (verified by authenticate exclusive) This function is used to django framework of a session of authenticated users additional information on the session id. (In the face of response data modifications made in advance)

(3) logout (Log, essentially encapsulates the function, call the session flush () method, clear content)

3.User Object (user model is the core of the framework):

(1) is_authenticated (), to determine whether the user login (using the django of login_required decorators to operate, after the successful landing to return to the original page visits (core code decorator implemented)):

def  my_view(request):

    if  not  request.user.is_authenticated():
        return  redirect("%s?next=%s"%(settings.LOGIN_URL, request.path))

(2) create_user and create_superuser, need to pass yo-mail, user name and password parameters.

(3) checkpassword, setpassword (password in the database stored by the encrypted hash algorithm)

4.django custom User:

(1) using the proxy proxy mode; ------ ORM using proxy mode on the mode.

  Conditions: If you are on the field provided by Django, and verification methods are quite satisfactory, there is no need to change

  Application: By setting proxy = true to set the proxy mode, the application scene (set the black list), the advantage does not affect the principle of the user table, you can extend the functionality:

class Person(User):

    class Meta:
        proxy = True

    def get_blacklist(self):
        return self.objects.filter(is_active=False)       

  Follow-up can call get_blacklist () Gets blacklist.

(2) one using a foreign key;

  Conditions: For user authentication method authentica quite satisfactory, use authenticate to do the verification, but want to expand the field.

  Application: by providing one foreign key, there may not be common fields in the user table, in the extension field. I would like to achieve using a mobile phone number or by email to familiarize love you log in user authentication.

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                        

  Above using the semaphore mechanism, when the user performs the save model, it will create a UserExtension objects and bind. Problem: save the data you need to perform operations twice.

(3) inherited from AbstracUser

  Conditions: you want to modify authenticate authentication, add a field to the model without changing the original field to field by generating a new class that inherits User's parent.

from django.contrib.auth.models Import AbstractUser 

class the User (AbstractUser): 
    telephone = models.CharField (MAX_LENGTH =. 11, UNIQUE = True) 
    School = models.CharField (MAX_LENGTH = 100 )
     # Specify telephone as USERNAME_FIELD, after using the authenticate 
    # function verification time, it can be verified according to the telephone 
    # instead of the original username 
    USERNAME_FIELD = ' telephone ' 
    required_fields = []
     # redefined Manager object, using the telephone, and when creating the user's 
    # password, instead of using the username and password 
    objects = the 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)

Because of changes in the original User need to re-do the configuration settings file: AUTH_USER_MODEL = youapp.User. In addition, because this way, undermines the table structure, we need to first migrate before the first definition of a good in.

Otherwise conflict with the system's built-in User.

(4) inherited from Abstractbaseuser

Conditions: Modify authentication, and decided to make changes to the original field, delete some fields.

Application: inherited from AbstractBaseUser, can be defined and selected fields in their own way.

class the User (AbstractBaseUser, PermissionsMixin): 

    In Email = models.EmailField (UNIQUE = True) 
    username = models.CharField (MAX_LENGTH = 150 ) 
    Telephone = models.CharField (MAX_LENGTH =. 11, UNIQUE = True) 
    the is_active = models.BooleanField (default = True) 
    
    # for a string user name field model is described as a unique identifier, the default is 
    # username 
    USERNAME_FIELD = ' Telephone ' 
    prompted to create a user through createsuperuser management command of. 
    Required_fields = []
     # model management class assigned to the principle of the modified class, subsequent calls (using django specific knowledge of the Manager class) 
    Objects = UserManager()

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username     

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)                    

 After you create a new model class, you need to configure seettins good AUTH_USER_MODEL = 'appname.User'. If you want to follow-up call to User, by "settings.AUTH_USER_MODEL".

5. Permissions

Content_type field in the table is present on essentially permissions, each model has a recording field (permission) in the table are the model-level permissions to be limiting for the operating table. By associating user rights and permissions to determine the nature of that query the database to see if the user has a permission. If you have privileges to perform a view, no, you can not perform this view, the return message to the user to perform that view.

(1) add permissions to the user:

   Added by way of model objects:

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

  Examples of permissions are django.contrib.auth.Permission through. This model contains three fields, name, codename and content_type, which indicates that permission belongs content_type

Which models under which app.

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',con
tent_type=content_type)

(2) data itself is only a rights, permissions may be realized by the following binding methods:

1 myuser.user_permissions.set (permission_list):. Direct authority of a given list.
2 myuser.user_permissions.add (permission, permission, ...):. One add permissions.
3 myuser.user_permissions.remove (permission, permission, ...):. Delete one by one authority.
4 . Myuser.user_permissions.clear (): Clear permission.
Myuser.has_perm 5. The ( ' <APP_NAME> <Codename>. ' ): Determining whether it has a permission. Permissions parameter is a character 
string, the format is app_name.codename. 
6. myuser.get_all_permissons (): Get all the privileges

(3) Decoration permissions defined (using django.contrib.auth.decorators.permission_required can easily check whether the user has the authority, if you have, it can be specified into view function)

from django.contrib.auth.decorators import permission_required

    @permission_required('front.view_article')
    def my_view(request):
        ...

6. Packet

In order to facilitate the user batch management, use django.contrib.auth.models.Group model, each group has two fields id and name, the model is mapped auth_group database tables.

Classify some rights, then added to a packet , followed and then add the user needs to give these rights to the packet.

(1) User grouping operation:

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 (): Gets rights groups the user belongs. 
3. user.groups: all packets on a user. Many relationship.               

(2) using the template permissions ( in settings.TEMPLATES.OPTIONS.context_processors, because adding a django.contrib.auth.context_processors.auth context processor, can be passed directly in the template through perms to get all user permissions . )

{% if perms.front.add_article %}
    <a href='/article/add/'>添加文章</a>
{% endif %}

7. Summary:

  A good programmer should know not to repeat not only create the wheel, but should know how the wheels are made to understand the principle behind a function, be able to design their own wheels, this is an excellent programmer. The so-called analogy, to think from a designer's point of view. To know the code is just an expression of ending the problem, you can have your own means of expression.

  In django framework, the core model ORM, authorization and authentication system to operate based on substantially ORM model. An operation of the entire table in the database system essentially comprising several models (red box):

  

  The above model, store user information, group and group permissions and rights. For the operation of the model is defined by a corresponding operating method (essentially made it complain action statement to the database ORM) based on the model, when using the direct call packaged, the operation of the model formulation.

  By the above analysis, to understand the role auth authentication system, to facilitate the direct use, but for which the internal has a simple understanding of the principle, object-oriented features may be utilized, as extended for User model, the model can be expanded to the entire model. Even they can develop their own verification authorization system.

  Finally, attach the two articles is how to write your own flask system certification authority, if you are familiar with django authorization system, can write yourself a used, the use of the wheel in order to be able to create better wheels:

  Flask rights articles flask_principal

  flask Rights Management

8. Supplementary

django's permission is table level permissions, if in some special cases, row-level data need to be performed, how you can use django-guardian, refer to the following blog:

https://blog.csdn.net/scdxmoe/article/details/72678005

  

 

Guess you like

Origin www.cnblogs.com/znn041622/p/10991598.html