Authorization Management System Design Scheme

Foreword: Permission design is a problem that 80% of programmers will encounter, such as application system permissions, database access permissions, approval permissions in official document circulation, file access permissions in the operating system, approval permissions for company internal documents, government In real life, authority is everywhere and all the time. What I want to introduce here is a design scheme about the access rights of documents for everyone to discuss, hoping to play a role in attracting ideas.
       Within the company, a series of physical documents such as contract documents and design drafts for a certain customer form a logical document, typically such as a series of database design ER diagrams, class diagrams, and object diagrams in application system design. Documents can be logically called design documents of an application system. When there are more than a few hundred similar documents, the company's internal document management depends on creating paper document cards to retrieve documents. At this time, an online document management system becomes the company's needs at this stage. Many inconveniences caused by too many documents.
       The main goal of the online document management system is to facilitate users to manage documents and communicate with each other, but not everyone can view or modify any document. Rights management becomes a pivotal issue here: those are my documents, what permissions do colleagues in the same department have on my documents, what permissions do other people have on my documents, what permissions do people in other departments have on my documents, Is it possible to have a specific person or a specific department have specific permissions on my document. This article provides a solution to these problems. Some necessary elements, such as user design and department design, are not discussed in this article. It is assumed that you have already designed it relatively well. The author discusses and solves these problems by referring to some ideas of UNIX authority design. Divided into two parts:
The first part discusses the types of permissions: For each document, you need to fill in the following document information, such as the name of the document, author, etc., and then add attachments. There are four types of operations on documents: download, delete, modify, and view. For example, if you need to download a file, you need to have the download permission, but you must first have the viewing permission. If you don’t have the viewing permission, you can’t download it. If you need to modify some information, including re-uploading the file, you need to have the modification permission. These 4 permissions can be replaced by four bits, 1 means permission, 0 means no permission, for example, the first bit is download, the second is delete, the third bit is modification, and the fourth bit is view , then 1111 has all the permissions, and 0000 means no permissions. Such binary bits can be stored in the database in hexadecimal. For example, if 0..A..F is used, the storage in the database is only one byte. If you need to add permissions, then add this permission in the high position. In the Integer class in Java, the shift operation can be conveniently performed. For the binary digit of the given permission, the & operation is performed on the corresponding bit. If the judgment result is greater than 0, you will know whether there is permission. For example, if 1010 and 0010 perform the & operation, if If the result is greater than 0, it means that there is permission to modify. If it is necessary to increase the authority, take out the original authority, perform an OR | operation on the corresponding authority bit, and then store it in. This is consistent with the Unix permission design.
The second part discusses how to authorize. Assume that the user has a unique ××× ID number, and each department has a ××× ID number. For a company with 1,000 employees, there are hundreds of departments, and their average ID number The length of can be assumed to be 3 bits. In the record of the document, a field needs to be added to fill in the number of the document owner (owner), so as to indicate who the document belongs to. At the same time, the department number (dept) of the owner is also added. If the same person has worked in two departments, his documents in different periods should belong to different departments. After these, there needs to be an authority field (ownerAuth) of the document owner, which stores 1 byte of authority information (assuming there are only four authorities). People in the same department often need to view or modify operations. In order to facilitate retrieval, the authority of the same department (deptAuth) needs to be added, which is also 1 byte, and anyone else has the authority (otherAuth) for the document. Suppose it is a Notifications, or document templates, require everyone to have read permissions, so this method is more appropriate. What if a person needs to be authorized? What if a department is authorized separately? There are two options here, 1. Add a table, which has a many-to-one relationship with the document table, so that a document can be authorized to multiple departments, or multiple people. 2. Add two fields, usersAuth, deptsAuth, note that there is an s before auth, which means storing the permissions of multiple people or departments. The stored content is ID number plus permission, such as 100:f, 101:A, Indicates that the user with ID number 100 has all the permissions of F, and so on. It can be seen that 6 bytes are required for the authorization of a single person or department, and the length of 1k fields can already authorize more than 170 objects separately. This is basically an operation. The limit of personnel, the operator will not be idle and bored to authorize one object to 170 people or departments one by one, which is a small probability event and can be ignored in practice. Among these two schemes, the author prefers the second one. The advantage is that the number of queries is small, and the disadvantage is that the number of authorized objects is limited. How to determine whether a user has specific permissions to a certain document, here you can set a priority search order according to your own usage, for example, to determine whether a user has read permissions to document A, you can go from ownerAuth->groupAuth-> The otherAuth->usersAuth->deptsAuth priority search and judgment can also be judged according to your own scheme. For otherAuth's more commonly used file systems, it may be more appropriate to put the otherAuth permission judgment first. There is no uniform standard for this.
The above is the author's thoughts on the design of document permissions. I was in a hurry, and I didn't carefully consider whether the sentences are smooth. If there is something unclear or incorrect, please advise.
-----------------------------------
 https://blog.51cto.com/tianli/227217

