"fail", "message" => "Method not allowed."])); } $db = getDB(); // 6.20.2 targets the input explicitly via username parameters for log-ins $usernameInput = trim($_POST['username'] ?? $_POST['login'] ?? ''); $password = $_POST['password'] ?? ''; if (empty($usernameInput) || empty($password)) { http_response_code(400); die(json_encode(["status" => "fail", "message" => "Username and password required to log in."])); } // 1. Core Verification Query: Strictly looking up by username namespace $stmt = $db->prepare("SELECT * FROM users WHERE username = ?"); $stmt->execute([$usernameInput]); $user = $stmt->fetch(); if ($user) { // 2A. Profile found -> Validate password string match if (!password_verify($password, $user['password_hash'])) { http_response_code(401); die(json_encode(["status" => "fail", "message" => "Invalid username or password match."])); } } else { // 2B. Auto-Creation Gateway: Provision an internal email profile automatically since it wasn't supplied $hashedPassword = password_hash($password, PASSWORD_BCRYPT); $cleanUsername = strtolower(preg_replace('/[^A-Za-z0-9_.]/', '', $usernameInput)); $generatedEmail = $cleanUsername . "@nostolgagram.internal"; $generatedFullName = ucfirst($cleanUsername) . " (NostolgaGram)"; try { $insertStmt = $db->prepare("INSERT INTO users (username, email, password_hash, full_name) VALUES (?, ?, ?, ?)"); $insertStmt->execute([$cleanUsername, $generatedEmail, $hashedPassword, $generatedFullName]); $stmt = $db->prepare("SELECT * FROM users WHERE id = ?"); $stmt->execute([$db->lastInsertId()]); $user = $stmt->fetch(); } catch (PDOException $e) { http_response_code(500); die(json_encode(["status" => "fail", "message" => "Dynamic generation profile failed."])); } } // 3. Complete Session Handshake http_response_code(200); header("Set-Cookie: sessionid=nostolga_sess_" . $user['id'] . "; Path=/; HttpOnly"); echo json_encode([ "logged_in_user" => [ "pk" => (int)$user['id'], "username" => $user['username'], "email" => $user['email'], "full_name" => $user['full_name'], "profile_pic_url" => $user['profile_pic'] ?? 'https://picsum.photos/150/150', "is_private" => false ], "status" => "ok" ]); exit;