aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/login/callback/+server.ts
blob: 1de781197f62e512095979d1f30682d0ec5375f5 (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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { base } from '$app/paths';
import * as auth from '$lib/auth.server.js';
import { error, isHttpError, isRedirect, json, redirect } from '@sveltejs/kit';
import * as client from 'openid-client';

// Pre-checker for nonce, not the primary implementation
const handleNonce = (nonce: string | null, nonceCookie: string | undefined) => {
  if (nonce) {
    try {
      const n = JSON.parse(nonceCookie ?? '[]');
      if (Array.isArray(n) && n.length && typeof n[0] === 'string') {
        if (!n.includes(nonce)) throw error(400, 'Nonce not in array');
        else return n.filter((v) => v !== nonce);
      } else throw error(400, 'Nonce provided, but nonce cookie not found');
    } catch (e) {
      throw error(400, `Failed parsing nonce: ${e}`);
    }
  } else if (nonceCookie) throw error(400, 'Missing Nonce');
};
export const GET = async (event) => {
  const sp = event.url.searchParams;

  const remainingNonces = handleNonce(
    sp.get('nonce'),
    event.cookies.get('pending-auth-nonces')
  );

  try {
    const tokens = await auth.authorizeNewSession(
      new URL(event.url.href),
      sp.get('nonce') ?? undefined
    );

    auth.setCookies(event.cookies, tokens);
    event.cookies.set('pending-auth-nonces', JSON.stringify(remainingNonces), {
      path: '/',
      secure: true,
      sameSite: true,
      httpOnly: true,
    });

    let target = event.cookies.get('next') ?? '/';
    if (new URL(target, event.url.href).host !== event.url.host) target = '/';
    event.cookies.delete('next', {
      path: '/',
    });
    throw redirect(
      303,
      `${base}/login/callback/ok?next=${encodeURIComponent(target)}`
    );
  } catch (e) {
    if (isRedirect(e) || isHttpError(e)) throw e;
    // @ts-ignore
    if (e?.cause?.error === 'invalid_grant')
      throw error(
        403,
        'Invalid Grant Provided - Does your account have access to all requested resources?'
      );
    else
      throw error(
        500,
        `Could not authorize new session: ${JSON.stringify(e, null, 2)}`
      );
  }
};