diff --git a/src/app.d.ts b/src/app.d.ts index 7e2ab5c..491ebb8 100644 --- a/src/app.d.ts +++ b/src/app.d.ts @@ -6,6 +6,7 @@ declare global { // interface Error {} interface Locals { user?: Models['User_type'] | Models['Error_type'] + token?: string } // interface PageData {} // interface Platform {} diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 4f15ae4..e340a5f 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -7,11 +7,13 @@ import { hooksUserMocks, isUserMock } from '$lib/mocks' export const handle = async ({ event, resolve }) => { const mock = event.request.headers.get(PLAYWRIGHT_MOCKING_HEADER) const token = import.meta.env.PROD - ? event.cookies.get(AUTH_COOKIE_NAME) + ? event.request.headers.get(AUTH_COOKIE_NAME) : import.meta.env.VITE_TOKEN if (!token) { return resolve(event) + } else { + event.locals.token = token } const currentUser = await event diff --git a/src/routes/(sidebarLayout)/+layout.server.ts b/src/routes/(sidebarLayout)/+layout.server.ts index 6e7fdad..f858a47 100644 --- a/src/routes/(sidebarLayout)/+layout.server.ts +++ b/src/routes/(sidebarLayout)/+layout.server.ts @@ -5,6 +5,7 @@ import { redirect } from '@sveltejs/kit' export const load = async ({ locals, cookies }) => { // redirect user if not logged in if (!locals.user) { + locals.token = undefined cookies.delete(AUTH_COOKIE_NAME, { domain: DOMAIN, path: '/' }) throw redirect(302, '/') } diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index 44fcef9..8c75d3c 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -1,14 +1,7 @@ -import { AUTH_COOKIE_NAME } from '$lib/cookies.js' - /** @type {import('./$types').LayoutData} */ -export const load = async ({ locals, cookies }) => { - const token = - import.meta.env.MODE === 'production' - ? cookies.get(AUTH_COOKIE_NAME) - : import.meta.env.VITE_TOKEN - +export const load = async ({ locals }) => { return { user: !locals.user || 'error_code' in locals.user ? undefined : locals.user, - token + token: locals.token } } diff --git a/src/routes/+page.server.ts b/src/routes/+page.server.ts index 4c231dc..81be42f 100644 --- a/src/routes/+page.server.ts +++ b/src/routes/+page.server.ts @@ -1,10 +1,8 @@ -import { AUTH_COOKIE_NAME } from '$lib/cookies.js' +import { paths } from '$lib/paths.js' import { redirect } from '@sveltejs/kit' -export const load = async ({ cookies, url }) => { - const token = import.meta.env.PROD ? cookies.get(AUTH_COOKIE_NAME) : import.meta.env.VITE_TOKEN - - if (token) { - throw redirect(302, '/dashboard' + (url.search || '')) +export const load = async ({ url, locals }) => { + if (locals.token && locals.user) { + throw redirect(302, paths.DASHBOARD + (url.search || '')) } }