Files
tinyTask/login.php
2026-02-16 00:45:57 -08:00

80 lines
2.4 KiB
PHP

<?php
require 'db.php';
require 'auth.php';
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
// Keep front-end field name "email" for compatibility; it can now be email OR username
$identifierRaw = trim($data['email'] ?? '');
$identifier = strtolower($identifierRaw);
$password = strval($data['password'] ?? '');
if ($identifier === '') {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'Email or username is required']);
exit;
}
$isEmail = filter_var($identifier, FILTER_VALIDATE_EMAIL) !== false;
$sql = "
SELECT u.id, u.email, u.username, u.password_hash,
r.name AS role_name,
r.can_manage_settings
FROM users u
JOIN roles r ON r.id = u.role_id
WHERE " . ($isEmail ? "u.email = ?" : "u.username = ?") . "
LIMIT 1
";
$stmt = $pdo->prepare($sql);
$stmt->execute([$identifier]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user || !password_verify($password, $user['password_hash'])) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'Invalid credentials']);
exit;
}
$_SESSION['user'] = [
'id' => (int)$user['id'],
'email' => $user['email'],
'username' => $user['username'], // NEW
'role' => $user['role_name'],
'can_manage_settings' => (int)$user['can_manage_settings'],
];
// Set active profile for this session (default profile if available)
$stmt = $pdo->prepare("SELECT id FROM profiles WHERE user_id = ? AND is_default = 1 LIMIT 1");
$stmt->execute([$_SESSION['user']['id']]);
$profileId = $stmt->fetchColumn();
if (!$profileId) {
$stmt = $pdo->prepare("SELECT id FROM profiles WHERE user_id = ? ORDER BY id ASC LIMIT 1");
$stmt->execute([$_SESSION['user']['id']]);
$profileId = $stmt->fetchColumn();
}
if (!$profileId) {
$stmt = $pdo->prepare("INSERT INTO profiles (user_id, name, is_default) VALUES (?, 'Default', 1)");
$stmt->execute([$_SESSION['user']['id']]);
$profileId = $pdo->lastInsertId();
}
$_SESSION['active_profile_id'] = (int)$profileId;
echo json_encode([
'success' => true,
'user' => [
'id' => $_SESSION['user']['id'],
'email' => $_SESSION['user']['email'],
'username' => $_SESSION['user']['username'], // NEW
'role' => $_SESSION['user']['role'],
'can_manage_settings' => $_SESSION['user']['can_manage_settings'],
],
'active_profile_id' => $_SESSION['active_profile_id']
]);