bleh
This commit is contained in:
parent
db4ce5599d
commit
2b3ee10ea7
|
|
@ -0,0 +1,244 @@
|
|||
import React, { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { clearAuth, guessUsernameFromToken, jwtExpSeconds, loadAuth, saveAuth } from "./authStorage";
|
||||
|
||||
const AuthCtx = createContext(null);
|
||||
|
||||
function apiBase() {
|
||||
// même domaine par défaut
|
||||
return (import.meta?.env?.VITE_API_BASE_URL || "").replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
async function apiFetch(path, opts = {}) {
|
||||
const url = apiBase() + path;
|
||||
const res = await fetch(url, {
|
||||
...opts,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(opts.headers || {}),
|
||||
},
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
async function whoami(accessToken) {
|
||||
const res = await apiFetch("/api/whoami", {
|
||||
method: "GET",
|
||||
headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
|
||||
});
|
||||
const j = await res.json().catch(() => null);
|
||||
return { ok: res.ok, status: res.status, json: j };
|
||||
}
|
||||
|
||||
async function refreshTokens(refreshToken) {
|
||||
const res = await apiFetch("/api/refresh", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ refresh_token: refreshToken }),
|
||||
});
|
||||
const j = await res.json().catch(() => null);
|
||||
return { ok: res.ok, status: res.status, json: j };
|
||||
}
|
||||
|
||||
function nowSec() {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }) {
|
||||
const [status, setStatus] = useState("loading"); // loading | anon | auth
|
||||
const [user, setUser] = useState(null); // { username }
|
||||
const [tokens, setTokens] = useState(null); // { access_token, refresh_token, ... }
|
||||
const [error, setError] = useState("");
|
||||
const refreshTimer = useRef(null);
|
||||
|
||||
function setAnon(msg = "") {
|
||||
setStatus("anon");
|
||||
setUser(null);
|
||||
setTokens(null);
|
||||
setError(msg || "");
|
||||
clearAuth();
|
||||
}
|
||||
|
||||
function setAuthFromTokens(t, usernameGuess = "") {
|
||||
setTokens(t);
|
||||
saveAuth({ ...t, obtained_at: Date.now() });
|
||||
const u = usernameGuess || guessUsernameFromToken(t?.access_token) || "";
|
||||
setUser(u ? { username: u } : null);
|
||||
setStatus("auth");
|
||||
setError("");
|
||||
}
|
||||
|
||||
async function ensureFreshSession(existing) {
|
||||
if (!existing?.access_token) return { ok: false, reason: "no_access_token" };
|
||||
|
||||
const exp = jwtExpSeconds(existing.access_token);
|
||||
const skew = 60; // seconds
|
||||
const isExpiredOrSoon = !exp || exp <= (nowSec() + skew);
|
||||
|
||||
// 1) refresh si nécessaire
|
||||
if (isExpiredOrSoon) {
|
||||
if (!existing.refresh_token) return { ok: false, reason: "expired_no_refresh" };
|
||||
|
||||
const rr = await refreshTokens(existing.refresh_token);
|
||||
if (!rr.ok || !rr.json?.access_token) {
|
||||
return { ok: false, reason: `refresh_failed_${rr.status}` };
|
||||
}
|
||||
|
||||
const merged = {
|
||||
...existing,
|
||||
...rr.json,
|
||||
};
|
||||
|
||||
// certains serveurs renvoient pas refresh_token à chaque fois
|
||||
if (!merged.refresh_token) merged.refresh_token = existing.refresh_token;
|
||||
|
||||
setAuthFromTokens(merged);
|
||||
existing = merged;
|
||||
} else {
|
||||
// access token encore bon
|
||||
setAuthFromTokens(existing);
|
||||
}
|
||||
|
||||
// 2) confirmer avec backend (whoami)
|
||||
const w = await whoami(existing.access_token);
|
||||
if (w.ok && w.json?.authenticated) {
|
||||
const uname = w.json.username || guessUsernameFromToken(existing.access_token) || "";
|
||||
setUser(uname ? { username: uname } : null);
|
||||
setStatus("auth");
|
||||
setError("");
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
// Si whoami fail, on considère désync (token invalide pour backend)
|
||||
return { ok: false, reason: `whoami_${w.status}` };
|
||||
}
|
||||
|
||||
function scheduleAutoRefresh(t) {
|
||||
if (refreshTimer.current) {
|
||||
clearInterval(refreshTimer.current);
|
||||
refreshTimer.current = null;
|
||||
}
|
||||
// check aux 30s, refresh quand exp < 90s
|
||||
refreshTimer.current = setInterval(async () => {
|
||||
const cur = loadAuth();
|
||||
if (!cur?.access_token) return;
|
||||
|
||||
const exp = jwtExpSeconds(cur.access_token);
|
||||
if (!exp) return;
|
||||
|
||||
if (exp <= nowSec() + 90) {
|
||||
if (!cur.refresh_token) {
|
||||
setAnon("Session expirée (pas de refresh_token).");
|
||||
return;
|
||||
}
|
||||
const rr = await refreshTokens(cur.refresh_token);
|
||||
if (!rr.ok || !rr.json?.access_token) {
|
||||
setAnon("Session expirée. Please login again.");
|
||||
return;
|
||||
}
|
||||
const merged = { ...cur, ...rr.json };
|
||||
if (!merged.refresh_token) merged.refresh_token = cur.refresh_token;
|
||||
setAuthFromTokens(merged);
|
||||
}
|
||||
}, 30000);
|
||||
}
|
||||
|
||||
async function restore() {
|
||||
setStatus("loading");
|
||||
setError("");
|
||||
const saved = loadAuth();
|
||||
if (!saved?.access_token) {
|
||||
setAnon("");
|
||||
return;
|
||||
}
|
||||
|
||||
const r = await ensureFreshSession(saved);
|
||||
if (!r.ok) {
|
||||
setAnon("Login desynced. Please login again.");
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleAutoRefresh(saved);
|
||||
}
|
||||
|
||||
async function login(username, password) {
|
||||
setError("");
|
||||
setStatus("loading");
|
||||
|
||||
const res = await apiFetch("/api/login", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
const j = await res.json().catch(() => null);
|
||||
if (!res.ok || !j?.access_token) {
|
||||
setAnon(j?.error_description || j?.error || "Login failed");
|
||||
return { ok: false, status: res.status, json: j };
|
||||
}
|
||||
|
||||
const t = {
|
||||
...j,
|
||||
obtained_at: Date.now(),
|
||||
};
|
||||
|
||||
setAuthFromTokens(t);
|
||||
scheduleAutoRefresh(t);
|
||||
|
||||
// confirm whoami (si ça fail -> desync)
|
||||
const w = await whoami(t.access_token);
|
||||
if (!w.ok || !w.json?.authenticated) {
|
||||
setAnon("Login desynced. Please login again.");
|
||||
return { ok: false, status: w.status, json: w.json };
|
||||
}
|
||||
|
||||
const uname = w.json.username || guessUsernameFromToken(t.access_token) || "";
|
||||
setUser(uname ? { username: uname } : null);
|
||||
setStatus("auth");
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
function logout() {
|
||||
if (refreshTimer.current) clearInterval(refreshTimer.current);
|
||||
refreshTimer.current = null;
|
||||
setAnon("");
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
restore();
|
||||
|
||||
const onStorage = (e) => {
|
||||
if (e.key === "sociowire:auth") restore();
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => window.removeEventListener("storage", onStorage);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (status === "auth" && tokens?.access_token) {
|
||||
scheduleAutoRefresh(tokens);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [status]);
|
||||
|
||||
const value = useMemo(() => {
|
||||
return {
|
||||
status,
|
||||
user,
|
||||
tokens,
|
||||
error,
|
||||
|
||||
isAuthed: status === "auth",
|
||||
accessToken: tokens?.access_token || "",
|
||||
|
||||
login,
|
||||
logout,
|
||||
restore,
|
||||
setError,
|
||||
};
|
||||
}, [status, user, tokens, error]);
|
||||
|
||||
return <AuthCtx.Provider value={value}>{children}</AuthCtx.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
return useContext(AuthCtx);
|
||||
}
|
||||
|
|
@ -59,7 +59,6 @@
|
|||
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@babel/generator": "^7.28.5",
|
||||
|
|
@ -1085,7 +1084,6 @@
|
|||
"integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"csstype": "^3.2.2"
|
||||
}
|
||||
|
|
@ -1136,7 +1134,6 @@
|
|||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
|
|
@ -1259,7 +1256,6 @@
|
|||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.9.0",
|
||||
"caniuse-lite": "^1.0.30001759",
|
||||
|
|
@ -1561,7 +1557,6 @@
|
|||
"integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.8.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
|
|
@ -2782,7 +2777,6 @@
|
|||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
|
|
@ -2868,7 +2862,6 @@
|
|||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.1.tgz",
|
||||
"integrity": "sha512-DGrYcCWK7tvYMnWh79yrPHt+vdx9tY+1gPZa7nJQtO/p8bLTDaHp4dzwEhQB7pZ4Xe3ok4XKuEPrVuc+wlpkmw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
|
|
@ -2878,7 +2871,6 @@
|
|||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.1.tgz",
|
||||
"integrity": "sha512-ibrK8llX2a4eOskq1mXKu/TGZj9qzomO+sNfO98M6d9zIPOEhlBkMkBUBLd1vgS0gQsLDBzA+8jJBVXDnfHmJg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"scheduler": "^0.27.0"
|
||||
},
|
||||
|
|
@ -3181,7 +3173,6 @@
|
|||
"integrity": "sha512-u09tdk/huMiN8xwoiBbig197jKdCamQTtOruSalOzbqGje3jdHiV0njQlAW0YvzoahkirFePNQ4RYlfnRQpXZA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@oxc-project/runtime": "0.97.0",
|
||||
"fdir": "^6.5.0",
|
||||
|
|
@ -3304,7 +3295,6 @@
|
|||
"integrity": "sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,13 +4,13 @@ import { clearAuth, guessUsernameFromToken, jwtExpSeconds, loadAuth, saveAuth }
|
|||
const AuthCtx = createContext(null);
|
||||
|
||||
function apiBase() {
|
||||
// même domaine par défaut
|
||||
return (import.meta?.env?.VITE_API_BASE_URL || "").replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
async function apiFetch(path, opts = {}) {
|
||||
const url = apiBase() + path;
|
||||
const res = await fetch(url, {
|
||||
credentials: "include",
|
||||
...opts,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
|
@ -20,13 +20,31 @@ async function apiFetch(path, opts = {}) {
|
|||
return res;
|
||||
}
|
||||
|
||||
// tolerant whoami: accepts {authenticated:true} OR {username:""} OR {user:""} OR just ok+token
|
||||
async function whoami(accessToken) {
|
||||
const res = await apiFetch("/api/whoami", {
|
||||
method: "GET",
|
||||
headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
|
||||
});
|
||||
const j = await res.json().catch(() => null);
|
||||
return { ok: res.ok, status: res.status, json: j };
|
||||
|
||||
const text = await res.text().catch(() => "");
|
||||
let json = null;
|
||||
try {
|
||||
json = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
json = null;
|
||||
}
|
||||
|
||||
const uname =
|
||||
(json && (json.username || json.user || json.preferred_username)) ||
|
||||
guessUsernameFromToken(accessToken) ||
|
||||
"";
|
||||
|
||||
const authed =
|
||||
!!res.ok &&
|
||||
(json?.authenticated === true || json?.ok === true || !!json?.username || !!json?.user || !!uname);
|
||||
|
||||
return { ok: !!res.ok, status: res.status, json, text, authenticated: authed, username: uname };
|
||||
}
|
||||
|
||||
async function refreshTokens(refreshToken) {
|
||||
|
|
@ -34,8 +52,16 @@ async function refreshTokens(refreshToken) {
|
|||
method: "POST",
|
||||
body: JSON.stringify({ refresh_token: refreshToken }),
|
||||
});
|
||||
const j = await res.json().catch(() => null);
|
||||
return { ok: res.ok, status: res.status, json: j };
|
||||
|
||||
const text = await res.text().catch(() => "");
|
||||
let json = null;
|
||||
try {
|
||||
json = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
json = null;
|
||||
}
|
||||
|
||||
return { ok: res.ok, status: res.status, json, text };
|
||||
}
|
||||
|
||||
function nowSec() {
|
||||
|
|
@ -70,53 +96,43 @@ export function AuthProvider({ children }) {
|
|||
if (!existing?.access_token) return { ok: false, reason: "no_access_token" };
|
||||
|
||||
const exp = jwtExpSeconds(existing.access_token);
|
||||
const skew = 60; // seconds
|
||||
const isExpiredOrSoon = !exp || exp <= (nowSec() + skew);
|
||||
const skew = 60;
|
||||
const isExpiredOrSoon = !exp || exp <= nowSec() + skew;
|
||||
|
||||
// 1) refresh si nécessaire
|
||||
if (isExpiredOrSoon) {
|
||||
if (!existing.refresh_token) return { ok: false, reason: "expired_no_refresh" };
|
||||
|
||||
const rr = await refreshTokens(existing.refresh_token);
|
||||
if (!rr.ok || !rr.json?.access_token) {
|
||||
return { ok: false, reason: `refresh_failed_${rr.status}` };
|
||||
return { ok: false, reason: `refresh_failed_${rr.status}`, detail: rr.text };
|
||||
}
|
||||
|
||||
const merged = {
|
||||
...existing,
|
||||
...rr.json,
|
||||
};
|
||||
|
||||
// certains serveurs renvoient pas refresh_token à chaque fois
|
||||
const merged = { ...existing, ...rr.json };
|
||||
if (!merged.refresh_token) merged.refresh_token = existing.refresh_token;
|
||||
|
||||
setAuthFromTokens(merged);
|
||||
existing = merged;
|
||||
} else {
|
||||
// access token encore bon
|
||||
setAuthFromTokens(existing);
|
||||
}
|
||||
|
||||
// 2) confirmer avec backend (whoami)
|
||||
const w = await whoami(existing.access_token);
|
||||
if (w.ok && w.json?.authenticated) {
|
||||
const uname = w.json.username || guessUsernameFromToken(existing.access_token) || "";
|
||||
setUser(uname ? { username: uname } : null);
|
||||
if (w.ok && w.authenticated) {
|
||||
setUser(w.username ? { username: w.username } : null);
|
||||
setStatus("auth");
|
||||
setError("");
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
// Si whoami fail, on considère désync (token invalide pour backend)
|
||||
return { ok: false, reason: `whoami_${w.status}` };
|
||||
return { ok: false, reason: `whoami_${w.status}`, detail: w.text || "" };
|
||||
}
|
||||
|
||||
function scheduleAutoRefresh(t) {
|
||||
function scheduleAutoRefresh() {
|
||||
if (refreshTimer.current) {
|
||||
clearInterval(refreshTimer.current);
|
||||
refreshTimer.current = null;
|
||||
}
|
||||
// check aux 30s, refresh quand exp < 90s
|
||||
|
||||
refreshTimer.current = setInterval(async () => {
|
||||
const cur = loadAuth();
|
||||
if (!cur?.access_token) return;
|
||||
|
|
@ -156,7 +172,7 @@ export function AuthProvider({ children }) {
|
|||
return;
|
||||
}
|
||||
|
||||
scheduleAutoRefresh(saved);
|
||||
scheduleAutoRefresh();
|
||||
}
|
||||
|
||||
async function login(username, password) {
|
||||
|
|
@ -168,29 +184,30 @@ export function AuthProvider({ children }) {
|
|||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
const j = await res.json().catch(() => null);
|
||||
const text = await res.text().catch(() => "");
|
||||
let j = null;
|
||||
try {
|
||||
j = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
j = null;
|
||||
}
|
||||
|
||||
if (!res.ok || !j?.access_token) {
|
||||
setAnon(j?.error_description || j?.error || "Login failed");
|
||||
return { ok: false, status: res.status, json: j };
|
||||
setAnon(j?.error_description || j?.error || text || "Login failed");
|
||||
return { ok: false, status: res.status, json: j, text };
|
||||
}
|
||||
|
||||
const t = {
|
||||
...j,
|
||||
obtained_at: Date.now(),
|
||||
};
|
||||
|
||||
const t = { ...j, obtained_at: Date.now() };
|
||||
setAuthFromTokens(t);
|
||||
scheduleAutoRefresh(t);
|
||||
scheduleAutoRefresh();
|
||||
|
||||
// confirm whoami (si ça fail -> desync)
|
||||
const w = await whoami(t.access_token);
|
||||
if (!w.ok || !w.json?.authenticated) {
|
||||
if (!w.ok || !w.authenticated) {
|
||||
setAnon("Login desynced. Please login again.");
|
||||
return { ok: false, status: w.status, json: w.json };
|
||||
return { ok: false, status: w.status, json: w.json, text: w.text };
|
||||
}
|
||||
|
||||
const uname = w.json.username || guessUsernameFromToken(t.access_token) || "";
|
||||
setUser(uname ? { username: uname } : null);
|
||||
setUser(w.username ? { username: w.username } : null);
|
||||
setStatus("auth");
|
||||
return { ok: true };
|
||||
}
|
||||
|
|
@ -203,7 +220,6 @@ export function AuthProvider({ children }) {
|
|||
|
||||
useEffect(() => {
|
||||
restore();
|
||||
|
||||
const onStorage = (e) => {
|
||||
if (e.key === "sociowire:auth") restore();
|
||||
};
|
||||
|
|
@ -212,22 +228,30 @@ export function AuthProvider({ children }) {
|
|||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (status === "auth" && tokens?.access_token) {
|
||||
scheduleAutoRefresh(tokens);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [status]);
|
||||
|
||||
// Backward-compatible fields expected by TopBar/MapView
|
||||
const value = useMemo(() => {
|
||||
const loading = status === "loading";
|
||||
const authenticated = status === "auth";
|
||||
const username = user?.username || "";
|
||||
const token = tokens?.access_token || "";
|
||||
|
||||
return {
|
||||
// internal
|
||||
status,
|
||||
user,
|
||||
tokens,
|
||||
error,
|
||||
|
||||
isAuthed: status === "auth",
|
||||
accessToken: tokens?.access_token || "",
|
||||
// expected by UI
|
||||
loading,
|
||||
authenticated,
|
||||
username,
|
||||
token,
|
||||
|
||||
lastError: error || "",
|
||||
lastInfo: "",
|
||||
needsEmailVerification: false,
|
||||
resendVerificationEmail: async () => {},
|
||||
|
||||
login,
|
||||
logout,
|
||||
|
|
|
|||
Loading…
Reference in New Issue