Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lego/feat/supabase auth #24

Merged
merged 11 commits into from
Apr 17, 2024
3 changes: 2 additions & 1 deletion .env.local.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
NEXT_PUBLIC_JSCL_API_URL='https://api.jsconf.dev/graphql'
NEXT_PUBLIC_TOKEN_STORAGE_KEY='HS:token_storage_key'
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY='pk_test_ZnVua3ktZ3JpZmZvbi04NC5jbGVyay5hY2NvdW50cy5kZXYk'
NEXT_PUBLIC_GOOGLE_MAPS_KEY='your_google_maps_key_here'
NEXT_PUBLIC_SUPABASE_URL='your_supabase_url'
NEXT_PUBLIC_SUPABASE_ANON_KEY='your_supabase_key'
93 changes: 93 additions & 0 deletions app/(transition)/(root)/login/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"use client";

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 { useTheme } from "next-themes";

const supabase = createClient();

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) {
redirect("/");
}

return (
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pense q ibamos a redirigir a auth.jschile.org 🤔
O eso pa después?

<div className="min-h-[calc(100dvh-57px)] w-full bg-muted px-4 pt-8">
<div className="m-auto flex w-full max-w-lg shrink-0 flex-col gap-4 rounded-2xl bg-background p-10 shadow-xl">
<div>
<h1 className="text-left text-2xl font-bold">Regístrate.</h1>
<p className="text-left text-sm text-muted-foreground">
Mantente al tanto de las novedades de JavaScript Chile.
</p>
</div>

<Auth
providers={["github", "twitter"]}
supabaseClient={supabase}
socialLayout="horizontal"
showLinks={false}
view="magic_link"
redirectTo={url}
localization={{
variables: {
magic_link: {
email_input_label: "Correo electrónico",
email_input_placeholder: "Ingresa tu correo electrónico",
button_label: "Enviar enlace mágico ✨",
confirmation_text: "Revisa tu correo electrónico",
empty_email_address: "Debes ingresar un correo electrónico",
loading_button_label: "Enviando...",
},
},
}}
appearance={{
theme: ThemeSupa,
variables: {
default: {
colors: {
brand: "#000",
brandAccent: "#2a2a2a",
},
},
},
}}
theme={resolvedTheme}
/>
</div>
</div>
);
};

export default AuthPage;
30 changes: 21 additions & 9 deletions app/(transition)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,42 @@
"use client";
import { useAuth } from "@clerk/clerk-react";
import { AnimatePresence, LazyMotion, domAnimation } from "framer-motion";
import React, { useEffect } from "react";
import React, { useEffect, useState } from "react";

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

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

useEffect(() => {
const start = async () => {
const token = await getToken({
template: "API_AUTH",
});
const { data } = await supabase.auth.getSession();
const accessToken = data?.session?.access_token;

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

window.localStorage.setItem(
process.env.NEXT_PUBLIC_TOKEN_STORAGE_KEY!,
token,
accessToken,
);
console.log({ token });
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>
Expand Down
36 changes: 14 additions & 22 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { Inter, Roboto } from "next/font/google";
import classNames from "classnames";
import { ThemeProvider } from "@/components/providers";
import { ApolloWrapper } from "../src/api/ApolloWrapper";
import { Clerk } from "../src/components/Auth/clerk";

const inter = Inter({
subsets: ["latin"],
Expand All @@ -29,27 +28,20 @@ export default function RootLayout({
children: React.ReactNode;
}) {
return (
<Clerk>
<html lang="es" className="h-[100dvh] bg-slate-950">
<body
className={classNames(
inter.variable,
roboto.variable,
)}
>
<ApolloWrapper>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
</ThemeProvider>
</ApolloWrapper>
</body>
</html>
</Clerk>
<html lang="es" className="h-[100dvh] bg-slate-950">
<body className={classNames(inter.variable, roboto.variable)}>
<ApolloWrapper>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
</ThemeProvider>
</ApolloWrapper>
</body>
</html>
);
}

Expand Down
19 changes: 19 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { type NextRequest } from 'next/server'
import { updateSession } from '@/utils/supabase/middleware'

export async function middleware(request: NextRequest) {
return await updateSession(request)
}

export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* Feel free to modify this pattern to include more paths.
*/
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
}
Loading
Loading