Files

82 lines
2.2 KiB
PHP

<?php
/**
* Authentication API
* POST ?action=login — Login
* POST ?action=logout — Logout
* GET ?action=check — Check session
*/
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
header('Content-Type: application/json; charset=utf-8');
$action = $_GET['action'] ?? $_POST['action'] ?? '';
switch ($action) {
case 'login':
handleLogin();
break;
case 'logout':
handleLogout();
break;
case 'check':
handleCheck();
break;
default:
jsonResponse(['error' => 'Invalid action'], 400);
}
function handleLogin() {
$input = getInput();
$username = trim($input['username'] ?? '');
$password = trim($input['password'] ?? '');
if (empty($username) || empty($password)) {
jsonResponse(['error' => 'กรุณากรอกชื่อผู้ใช้และรหัสผ่าน'], 400);
}
$db = getDB();
// Try login by username
$stmt = $db->prepare("SELECT * FROM users WHERE username = ? OR personnel_code = ? LIMIT 1");
$stmt->execute([$username, $username]);
$user = $stmt->fetch();
if (!$user || !password_verify($password, $user['password_hash'])) {
jsonResponse(['error' => 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง'], 401);
}
// Set session
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['role'] = $user['role'];
$_SESSION['full_name'] = $user['full_name'];
jsonResponse([
'success' => true,
'user' => [
'id' => $user['id'],
'username' => $user['username'],
'role' => $user['role'],
'full_name' => $user['full_name']
]
]);
}
function handleLogout() {
session_destroy();
jsonResponse(['success' => true, 'message' => 'ออกจากระบบสำเร็จ']);
}
function handleCheck() {
if (isLoggedIn()) {
jsonResponse([
'loggedIn' => true,
'user' => getCurrentUser()
]);
} else {
jsonResponse(['loggedIn' => false]);
}
}