Yii2 set up the background and implement RBAC rights control Complete example tutorial, yii2rbac_php Tutorial

Source: Internet
Author: User
Tags yii

Yii2 set up the background and implement RBAC rights control Complete example tutorial, Yii2rbac


1, installation Yii2

Not installed please refer to the YII2 history of the simplest installation tutorial, no one

Installed please continue to see the next steps

2. Configuration database

2.1 Configuration Database

Modify common/config/main-local.php The local database in the actual project is often inconsistent with the online database.

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

The MySQL database we use here is configured as follows


Of course, the information above the red circle needs to be manually modified by you, if it is a coincidence with me, then there is no need to modify the

2.2 Create User Data table, we want to implement background login

Description: The user table and the menu table can be created by referring to the SQL in the component yii2-admin that we downloaded later, the specific directory is located in

Vendor\mdmsoft\yii2-admin\migrations\schema-mysql.sqlcreate TABLE ' user ' (' id ' int (one) ' Not NULL auto_increment COMMENT  ' Self-increment id ', ' username ' varchar (255) NOT null COMMENT ' username ', ' auth_key ' varchar (+) ' NOT null COMMENT ' Auto login key ', ' Password_hash ' varchar (255) Not NULL COMMENT ' encrypted password ', ' password_reset_token ' varchar (255) DEFAULT NULL COMMENT ' Reset password token ', ' email ' varch AR (255) NOT NULL COMMENT ' mailbox ', ' role ' smallint (6) NOT null DEFAULT ' COMMENT ' role class ', ' status ' smallint (6) NOT NULL DEFA  ULT ' COMMENT ' state ', ' created_at ' int (one) not null COMMENT ' creation time ', ' updated_at ' int (one) NOT null COMMENT ' update Time ', PRIMARY KEY (' id ')) engine=innodb auto_increment=0 DEFAULT charset=utf8 comment= ' user table ';

2.3 Visit frontend site, register a user first

After successful registration, the top right corner will show the status of the login, we will use the registered users later

Next we'll start configuring the background template.

3. Render the background template with Adminlte

Background templates We use Adminlte (backend theme for Yii2 Framework)

Slot: Adminlte is a fully responsive administrative template. Easy-to-customize templates based on BOOTSTRAP3 framework. Suitable for a wide range of screen resolutions, from small mobile devices to large desktops.

Several pages are built-in, including dashboards, mailboxes, calendars, lock screens, login and registration, 404 errors, 500 errors, and more.

3.1 Installing Adminlte

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

Open the link above and follow the procedure to install it

Here I briefly outline my own installation steps, after CD advanced,

Because it's a Mac, it's composer to install it directly.

Composer require dmstr/yii2-adminlte-asset "2.*"

After successful installation, there will be several folders under the vendor directory, as follows

3.2 YII2 Configuration Integration Adminlte, build handsome on the background of the grade

Below we configure under backend/config/main.php first preview the effect, small heart catch nasty bar not hurry to taste the results

' components ' + = [' view ' = ' theme ' + [' pathmap ' = ' + ' @app/views ' and ' + ' @vendor/dmstr/yii2-adminlte-asset/ Example-views/yiisoft/yii2-app '], [],],

Nice, the page looks much more instantly.

The problem is, we are in the components of a separate configuration of the theme, so that later to modify the layout file what is very inconvenient to drop, below we copy the file down to cover the Yii's own layout.

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

Overwrite lauouts and site corresponding files in backend/views/directory

After overwriting, remember to block out the configuration items of the following view

To this, the background template construction is over, si not si very happy

4, below we use yii RBAC to achieve the background control of permissions

4.1 We first configure the next short route

The compontents of the backend/config/main.php file plus the following configuration

