Yii2 is a case study of setting up a perfect background and implementing rbac permission control, yii2rbac

Source: Internet
Author: User

Yii2 is a case study of setting up a perfect background and implementing rbac permission control, yii2rbac

Author: White Wolf Source: www. manks. top/article/yii2_frame_rbac_template

The copyright of this article belongs to the author. You are welcome to repost this article, but you must keep this statement without the author's consent and provide the original article connection clearly on the article page. Otherwise, you will be entitled to pursue legal liability.

1. Install yii2

For information about uninstalled installation, see the simplest installation tutorial in yii2 history. None

For installed instances, continue with the next step.

2. Configure database 2.1 configure Database

Modifying the local database of the common/config/main-local.php project is often different from the online database,

Here we can configure to main-local.php, after the product is launched, we can use git or svn to ignore the main-local.php, online direct deployment.

The mysql database we use here is configured as follows:

Of course, you need to manually modify the above red circle information. If it is a coincidence that it is the same as mine, you don't have to modify it.

2.2 create a user data table. We will implement background login later.

(User table and menu table creation can refer to the components we download after the yii2-admin inside the SQL, the specific directory is located in)

Vendor \ mdmsoft \ yii2-admin \ migrations \ schema-mysql. SQL

 

Create table 'user' ('id' int (11) not null AUTO_INCREMENT COMMENT 'auto-incrementing id', 'username' varchar (255) not null comment 'username ', 'auth _ key' varchar (32) not null comment 'automatic logon key', 'password _ hash' varchar (255) not null comment 'encrypted password ', 'password _ reset_token' varchar (255) default null comment 'reset password token', 'email 'varchar (255) not null comment 'mailbox', 'role' smallint (6) not null default '10' comment' role level ', 'status' smallint (6) not null default '10' comment' status', 'created _ at' int (11) not null comment 'creation time', 'updated _ at' int (11) not null comment' update time', primary key ('id ')) ENGINE = InnoDB AUTO_INCREMENT = 0 default charset = utf8 COMMENT = 'user table ';
2.3 visit the frontend site and register a user

After successful registration, the login status will be displayed in the upper-right corner. We will use this registered user later.

Next, we will start to configure the background template.

3. Rendering background templates using AdminLTE

The background template uses AdminLTE (Backend theme for Yii2 Framework)

Insert one piece: AdminLTE is a full response management template. Templates are easy to customize Based on the Bootstrap3 framework. Suitable for multiple screen resolutions, from small mobile devices to large desktops.

Multiple built-in pages, including dashboard, mailbox, calendar, screen lock, logon and registration, 404 error, 500 error, and so on.

3.1 install AdminLTE

Https://github.com/dmstr/yii2-adminlte-asset

Open the above link and follow the steps to install

Here I will briefly describe my installation steps. After cd advanced,

 

Because it is mac, here the installation of composer directly on the line of composer require dmstr/yii2-adminlte-asset "2 .*"

After the installation is successful, there will be several more folders under the vendor directory, as shown below:

3.2 yii2 is integrated with AdminLTE to build a handsome back-end

Next we will configure backend/config/main. php to preview the effect first, and try the result quickly.

 

'components' => [      'view' => [        'theme' => [            'pathMap' => [                                '@app/views' => '@vendor/dmstr/yii2-adminlte-asset/example-views/yiisoft/yii2-app'                          ],        ],    ],],

Nice, the page looks much better.

The problem is that we configure theme separately in components, so it is inconvenient to modify the layout file in the future. Next we will copy the hidden file to overwrite the layout that comes with yii.

Copy the layouts and site under the vendor/dmstr/yii2-adminlte-asset/example-views/yiisoft/yii2-app directory

Overwrite the lauouts and site files in the backend/views/directory.

Overwrite and remember to block the view configuration items under components.

At this point, the creation of background templates has come to an end, and si is not very happy.

 

4. Use rbac of yii to implement backend permission control. 4.1 configure the short route first.

Add the following configuration to compontents In the backend/config/main. php file

 

