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,7 +7,11 @@ export const isAuthenticated = writable(false);
const STORAGE_KEY = "dsec_session"; const STORAGE_KEY = "dsec_session";
export async function initAuth() { let initPromise: Promise<void> | null = null;
export function initAuth(): Promise<void> {
if (initPromise) return initPromise;
initPromise = (async () => {
const stored = localStorage.getItem(STORAGE_KEY); const stored = localStorage.getItem(STORAGE_KEY);
if (stored) { if (stored) {
try { try {
@ -23,6 +27,8 @@ export async function initAuth() {
localStorage.removeItem(STORAGE_KEY); localStorage.removeItem(STORAGE_KEY);
} }
} }
})();
return initPromise;
} }
function setSession(result: { userId: string; token: string; name: string }, email: string) { function setSession(result: { userId: string; token: string; name: string }, email: string) {

View file

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

View file

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