Aggiungendo funzioni per gestire il login. Da riformattare il codice

This commit is contained in:
Sergio-Bianchi 2025-10-24 19:51:59 +02:00
parent f47676d0cd
commit e0d4321541
6 changed files with 122 additions and 11 deletions

20
backend/api/cors.php Normal file
View File

@ -0,0 +1,20 @@
<?php
$allowedOrigins = [
'http://localhost:5173',
];
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
if (in_array($origin, $allowedOrigins, true)) {
header("Access-Control-Allow-Origin: $origin");
}
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}

49
backend/api/login.php Normal file
View File

@ -0,0 +1,49 @@
<?php
require_once __DIR__ . '/cors.php';
require_once __DIR__ . '/../services/Access.php';
use services\Access;
session_start();
header("Access-Control-Allow-Origin: http://localhost:5173");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");
$input = json_decode(file_get_contents('php://input'), true);
$username = $input['username'] ?? null;
$password = $input['password'] ?? null;
$answer = [
'status' => "fail",
'data' => [
],
];
if ($username && $password) {
$result = Access::login($username, $password);
if ($result && $result->num_rows > 0) {
$answer['status'] = "success";
$answer['data'] = [
'username' => $username,
];
http_response_code(200);
echo json_encode($answer);
} else {
http_response_code(401);
$answer['data']['title'] = 'Wrong username or password';
}
} else {
$answer['data']['title'] = 'Please insert username and password';
http_response_code(400);
echo json_encode($answer);
}
exit;

View File

@ -2,21 +2,28 @@
use services\Search;
header("Access-Control-Allow-Origin: http://localhost:3000");
session_start();
header("Access-Control-Allow-Origin: http://localhost:5173");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");
require_once __DIR__ . '/../services/Search.php';
// Get the search query parameter
$username = isset($_GET['username']) ? $_GET['username'] : '';
$_SESSION['username'] = $username;
$result = Search::searchByUsername($username);
if ($result->num_rows == 0) {
echo "Utente " . $username . " non trovato";
return;
exit;
} else {
echo json_encode(array_values($result->fetch_assoc()));
}
?>

View File

@ -1,7 +1,7 @@
<?php
namespace services;
include 'config/database-connection.php';
include __DIR__.'/../config/database-connection.php';
class Access
{

View File

@ -1,18 +1,55 @@
import React from "react";
import React, {useEffect, useState} from "react";
import '../styles/login.css'
function Login() {
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setLoading(true);
setError(null);
try {
const requestOptions = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({username, password}),
credentials: 'include',
};
const response = await fetch('http://localhost:8000/api/login.php', requestOptions)
const data = await response.json();
console.log(data)
if (!response.ok || data.status === 'fail') {
throw new Error(data.data?.message || "Login failed");
}
console.log("Logged in")
} catch (err: any) {
setError(err.message)
} finally {
setLoading(false)
}
}
return (
<>
<div id="login-container">
<div id="login-form-container">
<h1> Accedi </h1>
<form>
<form onSubmit={handleSubmit}>
<div className="spacer-50"></div>
<input type="text" placeholder="username"/>
<input type="password" placeholder="password"/>
<input
type="text" placeholder="username" value={username}
onChange={(e) => setUsername(e.target.value)}/>
<input type="password" placeholder="password" value={password}
onChange={(e) => setPassword(e.target.value)}/>
<button type="submit">Entra</button>
<div className="spacer-fill"></div>
</form>

View File

@ -7,7 +7,5 @@ import App from './App.tsx'
import Topbar from "./components/Topbar.tsx";
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>
<App/>
)