fix(web): guard authenticated routes instead of asserting the session user
library, playlists and playlists/[id] read locals.user!.sub with no check, so an anonymous request threw a TypeError and returned 500 instead of redirecting to login. Adds requireUser(), which redirects to /login?returnTo=... and returns a non-null SessionUser, and drops the five non-null assertions. /upload had no load at all: the page rendered for anonymous users and only failed on submit. It now redirects up front.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import createClient from 'openapi-fetch';
|
||||
import { error, fail, type ActionFailure } from '@sveltejs/kit';
|
||||
import { error, fail, redirect, type ActionFailure } from '@sveltejs/kit';
|
||||
import type { paths } from '$lib/api/schema';
|
||||
import type { SessionUser } from '$lib/types';
|
||||
import { apiConfig } from '$lib/server/config';
|
||||
|
||||
interface ApiClientOptions {
|
||||
@@ -16,6 +17,11 @@ export function createApiClient({ fetch, accessToken }: ApiClientOptions) {
|
||||
});
|
||||
}
|
||||
|
||||
export function requireUser(locals: App.Locals, url: URL): SessionUser {
|
||||
if (!locals.user) redirect(302, `/login?returnTo=${encodeURIComponent(url.pathname + url.search)}`);
|
||||
return locals.user;
|
||||
}
|
||||
|
||||
export function requireAccessToken(locals: App.Locals, message = 'Inicia sesión.'): string {
|
||||
if (!locals.accessToken) error(401, message);
|
||||
return locals.accessToken;
|
||||
|
||||
Reference in New Issue
Block a user