System Authority = Function Authority + Data Authority

1. Why do you need permission management?

        The problem of permissions in daily work is always with us. When a programmer newly joins a company, he needs to find someone to enable various permissions, such as network connection permissions, code download and submission permissions, monitoring platform login permissions, and operation platform query data. permissions and so on.

In many cases, we feel that so many complicated applications bring inconvenience to our work, and if we suddenly want to check some data and find that we have not applied for permission, we need to go through the approval process again, which will take a long time. Then why do you need such strict authority management?

For example, a payment company has an operation background, and the operation background can find all merchant information, legal representative information, transaction information and rate configuration information. If we give this information to every small partner of the company without screening , then anyone who runs the market can manipulate the merchant’s rate information. If one accidentally changes the rate, it will cause huge losses.

Another example is that the information of merchants is very confidential, and some partners with bad intentions take out this information and sell it to competitors of the merchant, which will cause serious adverse consequences to the merchant. Although doing so is the human fault of some individuals, if the information itself is not disclosed in the system, the occurrence of violations of law and discipline can be avoided to a large extent.

Generally speaking, ** rights management is an important guarantee for the company's data security. For different positions and levels, the data seen is different, and the restrictions on operating data are also different. **For example, information related to funds is only open to relevant positions in finance, and information related to configuration is only open to relevant positions in operations, so that each department and its functions can avoid many unnecessary security issues.

2.1 Authority design

        In terms of business classification, permissions can be divided into data viewing permissions, data modification permissions, etc., which correspond to page permissions, menu permissions, and button permissions in system design. Menus are also divided into first-level menus, second-level menus, and even third-level menus. Taking the left menu bar of the csdn article editing page as an example, there are two levels of menus. There are many buttons on the page corresponding to the menu. When designing, it is best to design the permissions into a tree structure, so that when applying for permissions, you can see the structure of the menu at a glance, and it is very clear which permissions are needed.

2.2 Why roles are needed

        After clarifying the permission structure, you need to think about how to assign permissions to users. When there are few users, you can assign them directly. One user can have multiple permissions, and one permission can be owned by multiple users. The user-permission model structure is as follows Shown:

         This model can satisfy the basic ability to assign permissions, but as the number of users grows, the disadvantages of this model are highlighted. Every user needs to assign permissions, which is a waste of time and energy for administrators, and users The messy correspondence with permissions will bring huge maintenance costs in the later stage. User-permission correspondence diagram:

        This correspondence is basically impossible to maintain when there are many users. In fact, many users need the same permissions for the same business module. In this case, can we use a third medium to assign the same permissions to this medium, and then associate the user with the medium, and the user will have media permissions. This is the classic RBAC model, where the medium is what we usually call a role.

2.3 Evolution of permission model

1 Basic RBAC model

        Once you have a role, you can assign permissions to the role. Users who need the same permission can be associated with the role. One permission can be assigned to multiple roles, one role can have multiple permissions, and the same user can be assigned multiple roles. A role can also correspond to multiple users, and the corresponding model is as follows:

        This is the classic RBAC model (role-based-access-control) , in which roles act as a bridge, connecting users and permissions. Each role can have multiple permissions, and each user can be assigned multiple roles. , so that the user has multiple permissions for multiple roles.

At the same time, because roles are used as a medium, the intricate interaction relationship is greatly reduced. For example, in a company with tens of thousands of people, only a few hundred roles may be needed, because many users need the same permissions. OK. The corresponding relationship diagram of this model is as follows:

         Users and roles, roles and permissions are all in a many-to-many relationship. This model is the most common permission management model, which saves a lot of permission maintenance costs. However, the actual business is ever-changing, and the permission management model also needs to be based on different Appropriate adjustments to the business model. For example, a company’s internal organizational structure is hierarchical. The higher the level, the greater the authority, because people with higher levels not only have the authority of their subordinates, but also have some additional authority in the second phase.

