update callback 547cfeda
Steve · 2024-09-20 15:38 1 file(s) · +20 −29
src/pages/auth/callback.ts +20 −29
1 -
import { createServerClient, parseCookieHeader } from "@supabase/ssr";
2 -
import type { APIRoute } from "astro";
3 1
export const prerender = false;
2 +
import type { APIRoute } from "astro";
3 +
import { supabase } from "../../lib/supabase";
4 4
5 -
export const GET: APIRoute = async ({ request, cookies, redirect }) => {
6 -
	const requestUrl = new URL(request.url);
7 -
	const code = requestUrl.searchParams.get("code");
8 -
	const next = requestUrl.searchParams.get("next") || "/";
5 +
export const GET: APIRoute = async ({ url, cookies, redirect }) => {
6 +
	const authCode = url.searchParams.get("code");
9 7
10 -
	if (code) {
11 -
		const supabase = createServerClient(
12 -
			import.meta.env.PUBLIC_SUPABASE_URL,
13 -
			import.meta.env.PUBLIC_SUPABASE_ANON_KEY,
14 -
			{
15 -
				cookies: {
16 -
					getAll() {
17 -
						return parseCookieHeader(request.headers.get("Cookie") ?? "");
18 -
					},
19 -
					setAll(cookiesToSet) {
20 -
						cookiesToSet.forEach(({ name, value, options }) =>
21 -
							cookies.set(name, value, options),
22 -
						);
23 -
					},
24 -
				},
25 -
			},
26 -
		);
8 +
	if (!authCode) {
9 +
		return new Response("No code provided", { status: 400 });
10 +
	}
27 11
28 -
		const { error } = await supabase.auth.exchangeCodeForSession(code);
12 +
	const { data, error } = await supabase.auth.exchangeCodeForSession(authCode);
29 13
30 -
		if (!error) {
31 -
			return redirect("/log");
32 -
		}
14 +
	if (error) {
15 +
		return new Response(error.message, { status: 500 });
33 16
	}
34 17
35 -
	// return the user to an error page with instructions
36 -
	return redirect("/auth/auth-code-error");
18 +
	const { access_token, refresh_token } = data.session;
19 +
20 +
	cookies.set("sb-access-token", access_token, {
21 +
		path: "/",
22 +
	});
23 +
	cookies.set("sb-refresh-token", refresh_token, {
24 +
		path: "/",
25 +
	});
26 +
27 +
	return redirect("/log");
37 28
};