基于角色的访问控制(RBAC)实现权限管理功能
<?php
class RBACWithDatabase {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function addRole($role) {
$sql = "INSERT INTO roles (name) VALUES ('$role')";
$this->db->query($sql);
}
public function addPermission($permission) {
$sql = "INSERT INTO permissions (name) VALUES ('$permission')";
$this->db->query($sql);
}
public function assignPermissionToRole($role, $permission) {
$sql = "INSERT INTO role_permissions (role_id, permission_id) VALUES ((SELECT id FROM roles WHERE name = '$role'), (SELECT id FROM permissions WHERE name = '$permission'))";
$this->db->query($sql);
}
public function hasPermission($role, $permission) {
$sql = "SELECT COUNT(*) FROM role_permissions rp
INNER JOIN roles r ON rp.role_id = r.id
INNER JOIN permissions p ON rp.permission_id = p.id
WHERE r.name = '$role' AND p.name = '$permission'";
$result = $this->db->query($sql);
return $result->fetchColumn() > 0;
}
}
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
$rbac = new RBACWithDatabase($db);
// 添加角色
$rbac->addRole('admin');
$rbac->addRole('user');
// 添加权限
$rbac->addPermission('view_dashboard');
$rbac->addPermission('edit_posts');
// 为角色分配权限
$rbac->assignPermissionToRole('admin', 'view_dashboard');
$rbac->assignPermissionToRole('admin', 'edit_posts');
$rbac->assignPermissionToRole('user', 'view_dashboard');
// 模拟用户角色和要执行的操作
$userRole = 'admin';
$operation = 'edit_posts';
if ($rbac->hasPermission($userRole, $operation)) {
echo "用户具有执行操作的权限";
} else {
echo "用户没有执行操作的权限";
}
?>