aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/routes/sb1-authorize/+server.ts
blob: b3a0cf73d1c01c69f8925a415befbe8938c5fcaa (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
import { error, redirect } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { db } from '$lib/server/db';
import { syncSession } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
import { SB1_ID, SB1_REDIRECT_URI, SB1_SECRET } from '$env/static/private';
import { Temporal } from "temporal-polyfill"

export const GET: RequestHandler = async ({ url }) => {
    const code = url.searchParams.get('code')
    const state = url.searchParams.get('state');

    if (!code) error(400, "?code is missing")
    if (!state) error(400, "?state is missing")

    const session = await db.select().from(syncSession).where(eq(syncSession.authzState, state))
    const { id } = session[0]

    const fd = new URLSearchParams()
    fd.set("client_id", SB1_ID)
    fd.set("client_secret", SB1_SECRET)
    fd.set("redirect_uri", SB1_REDIRECT_URI)
    fd.set("code", code)
    fd.set("state", state)
    fd.set("grant_type", "authorization_code")
    const response = await fetch("https://api.sparebank1.no/oauth/token", {
        method: "post",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: fd
    })

    const json = await response.json()

    if (response.ok) {
        const epoch = Temporal.Now.instant().epochMilliseconds
        await db.update(syncSession).set({ tokens: json, accessTokenCreated: epoch.toString(), refreshTokenCreated: epoch.toString() }).where(eq(syncSession.id, id))
        redirect(302, "/")
    } else {
        return new Response(json)
    }

    return new Response()
}