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