Files
willes_AI/inc/php/login.php

92 lines
2.8 KiB
PHP
Raw Normal View History

<?php
// Always start session safely
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Load DB
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user = trim($_POST['login_email'] ?? '');
$password = $_POST['login_password'] ?? '';
$captcha = $_POST['g-recaptcha-response'] ?? '';
// 1. Input validation
if (empty($user) || empty($password)) {
$errors[] = "All fields are required.";
}
// 2. CAPTCHA validation
$captcha_success = false;
$localHosts = ['127.0.0.1', 'localhost'];
if (in_array($_SERVER['SERVER_NAME'], $localHosts) || str_contains($_SERVER['HTTP_HOST'], '.test')) {
$captcha_success = true; // Skip CAPTCHA locally
} else {
if (!empty($captcha)) {
$captcha_secret = '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe'; // test key
$ch = curl_init("https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'secret' => $captcha_secret,
'response' => $captcha,
'remoteip' => $_SERVER['REMOTE_ADDR'] ?? null
]);
$captcha_response = curl_exec($ch);
curl_close($ch);
$captcha_data = json_decode($captcha_response, true);
$captcha_success = !empty($captcha_data['success']);
}
}
if (!$captcha_success) {
$errors[] = "CAPTCHA verification failed.";
}
// 3. Authentication
if (empty($errors)) {
try {
$conn = getConnection();
$stmt = $conn->prepare("
SELECT id, username, password, uniqueid
FROM users
WHERE email = :email OR username = :username
LIMIT 1
");
$stmt->execute([
'email' => $user,
'username' => $user
]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result && password_verify($password, $result['password'])) {
// Regenerate session ID on login (security)
session_regenerate_id(true);
$_SESSION['user_id'] = $result['id'];
$_SESSION['username'] = $result['username'];
$_SESSION['uniqueid'] = $result['uniqueid'];
header("Location: /home.php");
exit;
} else {
$errors[] = "Invalid email/username or password.";
}
} catch (Exception $e) {
$errors[] = "Database error: " . $e->getMessage();
}
}
// If failed
$_SESSION['login_error'] = implode("<br>", $errors);
header("Location: /landing.php");
exit;
}
?>