Files

73 lines
2.4 KiB
PHP

<?php
// auth.php
require_once 'config.php';
$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';
if ($method === 'POST' && $action === 'login') {
// Membaca input JSON dari frontend
$input = json_decode(file_get_contents('php://input'), true);
$username = trim($input['username'] ?? '');
$password = trim($input['password'] ?? '');
if (empty($username) || empty($password)) {
sendResponse(false, 'Username dan password wajib diisi.');
}
// Mencari user di database
$stmt = $conn->prepare("SELECT id, username, password, role, masjid_id, dhuafa_id FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 1) {
$user = $result->fetch_assoc();
// Memverifikasi kecocokan password yang di-hash
if (password_verify($password, $user['password'])) {
// Menyimpan data user ke dalam session server
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['role'] = $user['role'];
$_SESSION['masjid_id'] = $user['masjid_id'];
$_SESSION['dhuafa_id'] = $user['dhuafa_id'];
// Kirim data user yang berhasil login tanpa password-nya
unset($user['password']);
sendResponse(true, 'Login berhasil.', $user);
} else {
sendResponse(false, 'Password salah.');
}
} else {
sendResponse(false, 'Username tidak ditemukan.');
}
$stmt->close();
}
elseif ($method === 'GET' && $action === 'check') {
// Aksi untuk memeriksa apakah session user masih aktif saat halaman di-refresh
if (isset($_SESSION['user_id'])) {
sendResponse(true, 'Sesi aktif.', [
'id' => $_SESSION['user_id'],
'username' => $_SESSION['username'],
'role' => $_SESSION['role'],
'masjid_id' => $_SESSION['masjid_id'],
'dhuafa_id' => $_SESSION['dhuafa_id']
]);
} else {
sendResponse(false, 'Belum login.');
}
}
elseif ($method === 'POST' && $action === 'logout') {
// Menghapus seluruh session aktif
session_unset();
session_destroy();
sendResponse(true, 'Logout berhasil.');
}
else {
sendResponse(false, 'Aksi autentikasi tidak valid.');
}
?>