51 lines
1.4 KiB
PHP
51 lines
1.4 KiB
PHP
<?php
|
|
// api/login.php
|
|
require_once __DIR__ . '/config/database.php';
|
|
require_once __DIR__ . '/helpers/response.php';
|
|
setCORSHeaders();
|
|
|
|
$method = getMethod();
|
|
if ($method !== 'POST') {
|
|
sendError('Method tidak diizinkan', 405);
|
|
}
|
|
|
|
$body = getBody();
|
|
$username = trim($body['username'] ?? '');
|
|
$password = trim($body['password'] ?? '');
|
|
|
|
if (empty($username) || empty($password)) {
|
|
sendError('Username dan Password wajib diisi');
|
|
}
|
|
|
|
$db = getDB();
|
|
$stmt = $db->prepare("SELECT id, username, password, role, rumah_ibadah_id FROM users WHERE username = ?");
|
|
if (!$stmt) {
|
|
sendError('Gagal menyiapkan query database', 500);
|
|
}
|
|
$stmt->bind_param('s', $username);
|
|
$stmt->execute();
|
|
$user = $stmt->get_result()->fetch_assoc();
|
|
|
|
if (!$user || !password_verify($password, $user['password'])) {
|
|
sendError('Username atau Password salah', 401);
|
|
}
|
|
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
// Session settings for security
|
|
ini_set('session.cookie_httponly', 1);
|
|
ini_set('session.use_only_cookies', 1);
|
|
session_start();
|
|
}
|
|
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['username'] = $user['username'];
|
|
$_SESSION['role'] = $user['role'];
|
|
$_SESSION['rumah_ibadah_id'] = $user['rumah_ibadah_id'] ? (int)$user['rumah_ibadah_id'] : null;
|
|
|
|
sendSuccess([
|
|
'id' => $user['id'],
|
|
'username' => $user['username'],
|
|
'role' => $user['role'],
|
|
'rumah_ibadah_id' => $user['rumah_ibadah_id'] ? (int)$user['rumah_ibadah_id'] : null
|
|
], 'Login berhasil');
|