summaryrefslogtreecommitdiff
path: root/apps/web/app/auth/callback/route.ts
blob: a912da3926bbb890e7d1d103083127f5d4ef7985 (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
import { NextResponse } from "next/server"
import { createSupabaseServerClient } from "@/lib/supabase/server"
import type { EmailOtpType } from "@supabase/supabase-js"

function sanitizeRedirectPath(rawPath: string | null): string {
  if (!rawPath) return "/reader"
  if (!rawPath.startsWith("/")) return "/reader"
  if (rawPath.startsWith("//")) return "/reader"
  if (rawPath.includes("\\")) return "/reader"

  return rawPath
}

export async function GET(request: Request) {
  const { searchParams, origin } = new URL(request.url)
  const code = searchParams.get("code")
  const tokenHash = searchParams.get("token_hash")
  const type = searchParams.get("type") as EmailOtpType | null
  const next = sanitizeRedirectPath(searchParams.get("next"))

  const supabaseClient = await createSupabaseServerClient()

  if (tokenHash && type) {
    const { error } = await supabaseClient.auth.verifyOtp({
      token_hash: tokenHash,
      type,
    })

    if (!error) {
      return NextResponse.redirect(`${origin}${next}`)
    }
  }

  if (code) {
    const { error } = await supabaseClient.auth.exchangeCodeForSession(code)

    if (!error) {
      return NextResponse.redirect(`${origin}${next}`)
    }
  }

  return NextResponse.redirect(`${origin}/sign-in?error=auth`)
}