89 lines
2.1 KiB
PHP
89 lines
2.1 KiB
PHP
<?php
|
|
/**
|
|
* Authentication middleware and handlers
|
|
*/
|
|
|
|
/**
|
|
* Handle login action
|
|
* @param mysqli $db Database connection
|
|
* @return void
|
|
*/
|
|
function handleLogin(mysqli $db): void
|
|
{
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
$username = $input['username'] ?? '';
|
|
|
|
$stmt = $db->prepare("SELECT password, full_name FROM sales_users WHERE username = ?");
|
|
$stmt->bind_param("s", $username);
|
|
$stmt->execute();
|
|
$res = $stmt->get_result()->fetch_assoc();
|
|
|
|
if ($res && password_verify($input['password'], $res['password'])) {
|
|
$_SESSION['user'] = $username;
|
|
$_SESSION['full_name'] = $res['full_name'];
|
|
|
|
// Recovery cookie payload
|
|
$cookie_payload = base64_encode(json_encode([
|
|
'user' => $username,
|
|
'full_name' => $res['full_name'],
|
|
'expires' => MIDNIGHT_TIMESTAMP
|
|
]));
|
|
|
|
setcookie('telvero_remember', $cookie_payload, MIDNIGHT_TIMESTAMP, '/', '', isset($_SERVER['HTTPS']), true);
|
|
|
|
echo json_encode(['success' => true, 'user' => $res['full_name']]);
|
|
} else {
|
|
http_response_code(401);
|
|
echo json_encode(['error' => 'Login mislukt']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle session check action
|
|
* @return void
|
|
*/
|
|
function handleCheckSession(): void
|
|
{
|
|
if (isset($_SESSION['user'])) {
|
|
echo json_encode([
|
|
'authenticated' => true,
|
|
'user' => $_SESSION['full_name'] ?? $_SESSION['user']
|
|
]);
|
|
} else {
|
|
echo json_encode(['authenticated' => false]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle logout action
|
|
* @return void
|
|
*/
|
|
function handleLogout(): void
|
|
{
|
|
session_destroy();
|
|
setcookie('telvero_remember', '', time() - 3600, '/');
|
|
echo json_encode(['success' => true]);
|
|
}
|
|
|
|
/**
|
|
* Check if user is authenticated
|
|
* @return bool
|
|
*/
|
|
function isAuthenticated(): bool
|
|
{
|
|
return isset($_SESSION['user']);
|
|
}
|
|
|
|
/**
|
|
* Require authentication - exits if not authenticated
|
|
* @return void
|
|
*/
|
|
function requireAuth(): void
|
|
{
|
|
if (!isAuthenticated()) {
|
|
http_response_code(403);
|
|
echo json_encode(['error' => 'Not authenticated']);
|
|
exit;
|
|
}
|
|
}
|