Skip to content

Commit

Permalink
Fix home redirect behavior when credentials are bad
Browse files Browse the repository at this point in the history
  • Loading branch information
franknoirot committed Mar 21, 2024
1 parent 51c4118 commit a7e6f62
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
4 changes: 2 additions & 2 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ 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)
: import.meta.env.VITE_TOKEN
: import.meta.env.VITE_ZOO_DEV_TOKEN

if (!token && !unProtectedRoutes.includes(event.url.pathname)) {
throw redirect(303, '/')
Expand All @@ -32,7 +32,7 @@ export const handle = async ({ event, resolve }) => {
throw error(500, e)
})

if (!currentUser) {
if (!currentUser || 'message' in currentUser) {
event.locals.user = undefined
if (!unProtectedRoutes.includes(event.url.pathname)) throw redirect(303, '/')
} else {
Expand Down
28 changes: 24 additions & 4 deletions src/routes/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,30 @@
import { AUTH_COOKIE_NAME } from '$lib/cookies.js'
import { redirect } from '@sveltejs/kit'
import { error, redirect } from '@sveltejs/kit'
import type { Models } from '@kittycad/lib'

export const load = async ({ cookies, url }) => {
const token = import.meta.env.PROD ? cookies.get(AUTH_COOKIE_NAME) : import.meta.env.VITE_TOKEN
export const load = async ({ cookies, url, fetch }) => {
const token = import.meta.env.PROD
? cookies.get(AUTH_COOKIE_NAME)
: import.meta.env.VITE_ZOO_DEV_TOKEN

if (token) {
const currentUser = await fetch(import.meta.env.VITE_API_BASE_URL + '/user', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
})
.then(async (res) => (await res.json()) as Models['User_type'] | Models['Error_type'])
.catch((e) => {
throw error(500, e)
})

// Redirect to the dashboard if the user is already logged in
if (currentUser && 'email' in currentUser) {
throw redirect(302, '/dashboard' + (url.search || ''))
} else if (import.meta.env.DEV) {
console.warn(
'You might be using an invalid or expired token for your VITE_ZOO_DEV_TOKEN environment variable. Please check your .env file.'
)
}
}

0 comments on commit a7e6f62

Please sign in to comment.