' Urlmanager ' = [//used to indicate whether Urlmanager is enabled for URL beautification, known as the path format URL in Yii1.1, or renamed in Yii2.0. Not enabled by default. But in the actual use, especially the product environment, generally will be enabled. ' Enableprettyurl ' + true,//whether strict parsing is enabled, such as enabling strict parsing, requires that the current request should match at least 1 routing rules,//otherwise it is considered an invalid route. This option is only valid if Enableprettyurl is enabled. ' Enablestrictparsing ' = false,//whether the portal script is displayed in the URL. is a further complement to the beautification function. ' Showscriptname ' = false,//specifies a suffix that is appended to the URL, such as. html. Valid only when Enableprettyurl is enabled. ' Suffix ' = ', ' rules ' and ' = '
 
  
   
  /
  
   
    
   ' = '
   
    
     
    /view ', '
    
     
      
     /' = > "
     
      
       
      /"],],
     
      
    
     
   
    
  
   
 
  

Next, create the. htaccess file below the root of the project Backend/web, and add the following, this file you can not create, it seems that really need to hone the training OH

Options +followsymlinksindexignore */*rewriteengine on# If a directory or a file exists, use it directlyrewritecond%{requ Est_filename}!-frewritecond%{request_filename}!-d# otherwise forward it to index.phprewriterule. index.php

Of course, your Apache has to turn on the rewrite module.

Below we visit under the GII module test

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

The checksum is possible.

4.2 Creating the data tables required for permission control

Of course, these yii2 are ready for us.

Open a. vendor/yiisoft/yii2/rbac/migrations/schema-mysql.sql file, create a data table in sequence

' Auth_assignment '; ' auth_item_child '; ' Auth_item '; ' Auth_rule ';

Additional Menus menu table, need to create their own

Description: The User table and menu table creation can refer to Vendor\mdmsoft\yii2-admin\migrations\schema-mysql.sql

CREATE TABLE ' menu ' (' id ' int (one) not null auto_increment, ' name ' varchar (+) ' NOT NULL, ' parent ' int (one) ' DEFAULT NULL, ' Route ' varchar ' default NULL, ' order ' int (one) 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=inno DB DEFAULT Charset=utf8

4.3 Download and install Yii2-admin

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

Follow the steps step by step installation, with Adminlte installation

We'll see the Mdmsoft directory below the vendor directory.

4.4 Permissions Configuration

Open backend/config/main.php Modify Configuration

' Modules ' = [' admin ' = ' = ' class ' = ' Mdm\admin\module ',], ' aliases ' and ' [' @mdm/admin ' = ' and ' @vendor/MDMS Oft/yii2-admin ',],//here must add the AuthManager configuration item ' components ' and the [...] add AuthManager component to the//components array, There are Phpmanager and Dbmanager two ways,//phpmanager to save the permission relationship in the file, where the use of the Dbmanager method, the permission relationship is saved in the database. ' AuthManager ' = [' class ' = ' Yii\rbac\dbmanager ', ' defaultroles ' = ' [' Guest '], ', ...],

4.5 Our access under the Permissions module check how the effect

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

Well, the interface is some, the following we speed up the pace of acceptance under our authority this piece in the end or not?

In general, this step is OK. The back can feel the ability to add routes to assign permissions.

Below we add the permission column on the left menu, the code can be copied directly, placed in

Within

 
  
  
  • Permission control
    • Administrator
      • Background users
        • Routing
        • Permissions
        • Role
        • Distribution
        • Menu

Let's look at it, so that we can operate on the privilege very conveniently.

In this way, our access control is basically over, and the permissions need to be explained:

You should add a route first, then add a permission name, and then assign individual permissions to the role or individual.

5, how to use the menu to control menus?

in 4.5 steps we directly write UL Li's way to the left side of the menu to operate, it is also possible to achieve through the menu to control the permission to drop.

But, as a non-convenient operation, and to increase the modification of what things have to need us to modify the program implementation, this is also TTM inconvenient. Fortunately, we have a wonderful family, DDV kill kill.

Well, it's a long way off. Think carefully, is not the 123456 tables we created and a menu table is not used to the Nan? How do you use the goods? Come on, let's get back to the chase.

Preferred, we visit/admin/menu/index add a few first-class menu, let's call first Level 1, Level 2, Level 3 bar, oh yes, forget to add the route, how to do it, we visit the/admin/route/index to move the left side of the route to the right, Otherwise, creating a new menu above will fail. When creating a menu, [map] [data] we're not filling it out.

After the addition, we open the layout file Left.php,use two class files, respectively, Yii\bootstrap\nav and Mdm\admin\components\menuhelper;

The operation of getting permission Menuhelper::getassignedmenu all done for us.

OK, let's delete the 4.5 added Sidebar-menu menu and add the following code to try it out

Echo nav::widget ([' encodelabels ' = False, ' options ' = [' class ' = ' Sidebar-menu '], ' items ' and ' = Menuhelper:: Getassignedmenu (Yii:: $app->user->id),]);

Now that the Menu control permission we are basically OK, now you can continue to add the menu to try the effect.

To this, our background and RBAC control can be said to be very perfect, if you are in the process of trying to encounter any problems, the following message is good, we share the discussion.

Related reading:

YII2 RBAC Permissions Control Menu Example Tutorial

http://www.bkjia.com/PHPjc/1123824.html www.bkjia.com true http://www.bkjia.com/PHPjc/1123824.html techarticle Yii2 set up the background and implement RBAC rights control Complete Example tutorial, Yii2rbac 1, installation Yii2 not installed please refer to YII2 History of the simplest installation tutorial, no one has been installed please continue to see ...

  • Related Article

    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.