33 lines
1.1 KiB
TypeScript
33 lines
1.1 KiB
TypeScript
import { redirect, type Handle } from "@sveltejs/kit";
|
|
import { sequence } from "@sveltejs/kit/hooks";
|
|
import { createTRPCHandle } from "trpc-sveltekit";
|
|
|
|
import { skAuthHandle } from "$lib/server/auth";
|
|
import { createContext } from "$lib/server/trpc/context";
|
|
import { router } from "$lib/server/trpc/router";
|
|
|
|
/**
|
|
* Protect the application against unauthorized access.
|
|
* If the user is not logged in, all requests get redirected to the login page
|
|
* with the exception of the login page and the TRPC API (which has its own
|
|
* auth mechanism)
|
|
*/
|
|
const authorization: Handle = async ({ event, resolve }) => {
|
|
// Allowed pages without login: TRPC API (has its own auth hook), Auth.js internal
|
|
// pages and the login site
|
|
if (!/^\/(login|trpc)/.test(event.url.pathname)) {
|
|
if (!event.locals.session) {
|
|
const params = new URLSearchParams({ returnURL: event.url.pathname });
|
|
redirect(303, `/login?${params.toString()}`);
|
|
}
|
|
}
|
|
|
|
// If the request is still here, just proceed as normally
|
|
return resolve(event);
|
|
};
|
|
|
|
export const handle = sequence(
|
|
skAuthHandle,
|
|
authorization,
|
|
createTRPCHandle({ router, createContext }),
|
|
);
|