Skip to content

Commit

Permalink
fix(console): use i18n.resolveRoute for all server-side redirect)
Browse files Browse the repository at this point in the history
  • Loading branch information
xmlking committed Jan 24, 2024
1 parent fe0333f commit 6f9936c
Show file tree
Hide file tree
Showing 8 changed files with 20 additions and 22 deletions.
2 changes: 1 addition & 1 deletion apps/console/src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ import { sequence } from '@sveltejs/kit/hooks';
import { auth, guard, lang, theme } from '$lib/server/middleware';

// NOTE: Order is impotent! `auth` middleware sets `nhost` into `local` which is used by `guard` middleware
export const handle = sequence(auth, guard, lang, theme);
export const handle = sequence(lang, auth, guard, theme);
2 changes: 1 addition & 1 deletion apps/console/src/lib/server/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const auth = (async ({ event, resolve }) => {
event.cookies.delete(NHOST_SESSION_KEY, { path: '/' });
// TODO: should we throw error and desply error to user?
log.error('auth error:', error);
redirect(303, 'auth/signin');
redirect(303, i18n.resolveRoute('auth/signin'));
}

event.cookies.set(NHOST_SESSION_KEY, btoa(JSON.stringify(newSession)), { path: '/' });
Expand Down
20 changes: 9 additions & 11 deletions apps/console/src/lib/server/middleware/guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { redirect } from '@sveltejs/kit';
import type { Handle } from '@sveltejs/kit';
import { Logger, startsWith } from '@spectacular/utils';
import { building } from '$app/environment';
import { i18n } from '$lib/i18n.js'
/**
* Protect the route
* This should be the next middleware after auth middleware.
Expand All @@ -21,20 +22,17 @@ export const guard = (async ({ event, resolve }) => {
// get user roles
// check if role has access to target route

const {
url: { pathname, origin },
locals: { nhost }
} = event;

const { url: { pathname }, locals: { lang, nhost } } = event;
const canonicalPath = i18n.route(pathname)
// bypass guard for all unprotected routes.
if (!startsWith(pathname, protectedPaths)) {
if (!startsWith(canonicalPath, protectedPaths)) {
return await resolve(event);
}

const { isAuthenticated, isLoading } = nhost.auth.getAuthenticationStatus();
log.debug({ isAuthenticated, isLoading });
log.debug({ isAuthenticated, isLoading, lang });
if (!isAuthenticated) {
redirect(303, `${origin}/auth/signin?callbackUrl=${pathname}`);
redirect(303, i18n.resolveRoute(`/auth/signin?callbackUrl=${pathname}`));
}

const session = nhost.auth.getSession();
Expand All @@ -47,7 +45,7 @@ export const guard = (async ({ event, resolve }) => {
log.debug('session expired at: ', tokenExpirationTime);
// FIXME: redirect from middleware may cause recursion
// event.cookies.delete(NHOST_SESSION_KEY, { path: '/' })
redirect(303, `${origin}/logout?callbackUrl=/blog`);
redirect(303, i18n.resolveRoute('/logout?callbackUrl=/blog'));
}

// const user = nhost.auth.getUser()
Expand All @@ -59,12 +57,12 @@ export const guard = (async ({ event, resolve }) => {

if (startsWith(pathname, userPaths)) {
if (!roles?.includes('user')) {
redirect(303, `${origin}/home`);
redirect(303, i18n.resolveRoute('/home'));
}
}
if (startsWith(pathname, adminPaths)) {
if (!roles?.includes('supervisor')) {
redirect(303, `${origin}/dashboard`);
redirect(303, i18n.resolveRoute('/dashboard'));
}
}

Expand Down
1 change: 0 additions & 1 deletion apps/console/src/lib/server/middleware/rate-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ export const rateLimiter = (async ({ event, resolve }) => {
const status = await limiter.check(event);
log.debug({ status });

console.log(status);
if (status.limited) {
event.setHeaders({
'Retry-After': status.retryAfter.toString()
Expand Down
2 changes: 0 additions & 2 deletions apps/console/src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import '../app.pcss';
export let data;
console.log({ data });
// Floating UI for Popups
storePopup.set({ computePosition, autoUpdate, flip, shift, offset, arrow });
Expand All @@ -45,7 +44,6 @@
};
function matchPathWhitelist(pathname: string): boolean {
console.log({ pathname });
// If homepage route
if (i18n.route(pathname) === '/') return true;
// If any blog route `/blog`
Expand Down
5 changes: 3 additions & 2 deletions apps/console/src/routes/auth/signin/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { NhostClient, Provider } from '@nhost/nhost-js';
import { userSchema } from '$lib/schema/user';
import { NHOST_SESSION_KEY } from '$lib/nhost';
import { limiter } from '$lib/server/limiter/limiter';
import { i18n } from '$lib/i18n';

const pwSchema = userSchema.pick({
email: true,
Expand All @@ -30,7 +31,7 @@ export const load = async (event) => {

const session = nhost.auth.getSession();
log.debug(session);
if (session) redirectWithFlash(302, '/dashboard');
if (session) redirectWithFlash(302, i18n.resolveRoute('/dashboard'));
const pwForm = await superValidate(zod(pwSchema));
const pwlForm = await superValidate(zod(pwlSchema));
return { pwForm, pwlForm };
Expand Down Expand Up @@ -77,7 +78,7 @@ export const actions = {
if (session) {
cookies.set(NHOST_SESSION_KEY, btoa(JSON.stringify(session)), { path: '/' });
const message: App.Superforms.Message = { type: 'success', message: 'Signin sucessfull 😎' } as const;
redirectWithFlash(303, '/dashboard', message, event);
redirectWithFlash(303, i18n.resolveRoute('/dashboard'), message, event);
}

// This line should never reach.
Expand Down
5 changes: 3 additions & 2 deletions apps/console/src/routes/auth/signout/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Logger } from '@spectacular/utils';
import { redirect } from '@sveltejs/kit';
import { NHOST_SESSION_KEY } from '$lib/nhost';
import { i18n } from '$lib/i18n';
import type { Actions } from './$types';

const log = new Logger('server:auth:signout');
Expand All @@ -12,7 +13,7 @@ export const actions = {
await nhost.auth.signOut();
cookies.set(NHOST_SESSION_KEY, '', { httpOnly: true, path: '/', maxAge: 0 });

throw redirect(303, '/');
// throw redirect(303, '/signin')
throw redirect(303, i18n.resolveRoute('/'));
// throw redirect(303, i18n.resolveRoute('/signin'));
}
} satisfies Actions;
5 changes: 3 additions & 2 deletions apps/console/src/routes/auth/signup/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Logger } from '@spectacular/utils';
import { userSchema } from '$lib/schema/user';
import { NHOST_SESSION_KEY } from '$lib/nhost';
import { limiter } from '$lib/server/limiter/limiter';
import { i18n } from '$lib/i18n';

const signUpSchema = userSchema.pick({
firstName: true,
Expand All @@ -29,7 +30,7 @@ export const load = async (event) => {

const session = nhost.auth.getSession();
log.debug(session);
if (session) redirectWithFlash(302, '/dashboard');
if (session) redirectWithFlash(302, i18n.resolveRoute('/dashboard'));
const form = await superValidate(zod(signUpSchema));
return { form };
};
Expand Down Expand Up @@ -89,7 +90,7 @@ export const actions = {
if (session) {
cookies.set(NHOST_SESSION_KEY, btoa(JSON.stringify(session)), { path: '/' });
const message: App.Superforms.Message = { type: 'success', message: 'Signup sucessfull 😎' } as const;
redirectWithFlash(303, '/dashboard', message, event);
redirectWithFlash(303, i18n.resolveRoute('/dashboard'), message, event);
}

// This line should never reach.
Expand Down

0 comments on commit 6f9936c

Please sign in to comment.