'Urlmanager' => [// indicates whether URL beautification is enabled for urlManager. In Yii1.1, URL in path format is used. // Rename and beautify in Yii2.0. // Disabled by default. However, it is generally enabled in actual use, especially in the product environment. 'Enableprettyurl' => true, // whether strict resolution is enabled. If strict resolution is enabled, the current request must match at least one routing rule. // otherwise, the request is considered as an invalid route. // This option is only valid after enablePrettyUrl is enabled. 'Enablestrictparsing' => false, // indicates whether the script is displayed in the URL. Is a further supplement to the beautification function. 'Showscriptname' => false, // specifies a suffix after the URL, such as. html. Valid only when enablePrettyUrl is enabled. 'Suffix '=> '', 'rules' => [" <controller: \ w +>/<id: \ d +> "=>" <controller>/view "," <controller: \ w +>/<action: \ w +> "=>" <controller>/<action> "],],

Next, create the. htaccess file under the project's root directory backend/web and add the following content. You cannot create this file. It seems that you really need to hone your skills.

Options +FollowSymLinksIndexIgnore  */*RewriteEngine on# if a directory or a file exists, use it directlyRewriteCond  %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d# otherwise forward it to index.phpRewriteRule . index.php

Of course, you must enable the rewrite module for apache.

Next, let's test the gii module.

Http: // localhost/advanced/backend/web/gii

Verification is acceptable.

4.2 create a data table required for permission Control

Of course, yii2 is ready for us.

Open the vendor/yiisoft/yii2/rbac/migrations/schema-mysql. SQL file and create data tables in turn

'Auth _ assignment '; 'auth _ item_child'; 'auth _ item'; 'auth _ rule'; in addition, you need to create a menu table by yourself: to create a user TABLE and a menu TABLE, See vendor \ mdmsoft \ yii2-admin \ migrations \ schema-mysql.sqlCREATE TABLE 'menu '('id' int (11) not null AUTO_INCREMENT, 'name' varchar (128) not null, 'parent' int (11) default null, 'route 'varchar (256) default null, 'order' int (11) default null, 'data' text, primary key ('id'), KEY 'parent' ('parent'), CONSTRAINT 'menu _ ibfk_1 'foreign key ('parent ') REFERENCES 'menu '('id') on delete set null on update cascade) ENGINE = InnoDB default charset = utf8
4.3 download installation yii2-admin

Reference https://github.com/mdmsoft/yii2-admin

Follow the steps to install it step by step.

After the installation, we will see the mdmsoft directory under the vendor directory.

4.4 permission Configuration

Open backend/config/main. php to modify the configuration

 

'Modules' => ['admin' => ['class' => 'mdm \ admin \ module',],], & apos; & apos // The authManager configuration item 'components' must be added here => [... // Add the authManager component to the components array. There are two methods: PhpManager and DbManager. // PhpManager saves the permission relationship in the file. Here, DbManager is used, save the permission relationship to the database. 'authmanager' => ['class' => 'yii \ rbac \ dbmanager', 'defaultrole' => ['guest '],],...],
4.5 check the effect of the permission Module

Http: // localhost/advanced/backend/web/admin/route

Well, the interface is there. Can we speed up the acceptance of our permissions?

Generally, this step is OK. Later, you can find out how to add Route Assignment permissions.

Next, we add the permission column in the left menu. The code can be copied directly and placed in <section class = "sidebar"> </section>.

 

<Ul class = "sidebar-menu"> <li class = "treeview"> <a href = "#"> <I class = "fa-gears"> </I> <span> permission Control </span> <I class = "fa-angle-left pull-right"> </I> </a> <ul class = "treeview -menu "> <li class =" treeview "> <a href ="/admin "> administrator </a> <ul class =" treeview-menu "> <li> <a href = "/user"> <I class = "fa-circle-o"> </I> background user </a> </li> <li class =" treeview "> <a href ="/admin/role "> <I class =" fa-circle-o "> </I> permission <I class =" fa- angle-left pull-right "> </I> </a> <ul class =" treeview-menu "> <li> <a href ="/admin/route "> <I class = "fa-circle-o"> </I> routing </a> </li> <a href = "/admin/permission"> <I class = "fa-circle-o"> </I> permission </a> </li> <a href = "/admin/role"> <I class = "fa-circle-o"> </I> role </a> </li> <a href = "/admin/assignment"> <I class = "fa-circle-o"> </I> allocation </a> </li> <a href = "/admin/menu"> <I class = "fa-circle-o"> </I> menu </a> </li> </ul> </ li> </ul> </li> </ul>

As a result, it is very convenient for us to operate on permissions.

As a result, our permission control has come to an end. The following information is required for permission control:

You should first add a route, then add the permission name, and then assign permissions to roles or individuals independently.

5. How to Use menu to control menus?

In step 4.5, we directly write ul li to operate the menu on the left, which can also control permissions through menus. However, TTM is not convenient because it is inconvenient to operate and to add and modify things. Fortunately, our family has some tricks, such as "DDV" and "kill.

Well, it's a long journey. In retrospect, is there another menu table that we have created that has not been used in the first 123456 tables? How can this product be used? Come on, let's get back to the question.

First, visit/admin/menu/index to add several level-1 menus, for example, level 1, level 2, and level 3. Oh, I forgot to add a route. What's the problem, access/admin/route/index to move the route on the left to the right. Otherwise, the creation of the new menu will fail. When creating a menu, we do not enter [ing] [data] for the moment.

After adding the file, open the layout file left. php and use, which are yii \ bootstrap \ Nav and mdm \ admin \ components \ MenuHelper;

The MenuHelper: getAssignedMenu operation for obtaining permissions is complete for us.

OK. Let's Delete the sidebar-menu added by 4.5 and add the following code.

echo Nav::widget(    [        'encodeLabels' => false,        'options' => ['class' => 'sidebar-menu'],        'items' => MenuHelper::getAssignedMenu(Yii::$app->user->id),    ]);

Now the menu control permission is basically OK. Now you can continue to add the menu and try again.

At this point, our backend and rbac permission control can be said to be perfect. If you encounter any problems during your attempt, leave a message and let's discuss it together.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.