ThinkPHP 3.2 Implements Privilege Management Using RBAC

In ThinkPHP 3.2, RBAC is integrated to realize privilege management. The address of RBAC implementation class in the project is ThinkPHP/Librar/Org/Util/Rbac.class.php, which integrates the privilege management operation we need.

Table design

A total of four tables are provided in the Rbac.class.php file of thinkPHP Rbac, and one user table needs to be built by yourself.

Here's the sql I built for privileges

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 'Modular',
  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 Title',
  `status` TINYINT(1) DEFAULT '0' COMMENT 'State 0 disables 1 enablement',
  `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 level ID',
  `status` TINYINT(1) UNSIGNED DEFAULT NULL COMMENT 'State 0 disables 1 enablement',
  `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 'user 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 'user 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 'State 0 disables 1 enablement',
  PRIMARY KEY (`user_id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 COMMENT='User table';

2. Common configurations of privilege operations:

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

// Load the Extension Profile
'LOAD_EXT_CONFIG' => 'user',

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

<?php
/**
 * User Rights Profile
 */
return array(
    // Is Certification Needed
    'USER_AUTH_ON' => true,
    // Authentication Type 1 Logon Authentication 2 Real-time Authentication
    'USER_AUTH_TYPE' => 1,
    // Background User Authentication SESSION Marker
    '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') denotes 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 Data Table Model
    'USER_AUTH_MODEL' => 'User',
    // Super Administrator's SESSSION tag
    'ADMIN_AUTH_KEY' => 'wjAdministrator',
    // Default Requirement Authentication Module
    'REQUIRE_AUTH_MODULE' => '',
    // Default Requires Authentication Operations
    'REQUIRE_AUTH_ACTION' => '',
    // Default No Authentication Module
    'NOT_AUTH_MODULE' => 'Public',
    // Default authentication-free operation
    'NOT_AUTH_ACTION' => '',
    // Whether to Open Visitor Authorized Access
    'GUEST_AUTH_ON' => false,
    // Visitor's User ID
    'GUEST_AUTH_ID' => 0,
    // SESSION tag for background username
    'BACK_LOGIN_NAME' => 'loginBackName',
    // SESSSION tags for background roles
    'BACK_USER_ROLE' => 'bakcUserRole',
    // SESSSION tag for background role ID
    'BACK_ROLE_ID' => 'backRoleId',
    // SESSION tag for background user login time
    'BACK_ONLINE_TIME' => 'backOnlineTime',
    // Backstage online interval in minutes
    'ONLINE_INTERVAL' => 180,
    //Login-out URL
    'LOGOUT_URL' => '/test',
);

3. Common methods of privilege operation:

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

Cache permission list. This method can pass null values on the premise that 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()

Determine whether user-accessed modules and methods require privilege authentication

3: Rbac::AccessDecision()

Whether the user has access rights or not is checked to see if 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. Return flase if there is an indication of permission

4: Rbac::checkLogin();

Judge whether the user is logged in or not, and jump to the specified path if not logged in

5: Rbac::getAccessList($authId)

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

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

MoDEL returns an array containing the user's information, using USER_AUTH_MODEL in the configuration item if the model value is not passed

Fourth: Simple implementation examples of authority management:

1: Log in:

//Get the passed username and password
$username = I('post.username');
$password = I('post.password');
//Generating 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('No account exists');
}
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');
}
//SESSSION tag for background role ID
session(C('BACK_ROLE_ID'), $role['id']);
//SESSSION tags for background roles
session(C('BACK_USER_ROLE'), $role['name']);
//Background User Authentication SESSION Marker
session(C('USER_AUTH_KEY'), $authInfo['user_id']);
//SESSION tag for background username
session(C('BACK_LOGIN_NAME'), $authInfo['username']);
//SESSION tag for background user login time
session(C('BACK_ONLINE_TIME'), time());
//Determine whether the user role is a super administrator
if ($role['id'] == '1') {
    //Super Administrator sets the Super Administrator's SESSSION tag to true
    session(C('ADMIN_AUTH_KEY'), true);
}
// Cache access rights
Rbac::saveAccessList();
$this->success('Successful login', U('Index/index'));

2: Authorization verification after successful login:

//Verify logon
Rbac::checkLogin();
// User Rights Check
if (Rbac::checkAccess() && !Rbac::AccessDecision()) {
    // No privilege to 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 Visitor Visits
        }
        // Prompt error message
        $this->error(L('_VALID_ACCESS_'));
    }
}
//Automatic logout function to determine whether the SESSION tag of background user logon time has 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('Log in again if timeout occurs', U('Login/index'));
} else {
    session(C('BACK_ONLINE_TIME'), time());
}

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

Tags: PHP Session Database SQL

Posted on Mon, 26 Aug 2019 00:16:34 -0700 by multe-media