Files
UAS_WEBGIS_MichelleOlivia_D…/sig-kemiskinan/includes/auth.php
T
2026-06-10 21:46:56 +07:00

31 lines
1.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
// includes/auth.php v2.0
// ============================================================
// Middleware Autentikasi berbasis PHP Session
// ============================================================
require_once __DIR__ . '/config.php';
session_start();
// ── Cek apakah user sudah login ───────────────────────────
function requireAuth(array $allowedRoles = []): array {
if (!isset($_SESSION['user_id'])) {
jsonResponse(['success' => false, 'error' => 'Unauthorized silakan login', 'redirect' => '/index.html'], 401);
}
$user = $_SESSION['user'];
if (!empty($allowedRoles) && !in_array($user['role'], $allowedRoles)) {
jsonResponse(['success' => false, 'error' => 'Akses ditolak untuk role: ' . $user['role']], 403);
}
return $user;
}
// ── Ambil user saat ini (null jika belum login) ───────────
function currentUser(): ?array {
return $_SESSION['user'] ?? null;
}
// ── Cek apakah sudah login (tanpa redirect) ───────────────
function isLoggedIn(): bool {
return isset($_SESSION['user_id']);
}