<?php
declare(strict_types=1);
if (!defined('STORE_ROOT')) { http_response_code(403); exit; }
function authHandler(string $action, array $in): void {
// CSRF is already validated by router.php and api/index.php before reaching handlers
$email = trim($in['email'] ?? '');
$password = trim($in['password'] ?? '');
if ($action === 'login') {
if (!$email || !$password) {
App::err('Email and password are required.');
}
$res = Auth::login($email, $password);
if (!empty($res['success'])) {
App::ok(['success' => true]);
} else {
App::err($res['error'] ?? 'Invalid credentials.');
}
exit;
}
if ($action === 'register' || $action === 'signup') {
$name = trim($in['name'] ?? $in['full_name'] ?? '');
if (!$email || !$password) {
App::err('Email and password are required.');
}
if (strlen($password) < 8) {
App::err('Password must be at least 8 characters.');
}
$storeId = App::storeId();
$res = Auth::register($email, $password, $name, $storeId);
if (!empty($res['success'])) {
App::ok(['success' => true]);
} else {
App::err($res['error'] ?? 'Registration failed.');
}
exit;
}
if ($action === 'logout') {
Auth::logout();
App::ok(['success' => true]);
exit;
}
App::err('Unknown auth action');
}