-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Replace hooks.server.ts with +layout.server.ts (#146)
- Loading branch information
1 parent
0100257
commit b36ec3e
Showing
2 changed files
with
56 additions
and
68 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, '/') | ||
} | ||
} |