TVPNBackend/api/auth.php
2024-10-28 18:30:03 -04:00

91 lines
2.8 KiB
PHP

<?php
include_once($_SERVER['DOCUMENT_ROOT'] . "/db_config.php");
include_once($_SERVER['DOCUMENT_ROOT'] . "/includes/utils.php");
$data = json_decode(file_get_contents('php://input'), true);
$token = get_bearer_token();
if (!is_null($token)) {
$token = $mysqli->real_escape_string($token);
$stmt = $mysqli->prepare("SELECT * FROM users WHERE token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();
$response = array();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$response['success'] = "true";
$response['message'] = 'Login successful!';
$response['token'] = $row['token'];
$response['expires'] = $row['expires'];
} else {
$response['success'] = "false";
$response['message'] = 'Invalid token.';
$response['token'] = "";
$response['expires'] = 0;
}
// Close connections
$stmt->close();
$mysqli->close();
header('Content-Type: application/json');
echo '{"success":"' . $response['success'] . '", "isAuthenticated":' . $response['success'] . ', "token":"'. $response['token'] .'", "expires":' . $response['expires'] . ', "message":"' . $response['message'] . '"}';
return;
}
if (is_null($data)) {
header('Content-Type: application/json');
http_response_code(412);
echo '{"success":"false","message":"No body sent.","token":"","expires": 0,"isAuthenticated":false}';
return;
}
$user = $data['username'];
$pass = $data['password'];
// Input validation and sanitization
$user = $mysqli->real_escape_string($user);
// Prepare and bind
$stmt = $mysqli->prepare("SELECT * 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)) {
$response['success'] = "true";
$response['message'] = 'Login successful!';
$response['token'] = $row['token'];
$response['expires'] = $row['expires'];
} else {
$response['success'] = "false";
$response['message'] = 'Invalid username or password.';
$response['token'] = "";
$response['expires'] = 0;
}
} else {
$response['success'] = "false";
$response['message'] = 'Invalid username or password.';
$response['token'] = "";
$response['expires'] = 0;
}
// Close connections
$stmt->close();
$mysqli->close();
// Return JSON response
header('Content-Type: application/json');
echo '{"success":"' . $response['success'] . '", "isAuthenticated":' . $response['success'] . ', "token":"'. $response['token'] .'", "expires":' . $response['expires'] . ', "message":"' . $response['message'] . '"}';