mirror of
https://github.com/christianvidalwolf-prog/Craze-Data-check.git
synced 2026-08-03 13:35:25 +02:00
Auth: Implement automatic session refresh logic to prevent 'JWT expired' errors. The app now handles token renewal in the background, allowing users to save changes without interruption.
This commit is contained in:
+21
-12
@@ -50,6 +50,17 @@ export default function App() {
|
||||
setSession(null);
|
||||
};
|
||||
|
||||
// Sync session state when localStorage is updated (e.g. by token refresh)
|
||||
useEffect(() => {
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === 'craze_auth_session') {
|
||||
setSession(getStoredSession());
|
||||
}
|
||||
};
|
||||
window.addEventListener('storage', handleStorage);
|
||||
return () => window.removeEventListener('storage', handleStorage);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const loadDefaultData = async () => {
|
||||
setIsLoadingDefault(true);
|
||||
@@ -122,7 +133,7 @@ export default function App() {
|
||||
}
|
||||
|
||||
console.log('Fetching synced data from Supabase...');
|
||||
const syncedData = await getAllSyncedRows(session?.access_token);
|
||||
const syncedData = await getAllSyncedRows();
|
||||
|
||||
const resolvedCols = resolveColumnIndices(headers);
|
||||
const editableColumns = new Set([
|
||||
@@ -316,7 +327,7 @@ export default function App() {
|
||||
|
||||
// 3. Post-export: Reset pending statuses in Supabase
|
||||
console.log('Resetting pending statuses in Supabase...');
|
||||
resetAllPendingRows(session?.access_token).then(success => {
|
||||
resetAllPendingRows().then(success => {
|
||||
if (success) {
|
||||
console.log('Successfully reset all pending statuses');
|
||||
setRowStatuses({}); // Clear local statuses
|
||||
@@ -414,18 +425,17 @@ export default function App() {
|
||||
|
||||
setIsSavingAll(true);
|
||||
let failedArticles: string[] = [];
|
||||
let jwtExpired = false;
|
||||
const token = session?.access_token;
|
||||
let sessionIssue = false;
|
||||
|
||||
try {
|
||||
for (const [articleNo, { newData, originalData, articleName }] of entries) {
|
||||
console.log('[handleSaveAll] Saving article:', articleNo);
|
||||
const result = await saveRowToSupabase(articleNo, newData, token);
|
||||
const result = await saveRowToSupabase(articleNo, newData);
|
||||
console.log('[handleSaveAll] Save result for', articleNo, ':', result);
|
||||
|
||||
if (result.success) {
|
||||
// Also save to history
|
||||
await saveHistoryEntry(articleNo, articleName, originalData, newData, session?.user?.email || 'unknown', token);
|
||||
await saveHistoryEntry(articleNo, articleName, originalData, newData, session?.user?.email || 'unknown');
|
||||
|
||||
setRowStatuses(prev => ({ ...prev, [articleNo]: 'saved' }));
|
||||
setPendingRows(prev => {
|
||||
@@ -436,16 +446,16 @@ export default function App() {
|
||||
} else {
|
||||
setRowStatuses(prev => ({ ...prev, [articleNo]: 'error' }));
|
||||
failedArticles.push(`${articleNo} [${result.error || 'Unknown error'}]`);
|
||||
if (result.error?.includes('401') || result.error?.includes('JWT expired')) {
|
||||
jwtExpired = true;
|
||||
if (result.error?.includes('401') || result.error?.includes('expired') || result.error?.includes('Session expired')) {
|
||||
sessionIssue = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[handleSaveAll] Finished loop. Failed:', failedArticles.length);
|
||||
|
||||
if (jwtExpired) {
|
||||
alert("Tu sesión ha caducado (JWT expired). Por favor, haz clic en el botón de Cerrar Sesión (Sign out) arriba a la derecha y vuelve a iniciar sesión para guardar tus cambios.");
|
||||
if (sessionIssue) {
|
||||
alert("Tu sesión ha caducado definitivamente. Por favor, cierra sesión e inicia sesión de nuevo para continuar. No refresques la página para no perder tus cambios pendientes en pantalla.");
|
||||
} else if (failedArticles.length > 0) {
|
||||
alert(`Failed to save items:\n\n${failedArticles.join('\n')}\n\nPlease try again.`);
|
||||
} else {
|
||||
@@ -667,7 +677,6 @@ export default function App() {
|
||||
<HistoryView
|
||||
headers={appState.headers}
|
||||
data={appState.data}
|
||||
sessionToken={session?.access_token}
|
||||
onEdit={(index) => setEditingRowIndex(index)}
|
||||
onRevert={async (articleNo, revertedData, historyId) => {
|
||||
// Find the row in appState.data and update it
|
||||
@@ -691,7 +700,7 @@ export default function App() {
|
||||
}));
|
||||
// Delete the history entry after revert
|
||||
if (historyId) {
|
||||
await deleteHistoryEntry(String(historyId), session?.access_token);
|
||||
await deleteHistoryEntry(String(historyId));
|
||||
}
|
||||
}
|
||||
}}
|
||||
|
||||
Reference in New Issue
Block a user