Access Token 유무에 따른 자동 리다이렉트 구현

This commit is contained in:
static
2024-12-28 17:35:24 +09:00
parent c09a0b4aa0
commit 7267e319b4
3 changed files with 36 additions and 3 deletions

View File

@@ -1,4 +1,4 @@
import type { ServerInit } from "@sveltejs/kit";
import { redirect, type ServerInit, type Handle } from "@sveltejs/kit";
import schedule from "node-schedule";
import { cleanupExpiredRefreshTokens } from "$lib/server/db/token";
@@ -7,3 +7,17 @@ export const init: ServerInit = () => {
cleanupExpiredRefreshTokens();
});
};
export const handle: Handle = async ({ event, resolve }) => {
const path = event.url.pathname;
if (path.startsWith("/api") || path.startsWith("/auth")) {
return await resolve(event);
}
const accessToken = event.cookies.get("accessToken");
if (accessToken) {
return await resolve(event);
} else {
redirect(302, "/auth/login?redirect=" + encodeURIComponent(path));
}
};

View File

@@ -0,0 +1,13 @@
import { redirect } from "@sveltejs/kit";
import type { PageServerLoad } from "./$types";
export const load: PageServerLoad = async ({ url, cookies }) => {
const redirectPath = url.searchParams.get("redirect") || "/";
const accessToken = cookies.get("accessToken");
if (accessToken) {
redirect(302, redirectPath);
}
return { redirectPath };
};

View File

@@ -1,9 +1,12 @@
<script lang="ts">
import { goto } from "$app/navigation";
import { Button, TextButton } from "$lib/components/buttons";
import { TitleDiv, BottomDiv } from "$lib/components/divs";
import { TextInput } from "$lib/components/inputs";
import { requestLogin } from "./service";
let { data } = $props();
let email = $state("");
let password = $state("");
@@ -11,8 +14,11 @@
// TODO: Validation
const ok = await requestLogin(email, password);
// TODO: Action
if (ok) {
goto(data.redirectPath);
} else {
// TODO: Alert
}
};
</script>