aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/routes/sb1-authorize/+server.ts
blob: e08db3e0d1273004f8bb9bf533e419bcf352bc46 (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
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 text = await response.text()

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

    return new Response()
}