thinkPHP3.2 Implementation of Privilege Management Using RBAC

  • 2021-12-19 06:21:25
  • OfStack

In thinkphp3.2, we integrate RBAC to realize privilege management, and the address of RBAC implementation class in the project is: ThinkPHP/Librar/Org/Util/Rbac. class. php, which integrates the privilege management operations we need

1: Table design

In thinkPHP, Rbac, Rbac. class. php file 1 provides a total of 4 tables, and there is a user table that you need to build by yourself

The following is the sql related to permissions that I built

Where wj_ is the table prefix, change it to the table prefix in your project

1: Permission table:


CREATE TABLE IF NOT EXISTS `wj_access` (
 `role_id` SMALLINT(6) UNSIGNED NOT NULL COMMENT ' Role ID',
 `node_id` SMALLINT(6) UNSIGNED NOT NULL COMMENT ' Node ID',
 `level` TINYINT(1) NOT NULL COMMENT ' Depth ',
 `module` VARCHAR(50) DEFAULT NULL COMMENT ' Module ',
 KEY `groupId` (`role_id`),
 KEY `nodeId` (`node_id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 COMMENT=' Permission table ';

2: Node table:


CREATE TABLE IF NOT EXISTS `wj_node` (
 `id` SMALLINT(6) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT ' Node ID',
 `name` VARCHAR(20) NOT NULL COMMENT ' Node name ',
 `title` VARCHAR(50) DEFAULT NULL COMMENT ' Node header ',
 `status` TINYINT(1) DEFAULT '0' COMMENT ' Status  0 Disable  1 Enable ',
 `remark` VARCHAR(255) DEFAULT NULL COMMENT ' Describe ',
 `sort` SMALLINT(6) UNSIGNED DEFAULT NULL COMMENT ' Sort ',
 `pid` SMALLINT(6) UNSIGNED NOT NULL COMMENT ' Parent node ',
 `level` TINYINT(1) UNSIGNED NOT NULL COMMENT ' Depth ',
 PRIMARY KEY (`id`),
 KEY `level` (`level`),
 KEY `pid` (`pid`),
 KEY `status` (`status`),
 KEY `name` (`name`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 COMMENT=' Node table ';

3: User role table:


CREATE TABLE IF NOT EXISTS `wj_role` (
 `id` SMALLINT(6) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT ' Role ID',
 `name` VARCHAR(20) NOT NULL COMMENT ' Role name ',
 `pid` SMALLINT(6) DEFAULT NULL ' Parent ID',
 `status` TINYINT(1) UNSIGNED DEFAULT NULL COMMENT ' Status  0 Disable  1 Enable ',
 `remark` VARCHAR(255) DEFAULT NULL COMMENT ' Remarks ',
 PRIMARY KEY (`id`),
 KEY `pid` (`pid`),
 KEY `status` (`status`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 COMMENT=' User role table ';

4: User Role Association Table:


CREATE TABLE IF NOT EXISTS `wj_role_user` (
 `role_id` MEDIUMINT(9) UNSIGNED DEFAULT NULL COMMENT ' Role ID',
 `user_id` CHAR(32) DEFAULT NULL COMMENT ' Users ID',
 KEY `group_id` (`role_id`),
 KEY `user_id` (`user_id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 COMMENT=' User role association table ';

5: User table:


CREATE TABLE IF NOT EXISTS `wj_user` (
 `user_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT ' Users ID',
 `username` VARCHAR(50) NOT NULL COMMENT ' User name ',
 `password` VARCHAR(100) NOT NULL COMMENT ' Password ',
 `create_time` INT(10) DEFAULT NULL COMMENT ' Creation time ',
 `update_time` INT(10) DEFAULT NULL COMMENT ' Update time ',
 `status` INT(1) DEFAULT NULL COMMENT ' Status  0 Disable  1 Enable ',
 PRIMARY KEY (`user_id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 COMMENT=' User table ';

2: Common configurations for permission operations:

You can add to the array of config. php files:


//  Load Extended Configuration File 
'LOAD_EXT_CONFIG' => 'user',

In this way, we can place all our permission configurations in the user. php file at the same level of config. php, and the user. php file is configured as follows:


<?php
/**
 *  User rights profile 
 */
return array(
  //  Whether certification is required 
  'USER_AUTH_ON' => true,
  //  Type of authentication  1  Login authentication  2  Real-time authentication 
  'USER_AUTH_TYPE' => 1,
  //  Background user authentication SESSION Mark 
  'USER_AUTH_KEY' => 'wjAuthId',
  //  Default authentication gateway 
  'USER_AUTH_GATEWAY' => '?m=Admin&c=Login&a=index',
  // RBAC_DB_DSN  Database connection DSN
  //  Role table name ,C('DB_PREFIX') Presentation prefix 
  'RBAC_ROLE_TABLE' => C('DB_PREFIX') . 'role',
  //  User role association table name 
  'RBAC_USER_TABLE' => C('DB_PREFIX') . 'role_user',
  //  Permission table name 
  'RBAC_ACCESS_TABLE' => C('DB_PREFIX') . 'access',
  //  Node table name 
  'RBAC_NODE_TABLE' => C('DB_PREFIX') . 'node',
  //  Default validation datasheet model 
  'USER_AUTH_MODEL' => 'User',
  //  Super administrator's SESSION Mark 
  'ADMIN_AUTH_KEY' => 'wjAdministrator',
  //  Authentication module is required by default 
  'REQUIRE_AUTH_MODULE' => '',
  //  Authentication action is required by default 
  'REQUIRE_AUTH_ACTION' => '',
  //  No authentication module is required by default 
  'NOT_AUTH_MODULE' => 'Public',
  //  No authentication operation is required by default 
  'NOT_AUTH_ACTION' => '',
  //  Do you want to turn on authorized visitor access 
  'GUEST_AUTH_ON' => false,
  //  Users of tourists ID
  'GUEST_AUTH_ID' => 0,
  //  Object of the background user name SESSION Mark 
  'BACK_LOGIN_NAME' => 'loginBackName',
  //  Background role SESSION Mark 
  'BACK_USER_ROLE' => 'bakcUserRole',
  //  Backstage role ID Adj. SESSION Mark 
  'BACK_ROLE_ID' => 'backRoleId',
  //  Object of the login time of the background user SESSION Mark 
  'BACK_ONLINE_TIME' => 'backOnlineTime',
  //  Background online interval time , In minutes 
  'ONLINE_INTERVAL' => 180,
  // Log out of the login URL
  'LOGOUT_URL' => '/test',
);

3: Common methods of permission operation:

1: Rbac:: saveAccessList ($authId=null);

Cache permission list. This method can pass a null value only if you save the user's id in $_SESSION [C ('USER_AUTH_KEY')] when the user logs in, and then save the permissions of the user's corresponding role in $_SESSION ['_ ACCESS_LIST']

2: Rbac:: checkAccess ()

Judge whether the module and method accessed by the user need authority authentication

3: Rbac:: AccessDecision ()

Whether the user has access rights, that is, whether the current project module operation is in the $_SESSION ['_ACCESS_LIST'] array, that is, whether the $_SESSION '_ACCESS_LIST' 'Current controller' exists in the $_SESSION ['_ACCESS_LIST'] array. If it exists, it means it has permission otherwise it returns flase

4: Rbac:: checkLogin ();

Judge whether the user logs in or not, if not, jump to the specified path

5: Rbac:: getAccessList ($authId)

Returns the value of the permission list $_SESSION ['_ACCESS_LIST'] by querying the database

6: Rbac:: authenticate ($map, $model= '')

The MODEL return array passed into the query user's criteria and user table contains the user's information, using USER_AUTH_MODEL in the configuration item if the model value is not passed

4: Simple implementation example of permission management:

1: Login:


// Gets the user name and password passed 
$username = I('post.username');
$password = I('post.password');
// Generate authentication conditions 
$map = array();
$map['username'] = $username;
$map['status'] = array('eq', 1);
// Determine whether this user exists 
$authInfo = Rbac::authenticate($map);
if (!$authInfo) {
  $this->error(' The account number does not exist ');
}
if ($authInfo['password'] != md5($password)) {
  $this->error(' Password error ');
}
$user_id = $authInfo['user_id'];
$role_user = new Model();
$role = $role_user->Table(C("RBAC_USER_TABLE"))->alias("user")->where("user_id=" . $user_id)->join(C("RBAC_ROLE_TABLE") . " as role ON role.id=user.role_id")->field("id,name")->find();
if (empty($role)) {
  $this->error(' This user has no corresponding role , Unable to log in ');
}
// Backstage role ID Adj. SESSION Mark 
session(C('BACK_ROLE_ID'), $role['id']);
// Background role SESSION Mark 
session(C('BACK_USER_ROLE'), $role['name']);
// Background user authentication SESSION Mark 
session(C('USER_AUTH_KEY'), $authInfo['user_id']);
// Object of the background user name SESSION Mark 
session(C('BACK_LOGIN_NAME'), $authInfo['username']);
// Object of the login time of the background user SESSION Mark 
session(C('BACK_ONLINE_TIME'), time());
// Determine whether the user role is super administrator 
if ($role['id'] == '1') {
  // The super administrator will set the super administrator's SESSION Tag is set to true
  session(C('ADMIN_AUTH_KEY'), true);
}
//  Cache access rights 
Rbac::saveAccessList();
$this->success(' Login Successful ', U('Index/index'));

2: Permission verification after successful login:


// Verify login 
Rbac::checkLogin();
//  User rights check 
if (Rbac::checkAccess() && !Rbac::AccessDecision()) {
  //  No permissions   Clear login session  And throw an error 
  if (C('RBAC_ERROR_PAGE')) {
    //  Define Permission Error Page 
    redirect(C('RBAC_ERROR_PAGE'));
  } else {
    if (C('GUEST_AUTH_ON')) {
      // Open a tourist visit 
    }
    //  Prompt error message 
    $this->error(L('_VALID_ACCESS_'));
  }
}
// Automatic exit function to judge the login time of background users SESSION Whether the flag timed out 
if (session(C('BACK_ONLINE_TIME')) + C('ONLINE_INTERVAL') * 60 < time()) {
  if (session('?' . C('USER_AUTH_KEY'))) {
    session('[destroy]');
    if (isset($_COOKIE[session_name()])) {
      setcookie(session_name(), '', time() - 3600, '/');
    }
    session_destroy();
  }
  $this->error(' Please log in again after timeout ', U('Login/index'));
} else {
  session(C('BACK_ONLINE_TIME'), time());
}

According to the above, the authority management of user role can be realized


Related articles: