Complete Phase 1: MVC, DB migrations, Auth, RBAC, Security, and Views
This commit is contained in:
81
app/Services/Auth/RBAC.php
Normal file
81
app/Services/Auth/RBAC.php
Normal file
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Auth;
|
||||
|
||||
use App\Services\Database\Connection;
|
||||
use PDO;
|
||||
|
||||
class RBAC
|
||||
{
|
||||
private PDO $pdo;
|
||||
private array $permissionCache = [];
|
||||
|
||||
public function __construct(Connection $connection)
|
||||
{
|
||||
$this->pdo = $connection->getPdo();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a user has a specific permission.
|
||||
*/
|
||||
public function hasPermission(int $userId, string $permissionCode): bool
|
||||
{
|
||||
$permissions = $this->getUserPermissions($userId);
|
||||
return in_array($permissionCode, $permissions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all unique permissions code associated with the user's roles.
|
||||
*/
|
||||
public function getUserPermissions(int $userId): array
|
||||
{
|
||||
if (isset($this->permissionCache[$userId])) {
|
||||
return $this->permissionCache[$userId];
|
||||
}
|
||||
|
||||
$sql = "SELECT DISTINCT p.code
|
||||
FROM permissions p
|
||||
JOIN role_permissions rp ON p.id = rp.permission_id
|
||||
JOIN user_roles ur ON rp.role_id = ur.role_id
|
||||
WHERE ur.user_id = :user_id";
|
||||
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute(['user_id' => $userId]);
|
||||
|
||||
$permissions = $stmt->fetchAll(PDO::FETCH_COLUMN);
|
||||
$permissions = $permissions ?: [];
|
||||
|
||||
$this->permissionCache[$userId] = $permissions;
|
||||
|
||||
return $permissions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user roles.
|
||||
*/
|
||||
public function getUserRoles(int $userId): array
|
||||
{
|
||||
$sql = "SELECT r.code
|
||||
FROM roles r
|
||||
JOIN user_roles ur ON r.id = ur.role_id
|
||||
WHERE ur.user_id = :user_id";
|
||||
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute(['user_id' => $userId]);
|
||||
|
||||
$roles = $stmt->fetchAll(PDO::FETCH_COLUMN);
|
||||
return $roles ?: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign a role to a user.
|
||||
*/
|
||||
public function assignRoleToUser(int $userId, int $roleId): void
|
||||
{
|
||||
$stmt = $this->pdo->prepare("INSERT IGNORE INTO user_roles (user_id, role_id) VALUES (?, ?)");
|
||||
$stmt->execute([$userId, $roleId]);
|
||||
|
||||
// Invalidate in-memory permission cache for this user
|
||||
unset($this->permissionCache[$userId]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user