fix auth redirects

This commit is contained in:
liyunze 2026-08-31 19:28:01 +08:00
parent f826141940
commit 35b0d8020d
3 changed files with 25 additions and 17 deletions

View file

@ -7,22 +7,28 @@ export const isAuthenticated = writable(false);
const STORAGE_KEY = "dsec_session";
export async function initAuth() {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
try {
const { token } = JSON.parse(stored);
const user = await query("users:getByToken", { token });
if (user) {
currentUser.set(user as UserDoc);
isAuthenticated.set(true);
} else {
let initPromise: Promise<void> | null = null;
export function initAuth(): Promise<void> {
if (initPromise) return initPromise;
initPromise = (async () => {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
try {
const { token } = JSON.parse(stored);
const user = await query("users:getByToken", { token });
if (user) {
currentUser.set(user as UserDoc);
isAuthenticated.set(true);
} else {
localStorage.removeItem(STORAGE_KEY);
}
} catch {
localStorage.removeItem(STORAGE_KEY);
}
} catch {
localStorage.removeItem(STORAGE_KEY);
}
}
})();
return initPromise;
}
function setSession(result: { userId: string; token: string; name: string }, email: string) {

View file

@ -1,6 +1,6 @@
<script lang="ts">
import { query, mutation } from "$lib/api";
import { isAuthenticated, getToken } from "$lib/stores/auth";
import { isAuthenticated, getToken, initAuth } from "$lib/stores/auth";
import { goto } from "$app/navigation";
import { onMount } from "svelte";
import { get } from "svelte/store";
@ -19,8 +19,9 @@
let success = $state("");
onMount(async () => {
await initAuth();
if (!get(isAuthenticated)) {
goto("/auth/login");
goto("/auth/login", { replaceState: true });
return;
}
const [t, u] = await Promise.all([query("topics:getAll"), query("units:getAll")]);

View file

@ -1,6 +1,6 @@
<script lang="ts">
import { query, mutation } from "$lib/api";
import { isAuthenticated, getToken } from "$lib/stores/auth";
import { isAuthenticated, getToken, initAuth } from "$lib/stores/auth";
import { goto } from "$app/navigation";
import { onMount } from "svelte";
import { get } from "svelte/store";
@ -19,8 +19,9 @@
let success = $state("");
onMount(async () => {
await initAuth();
if (!get(isAuthenticated)) {
goto("/auth/login");
goto("/auth/login", { replaceState: true });
return;
}
const [t, u] = await Promise.all([query("topics:getAll"), query("units:getAll")]);