Skip to content

Commit

Permalink
Replace hooks.server.ts with +layout.server.ts (#146)
Browse files Browse the repository at this point in the history
  • Loading branch information
franknoirot authored Jul 20, 2024
1 parent 0100257 commit b36ec3e
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 68 deletions.
63 changes: 0 additions & 63 deletions src/hooks.server.ts

This file was deleted.

61 changes: 56 additions & 5 deletions src/routes/(sidebarLayout)/+layout.server.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,62 @@
import { DOMAIN } from '$lib/consts.js'
import { DOMAIN, PLAYWRIGHT_MOCKING_HEADER } from '$lib/consts.js'
import { AUTH_COOKIE_NAME } from '$lib/cookies.js'
import { hooksUserMocks, isUserMock } from '$lib/mocks.js'
import { SIGN_OUT_PARAM } from '$lib/paths.js'
import { redirect } from '@sveltejs/kit'

export const load = async ({ locals, cookies }) => {
// redirect user if not logged in
if (!locals.user) {
export const load = async ({ cookies, request, url, fetch }) => {
if (url.searchParams.get(SIGN_OUT_PARAM)) {
signOut()
}

const mockRequestHeader = request.headers.get(PLAYWRIGHT_MOCKING_HEADER)
const token = import.meta.env.PROD ? cookies.get(AUTH_COOKIE_NAME) : import.meta.env.VITE_TOKEN

if (!token) {
signOut()
}

const currentUser = await fetch(import.meta.env.VITE_API_BASE_URL + '/user', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
})
.then((res) => res.json())
.catch((e) => {
// If the user had a token but there was an error fetching the user,
//delete the token, because it was likely revoked or expired
console.error('Error fetching user:', e)
signOut()
})

if (!currentUser) {
signOut()
} else {
if ('error_code' in currentUser) {
console.error('Error fetching user:', currentUser.error_code)
signOut()
} else if (mockRequestHeader !== null) {
const userMock = isUserMock(mockRequestHeader)
return {
user: userMock ? hooksUserMocks[userMock](currentUser) : currentUser,
token
}
}

// Return the user and token
return {
user: currentUser,
token: token
}
}

/**
* Shared sign out function
*/
function signOut() {
cookies.delete(AUTH_COOKIE_NAME, { domain: DOMAIN, path: '/' })
throw redirect(302, '/')
throw redirect(303, '/')
}
}

0 comments on commit b36ec3e

Please sign in to comment.