Skip to content

Commit

Permalink
Creating <AuthProvider /> (#26)
Browse files Browse the repository at this point in the history
AuthProvider usa las sugerencias de supabase para authenticación general
(no específicas de NextJS)


https://supabase.com/docs/guides/auth/sessions#can-i-use-http-only-cookies-to-store-the-access-and-refresh-tokens

https://supabase.com/docs/guides/auth/sessions#sign-out-and-scopes

<img width="526" alt="image"
src="https://github.com/JSConfCL/tickets/assets/952992/368d8294-8e6c-452b-9d71-152750be4484">

`<AuthProvider />` refresca la cookie en cada instancia que se carga (o
cada que updatea la sesión mediante el event handler de
`onAuthStateChange`.

`WIN:` Como está en el Layout, cada ruta recibe su propia instancia de
Auth, (Y asi seguimos una de las sugerencias del uso de NextJS al menos
🙏🏼 )
  • Loading branch information
fforres authored Apr 10, 2024
1 parent b752bb0 commit d01d801
Show file tree
Hide file tree
Showing 20 changed files with 360 additions and 386 deletions.
20 changes: 6 additions & 14 deletions app/(transition)/(root)/events/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { gql } from "@apollo/client";
import { getApolloClient } from "@/api/ApolloClient";
import { getApolloClientForRSC } from "@/api/ApolloClientForRSC";
import { MapPinIcon } from "@heroicons/react/24/outline";
import { Attendees } from "@/components/Event/Attendees/Attendees";
import { Hero } from "@/components/Event/Hero/Hero";
Expand All @@ -11,30 +10,23 @@ import { EventType, PageProps } from "./types";
import { GetEventDocument } from "./getEvent.generated";

export default async function Event({ searchParams }: PageProps) {
const c = getApolloClient();
const c = getApolloClientForRSC();
const { id } = searchParams;

const { data, error } = await c.query<EventType>({
query: GetEventDocument,
variables: {
input: id
}
input: id,
},
});

if (error) return <h2>Ocurrió un error cargando el evento</h2>;

const { event } = data;

if (!event) return <h2>No pudimos encontrar el evento que estás buscando</h2>;

const {
address,
community,
description,
name,
startDateTime,
users,
} = event;
const { address, community, description, name, startDateTime, users } = event;

const eventDate = new Date(startDateTime).toLocaleString();

Expand Down
28 changes: 5 additions & 23 deletions app/(transition)/(root)/login/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,24 @@ import { NextPage } from "next";

import { redirect } from "next/navigation";
import { useEffect, useState } from "react";
import { Session } from "@supabase/supabase-js";
import { Auth } from "@supabase/auth-ui-react";
import { ThemeSupa } from "@supabase/auth-ui-shared";
import { createClient } from "@/utils/supabase/client";
import { supabaseClient } from "@/utils/supabase/client";
import { useTheme } from "next-themes";

const supabase = createClient();
import { useIsLoggedIn } from "@/utils/supabase/AuthProvider";

const AuthPage: NextPage = () => {
const [session, setSession] = useState<Session | null>(null);
const { resolvedTheme } = useTheme();
const [url, setUrl] = useState<string | undefined>();

useEffect(() => {
const url = new URL(window.location.href);
url.pathname = "/";
url.hash = "";
setUrl(url.toString());

// eslint-disable-next-line @typescript-eslint/no-floating-promises
supabase.auth.getSession().then(async ({ data: { session } }) => {
setSession(session);
await supabase.auth.startAutoRefresh();
});

const {
data: { subscription },
} = supabase.auth.onAuthStateChange(async (_event, session) => {
await supabase.auth.startAutoRefresh();
setSession(session);
});

return () => subscription.unsubscribe();
}, []);

if (session) {
const isLoggedIn = useIsLoggedIn();
if (isLoggedIn) {
redirect("/");
}

Expand All @@ -55,7 +37,7 @@ const AuthPage: NextPage = () => {

<Auth
providers={["github", "twitter"]}
supabaseClient={supabase}
supabaseClient={supabaseClient}
socialLayout="horizontal"
showLinks={false}
view="magic_link"
Expand Down
8 changes: 4 additions & 4 deletions app/(transition)/(root)/page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { getApolloClient } from "../../../src/api/ApolloClient";
import { getApolloClientForRSC } from "../../../src/api/ApolloClientForRSC";
import { LandingPageEvents } from "../../../src/components/features/LandingPageEvents";
import {
FetchExampleEventsDocument,
FetchExampleEventsQuery,
} from "../../../src/components/features/LandingPageEvents/graphql/FetchExampleEvents.generated";

export default async function Home() {
const c = getApolloClient();
const c = getApolloClientForRSC();
const variable = await c.query<FetchExampleEventsQuery>({
query: FetchExampleEventsDocument,
});
Expand All @@ -18,13 +18,13 @@ export default async function Home() {
</h1>
</div>
<div className="flex flex-col gap-4">
<h1>RSC</h1>
<h1 className="text-3xl">RSC</h1>
{variable.data?.events?.map((event) => (
<div key={event.id}>{event.id}</div>
))}
</div>
<div className="flex flex-col gap-4">
<h1>Client fetching</h1>
<h1 className="text-3xl">Client fetching</h1>
<LandingPageEvents />
</div>
</main>
Expand Down
44 changes: 7 additions & 37 deletions app/(transition)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,46 +1,16 @@
"use client";
import { AnimatePresence, LazyMotion, domAnimation } from "framer-motion";
import React, { useEffect, useState } from "react";
import React from "react";

import { createClient } from "@/utils/supabase/client";
import { AuthProvider } from "@/utils/supabase/AuthProvider";

export default function Layout({ children }: { children: React.ReactNode }) {
const supabase = createClient();

useEffect(() => {
const start = async () => {
const { data } = await supabase.auth.getSession();
const accessToken = data?.session?.access_token;

const localStorageKey = process.env.NEXT_PUBLIC_TOKEN_STORAGE_KEY;
if (!accessToken || !localStorageKey) {
return;
}

window.localStorage.setItem(
process.env.NEXT_PUBLIC_TOKEN_STORAGE_KEY!,
accessToken,
);
console.log({ accessToken });
};

const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event, session) => {
// TODO: handle token
});

start().catch((e) => {
console.error(e);
});

return () => subscription.unsubscribe();
}, []);

return (
<LazyMotion features={domAnimation}>
<AnimatePresence mode="sync">{children}</AnimatePresence>
</LazyMotion>
<AuthProvider>
<LazyMotion features={domAnimation}>
<AnimatePresence mode="sync">{children}</AnimatePresence>
</LazyMotion>
</AuthProvider>
);
}

Expand Down
19 changes: 0 additions & 19 deletions middleware.ts

This file was deleted.

Loading

0 comments on commit d01d801

Please sign in to comment.