RBAC(Role-Based Access Control)通過「用戶-角色-權限」三層映射,實現對後台功能(控制器/動作)的精細訪問控制。
| 表名 | 關鍵字段 | 說明 |
|---|---|---|
user | id, role_id | 用戶歸屬角色 |
role | role_id, access_ids | 角色擁有的權限 ID 集合(如 "1,3,5") |
access | access_id, controller, action | 具體權限點:控制器+方法 |
<?php
class BaseController extends Controller {
protected function _initialize() {
// 1. 獲取當前用戶角色
$roleId = session('role_id');
if (empty($roleId)) $this->redirect('/login');
// 2. 獲取角色授權的權限列表
$role = M('role')->find($roleId);
$accessIds = explode(',', $role['access_ids']); // 假設逗號分隔存儲
$accessList = M('access')->where(['access_id' => ['IN', $accessIds]])->select();
// 3. 構建允許訪問的「控制器/方法」鍵值集合
$allowed = [];
foreach ($accessList as $item) {
$allowed[] = strtolower($item['controller'] . '/' . $item['action']);
}
// 4. 獲取當前請求路由
$current = strtolower(CONTROLLER_NAME . '/' . ACTION_NAME);
// 5. 權限判斷
if (!in_array($current, $allowed)) {
$this->error('無權限訪問', '/index');
}
}
}
role_id => [允許路由列表],避免每請求查庫。access 表增加 type 字段區分「精確匹配」與「控制器級通配」(如 admin/*)。if ($user->is_super) return true;{if auth_check('user/delete')}...{/if} 渲染操作按鈕。