96 lines
2.6 KiB
PHP
96 lines
2.6 KiB
PHP
<?php
|
|
/**
|
|
* auth_check.php — Middleware RBAC untuk 4 role SKPL.
|
|
*
|
|
* Role: publik | enumerator | operator | pimpinan
|
|
*
|
|
* Usage:
|
|
* require_once __DIR__ . '/../config/auth_check.php';
|
|
* requireAnyRole(['operator']); // hanya operator
|
|
* requireAnyRole(['operator','pimpinan']); // operator atau pimpinan
|
|
* requireRole('operator'); // kompat lama (1 role)
|
|
*/
|
|
require_once __DIR__ . '/session.php';
|
|
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
startAppSession();
|
|
}
|
|
|
|
function isLoggedIn(): bool {
|
|
return isset($_SESSION['user_id']) && isset($_SESSION['role']);
|
|
}
|
|
|
|
function currentRole(): string {
|
|
return $_SESSION['role'] ?? 'publik';
|
|
}
|
|
|
|
/**
|
|
* Halaman beranda (landing) per role setelah login.
|
|
*/
|
|
function roleHome(string $role): string {
|
|
return app_url(match ($role) {
|
|
'operator' => 'admin/index.php',
|
|
'pimpinan' => 'pimpinan/index.php',
|
|
'enumerator' => 'enumerator/index.php',
|
|
default => 'peta_publik.php',
|
|
});
|
|
}
|
|
|
|
function requireLogin(?string $redirect = null): void {
|
|
if (!isLoggedIn()) {
|
|
$redirect = $redirect ?? app_url('login.php');
|
|
header("Location: $redirect");
|
|
exit;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Izinkan akses hanya jika role pengguna ada di daftar $roles.
|
|
* Jika tidak, dialihkan ke beranda role-nya sendiri.
|
|
*/
|
|
function requireAnyRole(array $roles, ?string $redirect = null): void {
|
|
requireLogin($redirect);
|
|
if (!in_array(currentRole(), $roles, true)) {
|
|
header('Location: ' . roleHome(currentRole()));
|
|
exit;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Kompatibilitas dengan kode lama: requireRole('operator').
|
|
*/
|
|
function requireRole(string $role, ?string $redirect = null): void {
|
|
requireAnyRole([$role], $redirect);
|
|
}
|
|
|
|
/**
|
|
* Cek role tanpa redirect (untuk tampilan kondisional menu).
|
|
*/
|
|
function hasAnyRole(array $roles): bool {
|
|
return isLoggedIn() && in_array(currentRole(), $roles, true);
|
|
}
|
|
|
|
function currentUser(): array {
|
|
return [
|
|
'id' => $_SESSION['user_id'] ?? null,
|
|
'username' => $_SESSION['username'] ?? '',
|
|
'email' => $_SESSION['email'] ?? '',
|
|
'role' => $_SESSION['role'] ?? '',
|
|
'wilayah_tugas'=> $_SESSION['wilayah_tugas'] ?? '',
|
|
'nama_lengkap' => $_SESSION['nama_lengkap'] ?? '',
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Label role yang ramah ditampilkan.
|
|
*/
|
|
function roleLabel(string $role): string {
|
|
return match ($role) {
|
|
'operator' => 'Operator',
|
|
'pimpinan' => 'Pimpinan',
|
|
'enumerator' => 'Enumerator',
|
|
'publik' => 'Publik',
|
|
default => ucfirst($role),
|
|
};
|
|
}
|