import { browser } from '$app/environment'; import { base } from '$app/paths'; import { redirect } from '@sveltejs/kit'; import type { ClientSession } from '../hooks.server'; import { goto } from '$app/navigation'; /** * Returns `true` if scopes are all included in session, otherwise either attempts to re-login with the new scope added (unless `getScopeOnFail` is false) and returns false * * Check the return value of this, even if getScopeOnFail is true; navigating client-side may not stop thread immediately! */ export const checkScope = ( session: ClientSession | null | undefined, /** The scopes we want */ neededScopes: string[], /** Redirect to login page if the scopes aren't found */ getScopeOnFail = false, /** The target URL if redirecting */ next?: string ) => { const scopes = session?.tokens.scope?.split(' ') ?? []; if (!neededScopes.find((v) => !scopes.includes(v))) return true; else if (getScopeOnFail) { const targetUrl = `${base}/login?${ next || browser ? `next=${next ?? encodeURIComponent(location.href)}&` : '' }scope=${encodeURIComponent( [...scopes, ...neededScopes] .filter((v, i, a) => a.indexOf(v) === i) .join(' ') )}`; if (browser) goto(targetUrl); else throw redirect(307, targetUrl); } return false; };