fix: Implement persistent zero-flicker JWT session hydration with localStorage and cookies across Student and Teacher portals

This commit is contained in:
Hamza-Ayed
2026-08-27 03:28:05 +03:00
parent f4af4d2db8
commit 845a5f3111
3 changed files with 66 additions and 19 deletions
+21 -4
View File
@@ -515,9 +515,16 @@ class StudentPortal
document.addEventListener('DOMContentLoaded', async () => {
const token = localStorage.getItem('saqel_student_jwt');
const cachedUser = localStorage.getItem('saqel_student_user');
if (token) {
await checkStudentSession(token);
if (cachedUser) {
try {
const u = JSON.parse(cachedUser);
renderDashboard(u);
} catch (e) {}
}
initWebSocket(token);
await checkStudentSession(token);
}
});
@@ -810,7 +817,12 @@ class StudentPortal
const data = await res.json();
if (res.ok && data.status === 'success' && data.data?.token) {
const token = data.data.token;
const user = data.data.user;
localStorage.setItem('saqel_student_jwt', token);
if (user) {
localStorage.setItem('saqel_student_user', JSON.stringify(user));
}
document.cookie = "saqel_student_jwt=" + token + "; path=/; max-age=2592000; SameSite=Lax";
initWebSocket(token);
await checkStudentSession(token);
} else {
@@ -830,15 +842,18 @@ class StudentPortal
const res = await fetch('/api/auth/me', {
headers: { 'Authorization': 'Bearer ' + token }
});
if (res.status === 401) {
handleLogout();
return;
}
const data = await res.json();
if (res.ok && data.data) {
studentData = data.data;
localStorage.setItem('saqel_student_user', JSON.stringify(data.data));
renderDashboard(data.data);
} else {
localStorage.removeItem('saqel_student_jwt');
}
} catch (e) {
console.error(e);
console.error('Session check notice:', e);
}
}
@@ -856,6 +871,8 @@ class StudentPortal
function handleLogout() {
localStorage.removeItem('saqel_student_jwt');
localStorage.removeItem('saqel_student_user');
document.cookie = "saqel_student_jwt=; path=/; max-age=0;";
if (wsSocket) wsSocket.close();
location.reload();
}