WIP 8737af8d
Steve · 2024-09-20 08:06 2 file(s) · +27 −43
src/pages/auth/callback.astro (deleted) +0 −43
1 -
---
2 -
import { createServerClient, parseCookieHeader } from "@supabase/ssr";
3 -
import { type APIRoute } from "astro";
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") || "/";
9 -
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(Astro.request.headers.get("Cookie") ?? "");
18 -
					},
19 -
					setAll(cookiesToSet) {
20 -
						cookiesToSet.forEach(({ name, value, options }) =>
21 -
							Astro.cookies.set(name, value, options),
22 -
						);
23 -
					},
24 -
				},
25 -
			},
26 -
		);
27 -
28 -
		const { error } = await supabase.auth.exchangeCodeForSession(code);
29 -
30 -
		if (!error) {
31 -
			return redirect(next);
32 -
		}
33 -
	}
34 -
35 -
	// return the user to an error page with instructions
36 -
	return redirect("/auth/auth-code-error");
37 -
};
38 -
---
39 -
40 -
<script>
41 -
  // This script will run on the client side to handle the redirect
42 -
  window.location.href = new URL(window.location.href).searchParams.get("next") || "/";
43 -
</script>
src/pages/auth/callback.ts (added) +27 −0
1 +
import type { APIRoute } from "astro";
2 +
import { supabase } from "../../../lib/supabase";
3 +
4 +
export const GET: APIRoute = async ({ url, cookies, redirect }) => {
5 +
	const authCode = url.searchParams.get("code");
6 +
7 +
	if (!authCode) {
8 +
		return new Response("No code provided", { status: 400 });
9 +
	}
10 +
11 +
	const { data, error } = await supabase.auth.exchangeCodeForSession(authCode);
12 +
13 +
	if (error) {
14 +
		return new Response(error.message, { status: 500 });
15 +
	}
16 +
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");
27 +
};