Skip to content

Commit

Permalink
Try getting token from headers more directly, use locals for route bl…
Browse files Browse the repository at this point in the history
…ocking
  • Loading branch information
franknoirot committed Jul 20, 2024
1 parent ca0277d commit cc511ec
Show file tree
Hide file tree
Showing 5 changed files with 11 additions and 16 deletions.
1 change: 1 addition & 0 deletions src/app.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ declare global {
// interface Error {}
interface Locals {
user?: Models['User_type'] | Models['Error_type']
token?: string
}
// interface PageData {}
// interface Platform {}
Expand Down
4 changes: 3 additions & 1 deletion src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/routes/(sidebarLayout)/+layout.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, '/')
}
Expand Down
11 changes: 2 additions & 9 deletions src/routes/+layout.server.ts
Original file line number Diff line number Diff line change
@@ -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
}
}
10 changes: 4 additions & 6 deletions src/routes/+page.server.ts
Original file line number Diff line number Diff line change
@@ -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 || ''))
}
}

0 comments on commit cc511ec

Please sign in to comment.