The RBAC model can assign different roles to people at different levels, and the corresponding roles with higher levels have more permissions. This processing method can solve the problem, but is there a better solution? The answer is definitely yes, which leads to RBAC model of role inheritance .

2.4 Introducing the RBAC model of user groups and the RBAC model of role restrictions

2.4.1 User Groups

        We created roles to solve the problems of cumbersome user assignment permissions and high maintenance costs for user-authority relationships when the number of users is large. Abstract a role, assign the permissions that need to be operated together to this role, and assign the role to the user, the user will have the permissions on the role, which avoids assigning permissions to users one by one and saves a lot of resources.

        Similarly, if a group of users need the same role, we also need to assign roles to users one by one. For example, a company has more than 500 people in the customer service department. One day, the R&D department developed a set of products for querying background data. Partners need to use it, but customer service has not given a unified role to all customer service partners before. At this time, it is necessary to add a new role, assign permissions to this role, and then assign roles to customer service personnel one by one. Sometimes you will find it very troublesome to add roles to 500 users one by one. But customer service personnel have common attributes, so we can create a user group, all customer service personnel belong to the customer service user group, assign roles to the customer service user group, and all users under this user group have the required permissions.

The model diagram after adding user groups to the RBAC model is as follows:

        Many friends will ask, what is the difference between user groups and roles? Simply put, a user group is a combination of a group of users, and a role is a bridge between users and permissions.  User groups combine users with the same attributes. For example, the development, product, and testing of the same project can be a user group. Employees in the same position in the same department can be a user group. A user group can be a rank, which can be A department can be people from different positions who work together.

Users can be grouped, and permissions can also be grouped. When there are too many permissions, the permissions of a module can be combined to form a permission group. The permission group also solves the problem of complex correspondence between permissions and roles.

For example, when we define permissions, first-level menus, second-level menus, and buttons can all be permissions. There are dozens of second-level menus under a first-level menu, and dozens of buttons under each second-level menu. At this time, we put It is also very troublesome to assign permissions to roles one by one. You can use the grouping method to group permissions, and then assign the divided groups to roles.

Grouping permissions is also a technical task. It is necessary to clarify the relationship between permissions. For example, in the payment operation background, we need to check various information, such as account data, order data, merchant data, etc. These query data are not in the A page, each page also has many buttons, we can combine these pages and the permissions corresponding to the buttons into a permission group and assign roles. The RBAC model after joining the permission group is as follows:

3. Model design: RBAC (Role-Based Access Control)

Universal "User Role Permissions" Platform Design - Zhihu

        RBAC (Role-Based Access Control) means that users are associated with roles and permissions. That is, a user has several roles, and each role has several permissions. In this way, an authorization model of "user-role-permission" is constructed. In this model, there is generally a many-to-many relationship between users and roles, and between roles and permissions.

2.1 account table (account)

        In our system, there will be a variety of login methods, such as mobile phone number, email address, ID number, and WeChat login. Therefore, this table is mainly used to record the information of each login method, but does not contain password information , because the same password will be used for various login methods. Each record is associated with a unique user record.

Account table (account) : only stores account-related information (such as password, registration source, registration IP, but does not include login account)

