summaryrefslogtreecommitdiffhomepage
path: root/packages/console/app/src/routes/auth/callback.ts
blob: cdfc8822946d56bc16e9ca81f23d9321e86324a2 (plain)
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
import { redirect } from "@solidjs/router"
import { getResponseHeaders } from "@solidjs/start/http"
import type { APIEvent } from "@solidjs/start/server"
import { AuthClient } from "~/context/auth"
import { useAuthSession } from "~/context/auth.session"

export async function GET(input: APIEvent) {
  const url = new URL(input.request.url)
  const code = url.searchParams.get("code")
  if (!code) throw new Error("No code found")
  const result = await AuthClient.exchange(code, `${url.origin}${url.pathname}`)
  if (result.err) {
    throw new Error(result.err.message)
  }
  const decoded = AuthClient.decode(result.tokens.access, {} as any)
  if (decoded.err) throw new Error(decoded.err.message)
  const session = await useAuthSession()
  const id = decoded.subject.properties.accountID
  await session.update((value) => {
    return {
      ...value,
      account: {
        ...value.account,
        [id]: {
          id,
          email: decoded.subject.properties.email,
        },
      },
      current: id,
    }
  })
  return redirect("/auth", {
    status: 302,
    headers: getResponseHeaders(),
  })
}