steve07s 1 год назад
Родитель
Сommit
3bab1d9c80
1 измененных файлов с 24 добавлено и 5 удалено
  1. 24 5
      static/js/frontend.js

+ 24 - 5
static/js/frontend.js

@@ -161,11 +161,20 @@ class FrontendState {
       data,
       error
     } = await getSessionFromBackend()
+    console.log(data)
     if (success) {
-      this.currentSession = data;
+      if (data) { // 檢查 data 是否存在
+        this.currentSession = data;
+        setLoggedIn(true);
+        updateUsernameDisplay(data.username); // 確保在 data 存在時才讀取 username
+      } else {
+        this.currentSession = undefined;
+        setLoggedIn(false);
+        updateUsernameDisplay(''); // 如果沒有用戶登入,清空用戶名顯示
+      }
     } else {
-      // ha ha I'm being lazy.  can you do better?
-      alert(error)
+      // 處理錯誤情況
+      alert('Unable to refresh session state. Please try again later.');
     }
     if (updateView) {
       this.updateView();
@@ -237,11 +246,21 @@ async function handleAuthEvent(event) {
 
 function updateUsernameDisplay(username) {
   const usernameSpan = document.querySelector('.username');
-  if (usernameSpan) {
-    usernameSpan.textContent = username || 'nobody'; // 如果username為空,顯示'nobody'
+  const loggedOutDivs = document.querySelectorAll('.forloggedout');
+  const loggedInDivs = document.querySelectorAll('.forloggedin');
+
+  if (username) {
+    usernameSpan.textContent = username;
+    loggedOutDivs.forEach(div => div.style.display = 'none');
+    loggedInDivs.forEach(div => div.style.display = 'block');
+  } else {
+    usernameSpan.textContent = 'nobody';
+    loggedOutDivs.forEach(div => div.style.display = 'block');
+    loggedInDivs.forEach(div => div.style.display = 'none');
   }
 }
 
+
 const authform = document.querySelector('form.authform')
 authform.addEventListener("click", handleAuthEvent);