CREATE TABLE `account`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '账号ID',
  `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户ID',
  `open_code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '登录账号,如手机号等',
  `category` tinyint(1) NULL DEFAULT NULL COMMENT '账号类别',
  `created` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `creator` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人',
  `edited` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  `editor` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人',
  `deleted` double(1, 0) UNSIGNED ZEROFILL NULL DEFAULT 0 COMMENT '逻辑删除:0=未删除,1=已删除',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `idx_member_id`(`user_id`) USING BTREE COMMENT '普通索引',
  CONSTRAINT `account_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
)

2.2 User table (user)

        It is mainly used to record the user's basic information and password information. Among them, the disabled state (state) is mainly used in the background management to control illegal users to use the system; the password salt (salt) is used to add a unique lock to each user's login password, even if the company's encrypted public key is leaked, it cannot be locked. It will not cause the password disclosure of all users.

User information table (user) : only store basic user information (excluding passwords)

CREATE TABLE `user`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `state` tinyint(1) NULL DEFAULT NULL COMMENT '用户状态:0=正常,1=禁用',
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
  `head_img_url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '头像图片地址',
  `mobile` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '手机号码',
  `salt` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码加盐',
  `password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '登录密码',
  `created` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `creator` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人',
  `edited` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  `editor` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '修改人',
  `deleted` tinyint(1) UNSIGNED ZEROFILL NULL DEFAULT 0 COMMENT '逻辑删除:0=未删除,1=已删除',
  PRIMARY KEY (`id`) USING BTREE
) 

 2.3 permission table (permission)

After having users, we hope that different users can operate and view different functions (such as pages, menus and buttons, etc.). Therefore, a table needs to be defined to store permission-related information. There is a parent-child relationship before including permissions. After the parent is assigned, it should have all child permissions. At the same time, the permission information will also be assigned to the front-end page for control, so a unique identifier (code) needs to be provided. Someone will ask if the id is not enough? Of course it is possible, but our ID is automatically generated, and each environment is different, and it is also different after regeneration, so a separate field is used for identification.

CREATE TABLE `permission`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '权限ID',
  `parent_id` bigint(20) NULL DEFAULT NULL COMMENT '所属父级权限ID',
  `code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '权限唯一CODE代码',
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '权限名称',
  `intro` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '权限介绍',
  `category` tinyint(1) NULL DEFAULT NULL COMMENT '权限类别',
  `uri` bigint(20) NULL DEFAULT NULL COMMENT 'URL规则',
  `created` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `creator` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人',
  `edited` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  `editor` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '修改人',
  `deleted` tinyint(1) UNSIGNED ZEROFILL NULL DEFAULT 0 COMMENT '逻辑删除:0=未删除,1=已删除',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `parent_id`(`parent_id`) USING BTREE COMMENT '父级权限ID',
  INDEX `code`(`code`) USING BTREE COMMENT '权限CODE代码'
)

2.4 role table (role)

In order to facilitate maintenance, we will group the records in the permission table, and assign some related permissions to the same group, which is called a role. The role of the role table is to aggregate scattered permissions, and then facilitate the unified processing of a related group (that is, small-scale batch processing). The addition of this table can be said to greatly reduce the above-mentioned difficult problem of maintenance.

CREATE TABLE `role`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '角色ID',
  `parent_id` bigint(20) NULL DEFAULT NULL COMMENT '所属父级角色ID',
  `code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '角色唯一CODE代码',
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '角色名称',
  `intro` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '角色介绍',
  `created` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `creator` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人',
  `edited` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  `editor` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '修改人',
  `deleted` tinyint(1) UNSIGNED ZEROFILL NULL DEFAULT 0 COMMENT '逻辑删除:0=未删除,1=已删除',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `parent_id`(`parent_id`) USING BTREE COMMENT '父级权限ID',
  INDEX `code`(`code`) USING BTREE COMMENT '权限CODE代码'
) 

 2.5 User-role table (user_role)

This table is mainly used to store which roles each user has. Typically, each user will only have a few roles, so the amount of data goes from 10 billion to 1 billion or less.

CREATE TABLE `user_role`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户ID',
  `role_id` bigint(20) NULL DEFAULT NULL COMMENT '角色ID',
  `created` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `creator` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人',
  `edited` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  `editor` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '修改人',
  `deleted` tinyint(1) UNSIGNED ZEROFILL NULL DEFAULT 0 COMMENT '逻辑删除:0=未删除,1=已删除',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `member_id`(`user_id`) USING BTREE COMMENT '用户ID',
  INDEX `role_id`(`role_id`) USING BTREE COMMENT '角色ID',
  CONSTRAINT `user_role_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `user_role_ibfk_2` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
)

2.6 Role - permission table (role_permission)

This table is used to define which permissions are available in each role group. The number of the table is less (basically within 10,000).

