✨ Improved authentication by checking the jwt in SvelteKit
This commit is contained in:
@@ -5,30 +5,39 @@
|
||||
*/
|
||||
|
||||
import type { Handle } from '@sveltejs/kit';
|
||||
import jws from 'jws';
|
||||
|
||||
/** @type {import('@sveltejs/kit').Handle} */
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
const res = await fetch(`${process.env.API_URL}/api/v1/users/check`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: event.request.headers.get('cookie') || ''
|
||||
}
|
||||
});
|
||||
if (res.ok) {
|
||||
event.locals.email = await res.text();
|
||||
const resp = await resolve(event);
|
||||
try {
|
||||
resp.headers.set('Set-Cookie', res.headers.get('set-cookie'));
|
||||
} catch {
|
||||
console.log('Cannot mutate immutable header');
|
||||
}
|
||||
|
||||
return resp;
|
||||
} else {
|
||||
const access_token = event.cookies.get('access_token');
|
||||
if (!access_token) {
|
||||
event.locals.email = null;
|
||||
return resolve(event);
|
||||
}
|
||||
const jwt = jws.decode(access_token.replace('Bearer ', ''));
|
||||
// if token expires, do a request to get a new one and set the response-cookies on the response
|
||||
if (Date.now() >= jwt.payload.exp * 1000) {
|
||||
const res = await fetch(`${process.env.API_URL}/api/v1/users/check`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: event.request.headers.get('cookie') || ''
|
||||
}
|
||||
});
|
||||
if (res.ok) {
|
||||
event.locals.email = await res.text();
|
||||
const resp = await resolve(event);
|
||||
console.log(res.headers.get('set-cookie'));
|
||||
try {
|
||||
resp.headers.set('Set-Cookie', res.headers.get('set-cookie'));
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
return resp;
|
||||
}
|
||||
}
|
||||
event.locals.email = jwt.payload.sub;
|
||||
return resolve(event);
|
||||
};
|
||||
|
||||
/*export const getSession: GetSession = async (event) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { signedIn } from '$lib/stores';
|
||||
import type { LayoutLoad } from './$types';
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
export const load: LayoutLoad = async ({ locals }) => {
|
||||
export const load: LayoutServerLoad = async ({ locals }) => {
|
||||
if (locals.email) {
|
||||
signedIn.set(true);
|
||||
} else {
|
||||
|
||||
@@ -2,7 +2,6 @@ import { redirect } from '@sveltejs/kit';
|
||||
|
||||
export const load = async ({ parent }) => {
|
||||
const { email } = await parent();
|
||||
|
||||
if (!email) {
|
||||
throw redirect(302, '/account/login?returnTo=/dashboard');
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
};
|
||||
$: {
|
||||
search_term;
|
||||
console.log(search_term);
|
||||
// console.log(search_term);
|
||||
search();
|
||||
}
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user