add signIn example

This commit is contained in:
Tony D'Addeo
2024-12-17 14:26:20 -06:00
committed by lucas-neynar
parent e1a87ff00f
commit cd4149abd5
9 changed files with 539 additions and 20 deletions

View File

@@ -0,0 +1,6 @@
import NextAuth from "next-auth"
import { authOptions } from "~/auth"
const handler = NextAuth(authOptions)
export { handler as GET, handler as POST }

View File

@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import { getSession } from "~/auth"
import "~/app/globals.css";
import { Providers } from "~/app/providers";
@@ -8,15 +9,17 @@ export const metadata: Metadata = {
description: "A Farcaster Frames v2 demo app",
};
export default function RootLayout({
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const session = await getSession()
return (
<html lang="en">
<body>
<Providers>{children}</Providers>
<Providers session={session}>{children}</Providers>
</body>
</html>
);

View File

@@ -1,6 +1,9 @@
"use client";
import dynamic from "next/dynamic";
import type { Session } from "next-auth"
import { SessionProvider } from "next-auth/react"
const WagmiProvider = dynamic(
() => import("~/components/providers/WagmiProvider"),
@@ -9,6 +12,12 @@ const WagmiProvider = dynamic(
}
);
export function Providers({ children }: { children: React.ReactNode }) {
return <WagmiProvider>{children}</WagmiProvider>;
export function Providers({ session, children }: { session: Session | null, children: React.ReactNode }) {
return (
<SessionProvider session={session}>
<WagmiProvider>
{children}
</WagmiProvider>
</SessionProvider>
);
}

77
src/auth.ts Normal file
View File

@@ -0,0 +1,77 @@
import { AuthOptions, getServerSession } from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
import { createAppClient, viemConnector } from "@farcaster/auth-client";
declare module "next-auth" {
interface Session {
user: {
fid: number;
};
}
}
export const authOptions: AuthOptions = {
// Configure one or more authentication providers
providers: [
CredentialsProvider({
name: "Sign in with Farcaster",
credentials: {
message: {
label: "Message",
type: "text",
placeholder: "0x0",
},
signature: {
label: "Signature",
type: "text",
placeholder: "0x0",
},
// In a production app with a server, these should be fetched from
// your Farcaster data indexer rather than have them accepted as part
// of credentials.
name: {
label: "Name",
type: "text",
placeholder: "0x0",
},
pfp: {
label: "Pfp",
type: "text",
placeholder: "0x0",
},
},
async authorize(credentials, req) {
const csrfToken = req?.body?.csrfToken;
const appClient = createAppClient({
ethereum: viemConnector(),
});
const verifyResponse = await appClient.verifySignInMessage({
message: credentials?.message as string,
signature: credentials?.signature as `0x${string}`,
domain: process.env.NEXTAUTH_URL ?? '',
nonce: csrfToken,
});
const { success, fid } = verifyResponse;
if (!success) {
return null;
}
return {
id: fid.toString(),
};
},
}),
],
callbacks: {
session: async ({ session, token }) => {
if (session?.user) {
session.user.fid = parseInt(token.sub ?? '');
}
return session;
},
}
}
export const getSession = () => getServerSession(authOptions)

View File

@@ -1,6 +1,7 @@
"use client";
import { useEffect, useCallback, useState, useMemo } from "react";
import { signIn, signOut, getCsrfToken } from "next-auth/react";
import sdk, {
FrameNotificationDetails,
type FrameContext,
@@ -22,6 +23,8 @@ import { Button } from "~/components/ui/Button";
import { truncateAddress } from "~/lib/truncateAddress";
import { base, optimism } from "wagmi/chains";
import { BaseError, UserRejectedRequestError } from "viem";
import { useSession } from "next-auth/react"
import { SignInResult } from "@farcaster/frame-core/dist/actions/signIn";
export default function Demo(
{ title }: { title?: string } = { title: "Frames v2 Demo" }
@@ -225,6 +228,15 @@ export default function Demo(
<div>
<h2 className="font-2xl font-bold">Actions</h2>
<div className="mb-4">
<div className="p-2 bg-gray-100 dark:bg-gray-800 rounded-lg my-2">
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
sdk.actions.signIn
</pre>
</div>
<SignIn />
</div>
<div className="mb-4">
<div className="p-2 bg-gray-100 dark:bg-gray-800 rounded-lg my-2">
<pre className="font-mono text-xs whitespace-pre-wrap break-words max-w-[260px] overflow-x-">
@@ -477,6 +489,80 @@ function SendEth() {
);
}
function SignIn() {
const [signingIn, setSigningIn] = useState(false);
const [signingOut, setSigningOut] = useState(false);
const [signInResult, setSignInResult] = useState<SignInResult>();
const { data: session, status } = useSession()
const getNonce = useCallback(async () => {
const nonce = await getCsrfToken();
if (!nonce) throw new Error("Unable to generate nonce");
return nonce;
}, []);
const handleSignIn = useCallback(async () => {
try {
setSigningIn(true);
const nonce = await getNonce();
const result = await sdk.actions.signIn({ nonce });
setSignInResult(result);
await signIn("credentials", {
message: result.message,
signature: result.signature,
redirect: false,
});
} finally {
setSigningIn(false);
}
}, [getNonce]);
const handleSignOut = useCallback(async () => {
try {
setSigningOut(true);
await signOut({ redirect: false })
setSignInResult(undefined);
} finally {
setSigningOut(false);
}
}, []);
return (
<>
{status !== "authenticated" &&
<Button
onClick={handleSignIn}
disabled={signingIn}
>
Sign In with Farcaster
</Button>
}
{status === "authenticated" &&
<Button
onClick={handleSignOut}
disabled={signingOut}
>
Sign out
</Button>
}
{session &&
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
<div className="font-semibold text-gray-500 mb-1">Session</div>
<div className="whitespace-pre">{JSON.stringify(session, null, 2)}</div>
</div>
}
{signInResult && !signingIn && (
<div className="my-2 p-2 text-xs overflow-x-scroll bg-gray-100 rounded-lg font-mono">
<div className="font-semibold text-gray-500 mb-1">SIWF Result</div>
<div className="whitespace-pre">{JSON.stringify(signInResult, null, 2)}</div>
</div>
)}
</>
);
}
const renderError = (error: Error | null) => {
if (!error) return null;
if (error instanceof BaseError) {