CREATE TABLE `role_permission`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `role_id` bigint(20) NULL DEFAULT NULL COMMENT '角色ID',
  `permission_id` bigint(20) NULL DEFAULT NULL COMMENT '权限ID',
  `created` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `creator` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人',
  `edited` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  `editor` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '修改人',
  `deleted` tinyint(1) UNSIGNED ZEROFILL NULL DEFAULT 0 COMMENT '逻辑删除:0=未删除,1=已删除',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `role_id`(`role_id`) USING BTREE COMMENT '角色ID',
  INDEX `permission_id`(`permission_id`) USING BTREE COMMENT '权限ID',
  CONSTRAINT `role_permission_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `role_permission_ibfk_2` FOREIGN KEY (`permission_id`) REFERENCES `permission` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
)

3.1 User group table (user_group)

Although the above-mentioned role table (role) is added, the data volume is reduced from 10 billion to 1 billion, but the data volume of 10 times is still a lot. And most users (subject users. Such as student systems, students are the subject) will be assigned the same role group. The difference between user group and role group:

  • Role group (role) : solves the grouping of permissions, reducing the repeated assignment of permissions
  • User group (user_group) : It solves the grouping of users and reduces the repeated authorization of users
CREATE TABLE `user_group`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `parent_id` bigint(20) NULL DEFAULT NULL COMMENT '所属父级用户组ID',
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户组名称',
  `code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户组CODE唯一代码',
  `intro` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户组介绍',
  `created` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `creator` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人',
  `edited` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  `editor` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '修改人',
  `deleted` tinyint(1) UNSIGNED ZEROFILL NULL DEFAULT 0 COMMENT '逻辑删除:0=未删除,1=已删除',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `parent_id`(`parent_id`) USING BTREE COMMENT '父级用户组ID',
  INDEX `code`(`code`) USING BTREE COMMENT '用户组CODE代码'
) 

 3.2 User Group - User Table (user_group_user)

This table is used to record which users belong to each user group.

CREATE TABLE `user_group_user`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID说',
  `user_group_id` bigint(20) NULL DEFAULT NULL COMMENT '用户组ID',
  `user_id` bigint(20) NULL DEFAULT NULL COMMENT '用户ID',
  `created` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `creator` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人',
  `edited` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  `editor` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '修改人',
  `deleted` tinyint(1) UNSIGNED ZEROFILL NULL DEFAULT 0 COMMENT '逻辑删除:0=未删除,1=已删除',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `member_group_id`(`user_group_id`) USING BTREE COMMENT '用户组ID',
  INDEX `member_id`(`user_id`) USING BTREE COMMENT '用户ID',
  CONSTRAINT `user_group_user_ibfk_1` FOREIGN KEY (`user_group_id`) REFERENCES `user_group` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `user_group_user_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) 

3.3 User group-role table (user_group_role)

This table is used to record which user roles each user group has.

CREATE TABLE `user_group_role`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `user_group_id` bigint(20) NULL DEFAULT NULL COMMENT '用户组ID',
  `role_id` bigint(20) NULL DEFAULT NULL COMMENT '角色ID',
  `created` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `creator` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人',
  `edited` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  `editor` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '修改人',
  `deleted` tinyint(1) UNSIGNED ZEROFILL NULL DEFAULT 0 COMMENT '逻辑删除:0=未删除,1=已删除',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `member_group_id`(`user_group_id`) USING BTREE COMMENT '用户组ID',
  INDEX `role_id`(`role_id`) USING BTREE COMMENT '角色ID',
  CONSTRAINT `user_group_role_ibfk_1` FOREIGN KEY (`user_group_id`) REFERENCES `user_group` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `user_group_role_ibfk_2` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) 

        The main users of each system basically occupy more than 90% of all users (systems that include both users and merchants, users and merchants are also subject users). Therefore, when each user registers, basically he only needs to assign a user group to which he belongs to complete the configuration of role permissions. After this processing, the amount of data will drop from 1 billion to more than 100 million. At the same time, the number of batch writes required for user registration is also reduced.

 User table (t_user)
user group table (t_group)
role table (t_role)
permission table (t_permission)
user table - user group (user_group)
user - role table (user_role) 
user group - role table (group_role)
role - permission table (role_permission )

3. Django: user authentication, authority management

         Permission is a mechanism that can restrict user behavior and control the content displayed on the page. A complete authority should include three elements: user, object and authority, that is, what user has what authority to what object.

Django's built-in permission mechanism is only for models, that is, if a user has change permissions for the Article model, then the user has modification permissions for all articles. If you want to implement permission management on a single object, you can use the third-party library guardian. This article will introduce the permission mechanism and guardian of the built-in "auth module" respectively.

1. Self-contained permission mechanism

The auth module is a standard permission management system provided by Django, which can provide user authentication, user group and permission management.

1.1 table structure

There are 6 database tables related to the auth module, namely

project

effect

Remark

auth_user.

User Info

auth_group

group information

Each group has two fields id and name

auth_user_groups

The relationship between user and group

auth_user_user_permissions

The relationship between user and permission

auth_permission

permissions

Each permission has id, name, 

content_type_id, codename four fields

auth_group_permissions

Correspondence between user groups and permissions

It is a more convenient way to use user groups to manage permissions. Group contains many-to-many field permissions

1.1 auth_user

The auth_user table maintains user information, the structure is as follows:

CREATE TABLE `auth_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `password` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
  `last_login` datetime(6) DEFAULT NULL,
  `is_superuser` tinyint(1) NOT NULL,
  `username` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
  `first_name` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  `last_name` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(254) COLLATE utf8mb4_unicode_ci NOT NULL,
  `is_staff` tinyint(1) NOT NULL,
  `is_active` tinyint(1) NOT NULL,
  `date_joined` datetime(6) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

