initial log in

This commit is contained in:
2025-11-29 10:19:39 +01:00
parent 7da69e5713
commit c5241eb155
14 changed files with 3243 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
import { useEffect, useState } from "react";
import Login from ".components/Login";
import MainApp from "./MainApp";
export default function App() {
const [loading, setLoading] = useState(true);
const [loggedIn, setLoggedIn] = useState(false);
useEffect(() => {
async function checkLogin() {
try {
// Call the endpoint that validates the refresh token cookie
const res = await fetch("http://localhost:7080/auth/login_refresh_token", {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": "react-app",
},
credentials: "include", // send cookies automatically
body: JSON.stringify({
device_id: crypto.randomUUID() // or a persistent device ID if you have one
}),
});
if (!res.ok) {
setLoggedIn(false);
return;
}
const data = await res.json();
// store short-lived token somewhere accessible
localStorage.setItem("access_token", data.access_token);
setLoggedIn(true);
} catch (err) {
console.error("Auth check failed:", err);
setLoggedIn(false);
} finally {
setLoading(false);
}
}
checkLogin();
}, []);
if (loading) return <p>Loading...</p>;
return loggedIn ? <MainApp /> : <Login />;
}

64
src/components/login.jsx Normal file
View File

@@ -0,0 +1,64 @@
import { useState } from "react";
export default function Login() {
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")
const [error, setError] = useState("")
async function handleSubmit(e) {
e.preventDefault();
setError("");
const device_id = crypto.randomUUID(); // browser-native UUID
try {
const res = await fetch("http://localhost:7080/auth/create_refresh", {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": "react-app" // optional
},
credentials: "include", // lets cookies like PHPSESSID flow if server sets them
body: JSON.stringify({
username,
password,
device_id
}),
});
if (!res.ok) {
setError("Invalid credentials or server error.");
return;
}
const data = await res.text();
console.log("Login success:", data);
// store tokens/responses where you want (context/localStorage/etc.)
} catch (err) {
setError("Network error.");
}
}
return (
<form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", width: "200px" }}>
<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">Login</button>
{error && <p style={{ color: "red" }}>{error}</p>}
</form>
);
}