import type { Handle } from '@sveltejs/kit'; import * as auth from '$lib/server/auth'; import { db } from '$lib/server/db'; import * as table from '$lib/server/db/schema'; const handleAuth: Handle = async ({ event, resolve }) => { // 1. 먼저 액세스 토큰 확인 const accessToken = event.cookies.get(auth.jwtCookieName); if (accessToken) { const { userId, isValid } = auth.validateJwtToken(accessToken); if (isValid && userId) { event.locals.user = {id: userId}; return resolve(event); } // 액세스 토큰이 유효하지 않으면 refresh 시도 } // 2. 액세스 토큰이 없거나 유효하지 않을 때 리프레시 토큰 확인 const refreshToken = event.cookies.get(auth.refreshCookieName); if (!refreshToken) { // 두 토큰 모두 없거나 유효하지 않으면 인증되지 않은 사용자로 처리 event.locals.user = null; return resolve(event); } // 리프레시 토큰 검증 const { userId, isValid } = auth.validateRefreshToken(refreshToken); if (!isValid || !userId) { // 리프레시 토큰이 유효하지 않으면 모든 쿠키 삭제 auth.deleteAuthCookies(event); event.locals.user = null; return resolve(event); } // 유효한 리프레시 토큰이 있으면 사용자 정보 조회 const user = await db.query.refreshTokens.findFirst({ where: (refreshTokens, { eq }) => eq(refreshTokens.id, userId) }); if (!user) { auth.deleteAuthCookies(event); event.locals.user = null; return resolve(event); } // 새 액세스 토큰 발급 const newAccessToken = auth.generateAccessToken(user.id); auth.setAccessTokenCookie(event, newAccessToken); // 사용자 정보 설정 event.locals.user = { id: user.id, }; return resolve(event); }; export const handle: Handle = handleAuth;