Files
tinyTask/login.php

67 lines
2.0 KiB
PHP

<?php
require 'db.php';
require 'auth.php';
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
$email = strtolower(trim($data['email'] ?? ''));
$password = strval($data['password'] ?? '');
$stmt = $pdo->prepare("
SELECT u.id, u.email, 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 u.email = ?
LIMIT 1
");
$stmt->execute([$email]);
$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' => intval($user['id']),
'email' => $user['email'],
'role' => $user['role_name'],
'can_manage_settings' => intval($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) {
// Fallback to first profile
$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) {
// Last-resort: create a default profile if none exist (useful for new users)
$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'],
'role' => $_SESSION['user']['role'],
'can_manage_settings' => $_SESSION['user']['can_manage_settings'],
],
'active_profile_id' => $_SESSION['active_profile_id']
]);