1.2 auth_group  

The auth_group table has only two fields, id and name, and the structure is as follows:

CREATE TABLE `auth_group` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Through the auth_user_groups table, a many-to-many relationship is established between auth_group and auth_user, the structure is as follows:

auth_user_groups

CREATE TABLE `auth_user_groups` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `group_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `auth_user_groups_user_id_group_id_94350c0c_uniq` (`user_id`,`group_id`),
  KEY `auth_user_groups_group_id_97559544_fk_auth_group_id` (`group_id`),
  CONSTRAINT `auth_user_groups_group_id_97559544_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`),
  CONSTRAINT `auth_user_groups_user_id_6a12ed8b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

1.3 auth_permission: The table stores the permission information of the model.

CREATE TABLE `auth_permission` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `content_type_id` int(11) NOT NULL,
  `codename` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `auth_permission_content_type_id_codename_01ab375a_uniq` (`content_type_id`,`codename`),
  CONSTRAINT `auth_permission_content_type_id_2f476e4b_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

auth_group_permissions

Maintain the many-to-many relationship between auth_permission and auth_group

CREATE TABLE `auth_group_permissions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `group_id` int(11) NOT NULL,
  `permission_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `auth_group_permissions_group_id_permission_id_0cd325b0_uniq` (`group_id`,`permission_id`),
  KEY `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` (`permission_id`),
  CONSTRAINT `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`),
  CONSTRAINT `auth_group_permissions_group_id_b120cbf9_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

auth_user_user_permissions

Maintain the many-to-many relationship between auth_permission and auth_user

CREATE TABLE `auth_user_user_permissions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `permission_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `auth_user_user_permissions_user_id_permission_id_14a6b632_uniq` (`user_id`,`permission_id`),
  KEY `auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm` (`permission_id`),
  CONSTRAINT `auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`),
  CONSTRAINT `auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

The above three tables ensure the authority management from the auth module to the model level, that is, whether the user has the authority to add (add), change (change), and delete (delete) a certain data table.

If you need object-level permission management, you need to use a third-party library, eg  django-guardian .

Note: The content_type_id entry in the auth_permission table is the application of the django.contrib.contenttypes module.

2. Related methods and functions

  • authenticate(),User Authentication. If the authentication information is valid, a User object will be returned. void returns None
  • user.set_password(new_password), modify user password
  • login(HttpRequest, user), combined with the django.contrib.sessions module, attach session id and other information to authenticated users.
  • logout(request), logout user
  • @login_required The decorator will first check whether it is logged in through the session key, and logged-in users can perform operations normally, and non-logged-in users will be redirected to the location specified by login_url. If the login_url parameter is not specified, redirects to settings.LOGIN_URL.
  • user.has_perm, to check whether the user has permission to operate a certain model:
user.has_perm('blog.add_article')
user.has_perm('blog.change_article')
user.has_perm('blog.delete_article')
  • django.contrib.auth.middleware.AuthenticationMiddleware, add currently-logged-in user to  HttpRequestthe object's userproperties.
  • django.contrib.auth.context_processors.authAdd auth to the context of the template (context)
  • django.contrib.auth.password_validationA series of password strength checks are provided in .

Note: This test is only for command line operations  createsuperuser, changepasswordetc., and is invalid for model operations, such as  User.objects.create_user(), create_superuser()etc. (because these are developer operations, not user operations)

Guess you like

Origin blog.csdn.net/qq_22473611/article/details/126334276