67 lines
1.6 KiB
PHP
67 lines
1.6 KiB
PHP
<?php
|
|
|
|
include_once($_SERVER['DOCUMENT_ROOT'] . "/db_config.php");
|
|
|
|
if (session_status() == PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
|
|
// Get the JSON input
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (is_null($data)) {
|
|
header('Content-Type: application/json');
|
|
http_response_code(412);
|
|
echo '{"success":"false","message":"No body sent."}';
|
|
return;
|
|
}
|
|
|
|
$user = $data['username'];
|
|
$pass = $data['password'];
|
|
|
|
// Input validation and sanitization
|
|
$user = $mysqli->real_escape_string($user);
|
|
|
|
// Prepare and bind
|
|
$stmt = $mysqli->prepare("SELECT passwordHash FROM users WHERE username = ?");
|
|
$stmt->bind_param("s", $user);
|
|
|
|
// Execute statement
|
|
$stmt->execute();
|
|
|
|
// Get result
|
|
$result = $stmt->get_result();
|
|
|
|
$response = array();
|
|
|
|
if ($result->num_rows > 0) {
|
|
$row = $result->fetch_assoc();
|
|
$hashed_password = $row['passwordHash'];
|
|
if (password_verify($pass, $hashed_password)) {
|
|
// Regenerate session ID to prevent session fixation
|
|
session_regenerate_id(true);
|
|
|
|
// Create session
|
|
$_SESSION['authenticated'] = true;
|
|
$_SESSION['username'] = $user;
|
|
|
|
$response['success'] = true;
|
|
$response['message'] = 'Login successful!';
|
|
} else {
|
|
$response['success'] = false;
|
|
$response['message'] = 'Invalid username or password.';
|
|
}
|
|
} else {
|
|
$response['success'] = false;
|
|
$response['message'] = 'Invalid username or password.';
|
|
}
|
|
|
|
// Close connections
|
|
$stmt->close();
|
|
$mysqli->close();
|
|
|
|
// Return JSON response
|
|
header('Content-Type: application/json');
|
|
echo '{"success":"' . $response['success'] . '","message":"' . $response['message'] . '"' . '}';
|
|
|