blob: 92b22a33b4bb6049520b97ec3d80e1805351bacf (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
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;
};
|