mirror of
https://github.com/neynarxyz/create-farcaster-mini-app.git
synced 2025-11-16 08:08:56 -05:00
with backend support
This commit is contained in:
parent
7de86c4a15
commit
6a7d1424e9
@ -32,9 +32,7 @@ export function Providers({
|
|||||||
backButtonEnabled={true}
|
backButtonEnabled={true}
|
||||||
>
|
>
|
||||||
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
||||||
<AuthKitProvider config={{}}>
|
<AuthKitProvider config={{}}>{children}</AuthKitProvider>
|
||||||
{children}
|
|
||||||
</AuthKitProvider>
|
|
||||||
</SafeFarcasterSolanaProvider>
|
</SafeFarcasterSolanaProvider>
|
||||||
</MiniAppProvider>
|
</MiniAppProvider>
|
||||||
</WagmiProvider>
|
</WagmiProvider>
|
||||||
|
|||||||
82
src/auth.ts
82
src/auth.ts
@ -1,8 +1,8 @@
|
|||||||
import { AuthOptions, getServerSession } from "next-auth"
|
import { AuthOptions, getServerSession } from 'next-auth';
|
||||||
import CredentialsProvider from "next-auth/providers/credentials";
|
import CredentialsProvider from 'next-auth/providers/credentials';
|
||||||
import { createAppClient, viemConnector } from "@farcaster/auth-client";
|
import { createAppClient, viemConnector } from '@farcaster/auth-client';
|
||||||
|
|
||||||
declare module "next-auth" {
|
declare module 'next-auth' {
|
||||||
interface Session {
|
interface Session {
|
||||||
user: {
|
user: {
|
||||||
fid: number;
|
fid: number;
|
||||||
@ -29,40 +29,47 @@ export const authOptions: AuthOptions = {
|
|||||||
// Configure one or more authentication providers
|
// Configure one or more authentication providers
|
||||||
providers: [
|
providers: [
|
||||||
CredentialsProvider({
|
CredentialsProvider({
|
||||||
name: "Sign in with Farcaster",
|
name: 'Sign in with Farcaster',
|
||||||
credentials: {
|
credentials: {
|
||||||
message: {
|
message: {
|
||||||
label: "Message",
|
label: 'Message',
|
||||||
type: "text",
|
type: 'text',
|
||||||
placeholder: "0x0",
|
placeholder: '0x0',
|
||||||
},
|
},
|
||||||
signature: {
|
signature: {
|
||||||
label: "Signature",
|
label: 'Signature',
|
||||||
type: "text",
|
type: 'text',
|
||||||
placeholder: "0x0",
|
placeholder: '0x0',
|
||||||
|
},
|
||||||
|
nonce: {
|
||||||
|
label: 'Nonce',
|
||||||
|
type: 'text',
|
||||||
|
placeholder: 'Custom nonce (optional)',
|
||||||
},
|
},
|
||||||
// In a production app with a server, these should be fetched from
|
// In a production app with a server, these should be fetched from
|
||||||
// your Farcaster data indexer rather than have them accepted as part
|
// your Farcaster data indexer rather than have them accepted as part
|
||||||
// of credentials.
|
// of credentials.
|
||||||
// question: should these natively use the Neynar API?
|
// question: should these natively use the Neynar API?
|
||||||
name: {
|
name: {
|
||||||
label: "Name",
|
label: 'Name',
|
||||||
type: "text",
|
type: 'text',
|
||||||
placeholder: "0x0",
|
placeholder: '0x0',
|
||||||
},
|
},
|
||||||
pfp: {
|
pfp: {
|
||||||
label: "Pfp",
|
label: 'Pfp',
|
||||||
type: "text",
|
type: 'text',
|
||||||
placeholder: "0x0",
|
placeholder: '0x0',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
async authorize(credentials, req) {
|
async authorize(credentials, req) {
|
||||||
const csrfToken = req?.body?.csrfToken;
|
const csrfToken = req?.body?.csrfToken;
|
||||||
if (!csrfToken) {
|
|
||||||
console.error('CSRF token is missing from request');
|
const nonce = credentials?.nonce || csrfToken;
|
||||||
|
|
||||||
|
if (!nonce) {
|
||||||
|
console.error('No nonce or CSRF token provided');
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const appClient = createAppClient({
|
const appClient = createAppClient({
|
||||||
ethereum: viemConnector(),
|
ethereum: viemConnector(),
|
||||||
});
|
});
|
||||||
@ -73,8 +80,9 @@ export const authOptions: AuthOptions = {
|
|||||||
message: credentials?.message as string,
|
message: credentials?.message as string,
|
||||||
signature: credentials?.signature as `0x${string}`,
|
signature: credentials?.signature as `0x${string}`,
|
||||||
domain,
|
domain,
|
||||||
nonce: csrfToken,
|
nonce,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { success, fid } = verifyResponse;
|
const { success, fid } = verifyResponse;
|
||||||
|
|
||||||
if (!success) {
|
if (!success) {
|
||||||
@ -100,30 +108,30 @@ export const authOptions: AuthOptions = {
|
|||||||
name: `next-auth.session-token`,
|
name: `next-auth.session-token`,
|
||||||
options: {
|
options: {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
sameSite: "none",
|
sameSite: 'none',
|
||||||
path: "/",
|
path: '/',
|
||||||
secure: true
|
secure: true,
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
callbackUrl: {
|
callbackUrl: {
|
||||||
name: `next-auth.callback-url`,
|
name: `next-auth.callback-url`,
|
||||||
options: {
|
options: {
|
||||||
sameSite: "none",
|
sameSite: 'none',
|
||||||
path: "/",
|
path: '/',
|
||||||
secure: true
|
secure: true,
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
csrfToken: {
|
csrfToken: {
|
||||||
name: `next-auth.csrf-token`,
|
name: `next-auth.csrf-token`,
|
||||||
options: {
|
options: {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
sameSite: "none",
|
sameSite: 'none',
|
||||||
path: "/",
|
path: '/',
|
||||||
secure: true
|
secure: true,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
};
|
||||||
|
|
||||||
export const getSession = async () => {
|
export const getSession = async () => {
|
||||||
try {
|
try {
|
||||||
@ -132,4 +140,4 @@ export const getSession = async () => {
|
|||||||
console.error('Error getting server session:', error);
|
console.error('Error getting server session:', error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|||||||
@ -12,7 +12,7 @@ export function AuthDialog({
|
|||||||
}: {
|
}: {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
url: string;
|
url?: string;
|
||||||
isError: boolean;
|
isError: boolean;
|
||||||
error?: Error | null;
|
error?: Error | null;
|
||||||
step: 'signin' | 'access' | 'loading';
|
step: 'signin' | 'access' | 'loading';
|
||||||
@ -47,49 +47,49 @@ export function AuthDialog({
|
|||||||
return {
|
return {
|
||||||
title: 'Grant Access',
|
title: 'Grant Access',
|
||||||
description: (
|
description: (
|
||||||
<div className='space-y-3'>
|
<div className="space-y-3">
|
||||||
<p className='text-gray-600 dark:text-gray-400'>
|
<p className="text-gray-600 dark:text-gray-400">
|
||||||
Allow this app to access your Farcaster account:
|
Allow this app to access your Farcaster account:
|
||||||
</p>
|
</p>
|
||||||
<div className='space-y-2 text-sm'>
|
<div className="space-y-2 text-sm">
|
||||||
<div className='flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg'>
|
<div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||||
<div className='w-6 h-6 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center'>
|
<div className="w-6 h-6 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center">
|
||||||
<svg
|
<svg
|
||||||
className='w-3 h-3 text-green-600 dark:text-green-400'
|
className="w-3 h-3 text-green-600 dark:text-green-400"
|
||||||
fill='currentColor'
|
fill="currentColor"
|
||||||
viewBox='0 0 20 20'
|
viewBox="0 0 20 20"
|
||||||
>
|
>
|
||||||
<path
|
<path
|
||||||
fillRule='evenodd'
|
fillRule="evenodd"
|
||||||
d='M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z'
|
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
|
||||||
clipRule='evenodd'
|
clipRule="evenodd"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div className='font-medium text-gray-900 dark:text-gray-100'>
|
<div className="font-medium text-gray-900 dark:text-gray-100">
|
||||||
Read Access
|
Read Access
|
||||||
</div>
|
</div>
|
||||||
<div className='text-gray-500 dark:text-gray-400'>
|
<div className="text-gray-500 dark:text-gray-400">
|
||||||
View your profile and public information
|
View your profile and public information
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className='flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg'>
|
<div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||||
<div className='w-6 h-6 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center'>
|
<div className="w-6 h-6 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center">
|
||||||
<svg
|
<svg
|
||||||
className='w-3 h-3 text-blue-600 dark:text-blue-400'
|
className="w-3 h-3 text-blue-600 dark:text-blue-400"
|
||||||
fill='currentColor'
|
fill="currentColor"
|
||||||
viewBox='0 0 20 20'
|
viewBox="0 0 20 20"
|
||||||
>
|
>
|
||||||
<path d='M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z' />
|
<path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
|
||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div className='font-medium text-gray-900 dark:text-gray-100'>
|
<div className="font-medium text-gray-900 dark:text-gray-100">
|
||||||
Write Access
|
Write Access
|
||||||
</div>
|
</div>
|
||||||
<div className='text-gray-500 dark:text-gray-400'>
|
<div className="text-gray-500 dark:text-gray-400">
|
||||||
Post casts, likes, and update your profile
|
Post casts, likes, and update your profile
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -118,43 +118,43 @@ export function AuthDialog({
|
|||||||
const content = getStepContent();
|
const content = getStepContent();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm'>
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
|
||||||
<div className='bg-white dark:bg-gray-800 rounded-xl p-6 max-w-md mx-4 shadow-2xl border border-gray-200 dark:border-gray-700'>
|
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 max-w-md mx-4 shadow-2xl border border-gray-200 dark:border-gray-700">
|
||||||
<div className='flex justify-between items-center mb-4'>
|
<div className="flex justify-between items-center mb-4">
|
||||||
<h2 className='text-lg font-semibold text-gray-900 dark:text-gray-100'>
|
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||||
{isError ? 'Error' : content.title}
|
{isError ? 'Error' : content.title}
|
||||||
</h2>
|
</h2>
|
||||||
<button
|
<button
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className='text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors'
|
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
|
||||||
>
|
>
|
||||||
<svg
|
<svg
|
||||||
className='w-6 h-6'
|
className="w-6 h-6"
|
||||||
fill='none'
|
fill="none"
|
||||||
stroke='currentColor'
|
stroke="currentColor"
|
||||||
viewBox='0 0 24 24'
|
viewBox="0 0 24 24"
|
||||||
>
|
>
|
||||||
<path
|
<path
|
||||||
strokeLinecap='round'
|
strokeLinecap="round"
|
||||||
strokeLinejoin='round'
|
strokeLinejoin="round"
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
d='M6 18L18 6M6 6l12 12'
|
d="M6 18L18 6M6 6l12 12"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isError ? (
|
{isError ? (
|
||||||
<div className='text-center'>
|
<div className="text-center">
|
||||||
<div className='text-red-600 dark:text-red-400 mb-4'>
|
<div className="text-red-600 dark:text-red-400 mb-4">
|
||||||
{error?.message || 'Unknown error, please try again.'}
|
{error?.message || 'Unknown error, please try again.'}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className='text-center'>
|
<div className="text-center">
|
||||||
<div className='mb-6'>
|
<div className="mb-6">
|
||||||
{typeof content.description === 'string' ? (
|
{typeof content.description === 'string' ? (
|
||||||
<p className='text-gray-600 dark:text-gray-400'>
|
<p className="text-gray-600 dark:text-gray-400">
|
||||||
{content.description}
|
{content.description}
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
@ -162,23 +162,23 @@ export function AuthDialog({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='mb-6 flex justify-center'>
|
<div className="mb-6 flex justify-center">
|
||||||
{content.showQR && content.qrUrl ? (
|
{content.showQR && content.qrUrl ? (
|
||||||
<div className='p-4 bg-white rounded-lg'>
|
<div className="p-4 bg-white rounded-lg">
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img
|
<img
|
||||||
src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(
|
src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(
|
||||||
content.qrUrl
|
content.qrUrl
|
||||||
)}`}
|
)}`}
|
||||||
alt='QR Code'
|
alt="QR Code"
|
||||||
className='w-48 h-48'
|
className="w-48 h-48"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : step === 'loading' || isLoading ? (
|
) : step === 'loading' || isLoading ? (
|
||||||
<div className='w-48 h-48 flex items-center justify-center bg-gray-50 dark:bg-gray-700 rounded-lg'>
|
<div className="w-48 h-48 flex items-center justify-center bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||||
<div className='flex flex-col items-center gap-3'>
|
<div className="flex flex-col items-center gap-3">
|
||||||
<div className='spinner w-8 h-8' />
|
<div className="spinner w-8 h-8" />
|
||||||
<span className='text-sm text-gray-500 dark:text-gray-400'>
|
<span className="text-sm text-gray-500 dark:text-gray-400">
|
||||||
{step === 'loading'
|
{step === 'loading'
|
||||||
? 'Setting up access...'
|
? 'Setting up access...'
|
||||||
: 'Loading...'}
|
: 'Loading...'}
|
||||||
@ -204,7 +204,7 @@ export function AuthDialog({
|
|||||||
'_blank'
|
'_blank'
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
className='btn btn-outline flex items-center justify-center gap-2 w-full'
|
className="btn btn-outline flex items-center justify-center gap-2 w-full"
|
||||||
>
|
>
|
||||||
I'm using my phone →
|
I'm using my phone →
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@ -20,7 +20,7 @@ export function ProfileButton({
|
|||||||
const pfpUrl = userData?.pfpUrl ?? 'https://farcaster.xyz/avatar.png';
|
const pfpUrl = userData?.pfpUrl ?? 'https://farcaster.xyz/avatar.png';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='relative' ref={ref}>
|
<div className="relative" ref={ref}>
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowDropdown(!showDropdown)}
|
onClick={() => setShowDropdown(!showDropdown)}
|
||||||
className={cn(
|
className={cn(
|
||||||
@ -33,14 +33,14 @@ export function ProfileButton({
|
|||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img
|
<img
|
||||||
src={pfpUrl}
|
src={pfpUrl}
|
||||||
alt='Profile'
|
alt="Profile"
|
||||||
className='w-6 h-6 rounded-full object-cover flex-shrink-0'
|
className="w-6 h-6 rounded-full object-cover flex-shrink-0"
|
||||||
onError={(e) => {
|
onError={(e) => {
|
||||||
(e.target as HTMLImageElement).src =
|
(e.target as HTMLImageElement).src =
|
||||||
'https://farcaster.xyz/avatar.png';
|
'https://farcaster.xyz/avatar.png';
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<span className='text-sm font-medium truncate max-w-[120px]'>
|
<span className="text-sm font-medium truncate max-w-[120px]">
|
||||||
{name ? name : '...'}
|
{name ? name : '...'}
|
||||||
</span>
|
</span>
|
||||||
<svg
|
<svg
|
||||||
@ -48,39 +48,39 @@ export function ProfileButton({
|
|||||||
'w-4 h-4 transition-transform flex-shrink-0',
|
'w-4 h-4 transition-transform flex-shrink-0',
|
||||||
showDropdown && 'rotate-180'
|
showDropdown && 'rotate-180'
|
||||||
)}
|
)}
|
||||||
fill='none'
|
fill="none"
|
||||||
stroke='currentColor'
|
stroke="currentColor"
|
||||||
viewBox='0 0 24 24'
|
viewBox="0 0 24 24"
|
||||||
>
|
>
|
||||||
<path
|
<path
|
||||||
strokeLinecap='round'
|
strokeLinecap="round"
|
||||||
strokeLinejoin='round'
|
strokeLinejoin="round"
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
d='M19 9l-7 7-7-7'
|
d="M19 9l-7 7-7-7"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{showDropdown && (
|
{showDropdown && (
|
||||||
<div className='absolute top-full right-0 left-0 mt-1 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-50'>
|
<div className="absolute top-full right-0 left-0 mt-1 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-50">
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
onSignOut();
|
onSignOut();
|
||||||
setShowDropdown(false);
|
setShowDropdown(false);
|
||||||
}}
|
}}
|
||||||
className='w-full px-4 py-3 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 rounded-lg transition-colors'
|
className="w-full px-4 py-3 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center gap-3 rounded-lg transition-colors"
|
||||||
>
|
>
|
||||||
<svg
|
<svg
|
||||||
className='w-4 h-4'
|
className="w-4 h-4"
|
||||||
fill='none'
|
fill="none"
|
||||||
stroke='currentColor'
|
stroke="currentColor"
|
||||||
viewBox='0 0 24 24'
|
viewBox="0 0 24 24"
|
||||||
>
|
>
|
||||||
<path
|
<path
|
||||||
strokeLinecap='round'
|
strokeLinecap="round"
|
||||||
strokeLinejoin='round'
|
strokeLinejoin="round"
|
||||||
strokeWidth={1.5}
|
strokeWidth={1.5}
|
||||||
d='M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1'
|
d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
Sign out
|
Sign out
|
||||||
|
|||||||
@ -10,25 +10,78 @@ import { ProfileButton } from '~/components/ui/NeynarAuthButton/ProfileButton';
|
|||||||
import { AuthDialog } from '~/components/ui/NeynarAuthButton/AuthDialog';
|
import { AuthDialog } from '~/components/ui/NeynarAuthButton/AuthDialog';
|
||||||
import { getItem, removeItem, setItem } from '~/lib/localStorage';
|
import { getItem, removeItem, setItem } from '~/lib/localStorage';
|
||||||
import { useMiniApp } from '@neynar/react';
|
import { useMiniApp } from '@neynar/react';
|
||||||
|
import {
|
||||||
|
signIn as backendSignIn,
|
||||||
|
signOut as backendSignOut,
|
||||||
|
} from 'next-auth/react';
|
||||||
|
import sdk, { SignIn as SignInCore } from '@farcaster/frame-sdk';
|
||||||
|
|
||||||
const STORAGE_KEY = 'neynar_authenticated_user';
|
const STORAGE_KEY = 'neynar_authenticated_user';
|
||||||
const FARCASTER_FID = 9152;
|
const FARCASTER_FID = 9152;
|
||||||
|
|
||||||
interface StoredAuthState {
|
interface StoredAuthState {
|
||||||
isAuthenticated: boolean;
|
isAuthenticated: boolean;
|
||||||
userData?: {
|
user: {
|
||||||
fid?: number;
|
object: 'user';
|
||||||
pfpUrl?: string;
|
fid: number;
|
||||||
username?: string;
|
username: string;
|
||||||
|
display_name: string;
|
||||||
|
pfp_url: string;
|
||||||
|
custody_address: string;
|
||||||
|
profile: {
|
||||||
|
bio: {
|
||||||
|
text: string;
|
||||||
|
mentioned_profiles?: Array<{
|
||||||
|
object: 'user_dehydrated';
|
||||||
|
fid: number;
|
||||||
|
username: string;
|
||||||
|
display_name: string;
|
||||||
|
pfp_url: string;
|
||||||
|
custody_address: string;
|
||||||
|
}>;
|
||||||
|
mentioned_profiles_ranges?: Array<{
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
}>;
|
||||||
};
|
};
|
||||||
lastSignInTime?: number;
|
location?: {
|
||||||
signers?: {
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
address: {
|
||||||
|
city: string;
|
||||||
|
state: string;
|
||||||
|
country: string;
|
||||||
|
country_code: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
follower_count: number;
|
||||||
|
following_count: number;
|
||||||
|
verifications: string[];
|
||||||
|
verified_addresses: {
|
||||||
|
eth_addresses: string[];
|
||||||
|
sol_addresses: string[];
|
||||||
|
primary: {
|
||||||
|
eth_address: string;
|
||||||
|
sol_address: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
verified_accounts: Array<Record<string, unknown>>;
|
||||||
|
power_badge: boolean;
|
||||||
|
url?: string;
|
||||||
|
experimental?: {
|
||||||
|
neynar_user_score: number;
|
||||||
|
deprecation_notice: string;
|
||||||
|
};
|
||||||
|
score: number;
|
||||||
|
} | null;
|
||||||
|
signers: {
|
||||||
object: 'signer';
|
object: 'signer';
|
||||||
signer_uuid: string;
|
signer_uuid: string;
|
||||||
public_key: string;
|
public_key: string;
|
||||||
status: 'approved';
|
status: 'approved';
|
||||||
fid: number;
|
fid: number;
|
||||||
}[]; // Store the list of signers
|
}[];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main Custom SignInButton Component
|
// Main Custom SignInButton Component
|
||||||
@ -48,6 +101,12 @@ export function NeynarAuthButton() {
|
|||||||
const [pollingInterval, setPollingInterval] = useState<NodeJS.Timeout | null>(
|
const [pollingInterval, setPollingInterval] = useState<NodeJS.Timeout | null>(
|
||||||
null
|
null
|
||||||
);
|
);
|
||||||
|
const [message, setMessage] = useState<string | null>(null);
|
||||||
|
const [signature, setSignature] = useState<string | null>(null);
|
||||||
|
const [debugState, setDebugState] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Determine which flow to use based on context
|
||||||
|
const useBackendFlow = context !== undefined;
|
||||||
|
|
||||||
// Helper function to create a signer
|
// Helper function to create a signer
|
||||||
const createSigner = useCallback(async () => {
|
const createSigner = useCallback(async () => {
|
||||||
@ -68,6 +127,24 @@ export function NeynarAuthButton() {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Helper function to fetch user data from Neynar API
|
||||||
|
const fetchUserData = useCallback(
|
||||||
|
async (fid: number): Promise<User | null> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/users?fids=${fid}`);
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
return data.users?.[0] || null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching user data:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
// Helper function to generate signed key request
|
// Helper function to generate signed key request
|
||||||
const generateSignedKeyRequest = useCallback(
|
const generateSignedKeyRequest = useCallback(
|
||||||
async (signerUuid: string, publicKey: string) => {
|
async (signerUuid: string, publicKey: string) => {
|
||||||
@ -123,13 +200,19 @@ export function NeynarAuthButton() {
|
|||||||
const signerData = await response.json();
|
const signerData = await response.json();
|
||||||
|
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
|
let user: StoredAuthState['user'] | null = null;
|
||||||
|
|
||||||
|
if (signerData.signers && signerData.signers.length > 0) {
|
||||||
|
user = await fetchUserData(signerData.signers[0].fid);
|
||||||
|
}
|
||||||
|
|
||||||
// Store signers in localStorage, preserving existing auth data
|
// Store signers in localStorage, preserving existing auth data
|
||||||
const existingAuth = getItem<StoredAuthState>(STORAGE_KEY);
|
const existingAuth = getItem<StoredAuthState>(STORAGE_KEY);
|
||||||
const updatedState: StoredAuthState = {
|
const updatedState: StoredAuthState = {
|
||||||
...existingAuth,
|
...existingAuth,
|
||||||
isAuthenticated: true,
|
isAuthenticated: !!user,
|
||||||
signers: signerData.signers || [],
|
signers: signerData.signers || [],
|
||||||
lastSignInTime: existingAuth?.lastSignInTime || Date.now(),
|
user,
|
||||||
};
|
};
|
||||||
setItem<StoredAuthState>(STORAGE_KEY, updatedState);
|
setItem<StoredAuthState>(STORAGE_KEY, updatedState);
|
||||||
setStoredAuth(updatedState);
|
setStoredAuth(updatedState);
|
||||||
@ -225,8 +308,7 @@ export function NeynarAuthButton() {
|
|||||||
const existingAuth = getItem<StoredAuthState>(STORAGE_KEY);
|
const existingAuth = getItem<StoredAuthState>(STORAGE_KEY);
|
||||||
const authState: StoredAuthState = {
|
const authState: StoredAuthState = {
|
||||||
isAuthenticated: true,
|
isAuthenticated: true,
|
||||||
userData: res as StoredAuthState['userData'],
|
user: res as StoredAuthState['user'],
|
||||||
lastSignInTime: Date.now(),
|
|
||||||
signers: existingAuth?.signers || [], // Preserve existing signers
|
signers: existingAuth?.signers || [], // Preserve existing signers
|
||||||
};
|
};
|
||||||
setItem<StoredAuthState>(STORAGE_KEY, authState);
|
setItem<StoredAuthState>(STORAGE_KEY, authState);
|
||||||
@ -246,8 +328,8 @@ export function NeynarAuthButton() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const {
|
const {
|
||||||
signIn,
|
signIn: frontendSignIn,
|
||||||
signOut,
|
signOut: frontendSignOut,
|
||||||
connect,
|
connect,
|
||||||
reconnect,
|
reconnect,
|
||||||
isSuccess,
|
isSuccess,
|
||||||
@ -259,63 +341,97 @@ export function NeynarAuthButton() {
|
|||||||
validSignature,
|
validSignature,
|
||||||
} = signInState;
|
} = signInState;
|
||||||
|
|
||||||
// Connect when component mounts and we have a nonce
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (nonce && !channelToken) {
|
setMessage(data?.message || null);
|
||||||
|
setSignature(data?.signature || null);
|
||||||
|
}, [data?.message, data?.signature]);
|
||||||
|
|
||||||
|
// Connect for frontend flow when nonce is available
|
||||||
|
useEffect(() => {
|
||||||
|
if (!useBackendFlow && nonce && !channelToken) {
|
||||||
connect();
|
connect();
|
||||||
}
|
}
|
||||||
}, [nonce, channelToken, connect]);
|
}, [useBackendFlow, nonce, channelToken, connect]);
|
||||||
|
|
||||||
// Handle fetching signers after successful authentication
|
// Handle fetching signers after successful authentication
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (data?.message && data?.signature) {
|
if (message && signature) {
|
||||||
const handleSignerFlow = async () => {
|
const handleSignerFlow = async () => {
|
||||||
try {
|
try {
|
||||||
// Ensure we have message and signature
|
// // Ensure we have message and signature
|
||||||
if (!data.message || !data.signature) {
|
// if (!message || !signature) {
|
||||||
console.error('❌ Missing message or signature');
|
// console.error('❌ Missing message or signature');
|
||||||
return;
|
// return;
|
||||||
}
|
// }
|
||||||
|
|
||||||
// Step 1: Change to loading state
|
// Step 1: Change to loading state
|
||||||
setDialogStep('loading');
|
setDialogStep('loading');
|
||||||
setSignersLoading(true);
|
setSignersLoading(true);
|
||||||
|
|
||||||
// First, fetch existing signers
|
// First, fetch existing signers
|
||||||
const signers = await fetchAllSigners(data.message, data.signature);
|
const signers = await fetchAllSigners(message, signature);
|
||||||
|
|
||||||
|
setDebugState('Fetched signers...');
|
||||||
|
|
||||||
// Check if no signers exist or if we have empty signers
|
// Check if no signers exist or if we have empty signers
|
||||||
if (!signers || signers.length === 0) {
|
if (!signers || signers.length === 0) {
|
||||||
// Step 1: Create a signer
|
// Step 1: Create a signer
|
||||||
const newSigner = await createSigner();
|
const newSigner = await createSigner();
|
||||||
|
|
||||||
|
setDebugState('Created new signer...');
|
||||||
|
|
||||||
// Step 2: Generate signed key request
|
// Step 2: Generate signed key request
|
||||||
const signedKeyData = await generateSignedKeyRequest(
|
const signedKeyData = await generateSignedKeyRequest(
|
||||||
newSigner.signer_uuid,
|
newSigner.signer_uuid,
|
||||||
newSigner.public_key
|
newSigner.public_key
|
||||||
);
|
);
|
||||||
|
|
||||||
|
setDebugState('Generated signed key request...');
|
||||||
|
|
||||||
// Step 3: Show QR code in access dialog for signer approval
|
// Step 3: Show QR code in access dialog for signer approval
|
||||||
if (signedKeyData.signer_approval_url) {
|
if (signedKeyData.signer_approval_url) {
|
||||||
|
setDebugState('Setting signer approval URL...');
|
||||||
setSignerApprovalUrl(signedKeyData.signer_approval_url);
|
setSignerApprovalUrl(signedKeyData.signer_approval_url);
|
||||||
setSignersLoading(false); // Stop loading, show QR code
|
setSignersLoading(false); // Stop loading, show QR code
|
||||||
if (isMobile() && context?.client?.clientFid === FARCASTER_FID) {
|
if (
|
||||||
|
context?.client?.platformType === 'mobile' &&
|
||||||
|
context?.client?.clientFid === FARCASTER_FID
|
||||||
|
) {
|
||||||
|
setDebugState('Opening mobile app...');
|
||||||
setShowDialog(false);
|
setShowDialog(false);
|
||||||
window.open(signedKeyData.signer_approval_url, '_blank');
|
await sdk.actions.openUrl(
|
||||||
|
signedKeyData.signer_approval_url.replace(
|
||||||
|
'https://client.farcaster.xyz/deeplinks/',
|
||||||
|
'farcaster://'
|
||||||
|
)
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
setDialogStep('access'); // Switch to access step to show QR
|
setDebugState(
|
||||||
|
'Opening access dialog...' +
|
||||||
|
` ${context?.client?.platformType}` +
|
||||||
|
` ${context?.client?.clientFid}`
|
||||||
|
);
|
||||||
|
setDialogStep('access');
|
||||||
|
setShowDialog(true);
|
||||||
|
setDebugState(
|
||||||
|
'Opening access dialog...2' +
|
||||||
|
` ${dialogStep}` +
|
||||||
|
` ${showDialog}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 4: Start polling for signer approval
|
// Step 4: Start polling for signer approval
|
||||||
startPolling(newSigner.signer_uuid, data.message, data.signature);
|
startPolling(newSigner.signer_uuid, message, signature);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
setDebugState('Signers already exist, proceeding to signin...');
|
||||||
// If signers exist, close the dialog
|
// If signers exist, close the dialog
|
||||||
setSignersLoading(false);
|
setSignersLoading(false);
|
||||||
setShowDialog(false);
|
setShowDialog(false);
|
||||||
setDialogStep('signin');
|
setDialogStep('signin');
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
setDebugState('Error in signer flow:');
|
||||||
console.error('❌ Error in signer flow:', error);
|
console.error('❌ Error in signer flow:', error);
|
||||||
// On error, reset to signin step
|
// On error, reset to signin step
|
||||||
setDialogStep('signin');
|
setDialogStep('signin');
|
||||||
@ -326,48 +442,111 @@ export function NeynarAuthButton() {
|
|||||||
handleSignerFlow();
|
handleSignerFlow();
|
||||||
}
|
}
|
||||||
}, [
|
}, [
|
||||||
data?.message,
|
message,
|
||||||
data?.signature,
|
signature,
|
||||||
fetchAllSigners,
|
fetchAllSigners,
|
||||||
createSigner,
|
createSigner,
|
||||||
generateSignedKeyRequest,
|
generateSignedKeyRequest,
|
||||||
startPolling,
|
startPolling,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const handleSignIn = useCallback(() => {
|
// Backend flow using NextAuth
|
||||||
|
const handleBackendSignIn = useCallback(async () => {
|
||||||
|
if (!nonce) {
|
||||||
|
console.error('❌ No nonce available for backend sign-in');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setSignersLoading(true);
|
||||||
|
const result = await sdk.actions.signIn({ nonce });
|
||||||
|
|
||||||
|
const signInData = {
|
||||||
|
message: result.message,
|
||||||
|
signature: result.signature,
|
||||||
|
redirect: false,
|
||||||
|
nonce: nonce,
|
||||||
|
};
|
||||||
|
|
||||||
|
const nextAuthResult = await backendSignIn('credentials', signInData);
|
||||||
|
if (nextAuthResult?.ok) {
|
||||||
|
setMessage(result.message);
|
||||||
|
setSignature(result.signature);
|
||||||
|
} else {
|
||||||
|
console.error('❌ NextAuth sign-in failed:', nextAuthResult);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof SignInCore.RejectedByUser) {
|
||||||
|
console.log('ℹ️ Sign-in rejected by user');
|
||||||
|
} else {
|
||||||
|
console.error('❌ Backend sign-in error:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [nonce]);
|
||||||
|
|
||||||
|
const handleFrontEndSignIn = useCallback(() => {
|
||||||
if (isError) {
|
if (isError) {
|
||||||
reconnect();
|
reconnect();
|
||||||
}
|
}
|
||||||
setDialogStep('signin');
|
setDialogStep('signin');
|
||||||
setShowDialog(true);
|
setShowDialog(true);
|
||||||
signIn();
|
frontendSignIn();
|
||||||
|
|
||||||
// Open mobile app if on mobile and URL is available
|
// Open mobile app if on mobile and URL is available
|
||||||
if (url && isMobile()) {
|
if (url && isMobile()) {
|
||||||
window.open(url, '_blank');
|
window.open(url, '_blank');
|
||||||
}
|
}
|
||||||
}, [isError, reconnect, signIn, url]);
|
}, [isError, reconnect, frontendSignIn, url]);
|
||||||
|
|
||||||
|
const handleSignOut = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setSignersLoading(true);
|
||||||
|
|
||||||
|
if (useBackendFlow) {
|
||||||
|
await backendSignOut({ redirect: false });
|
||||||
|
} else {
|
||||||
|
frontendSignOut();
|
||||||
|
}
|
||||||
|
|
||||||
const handleSignOut = useCallback(() => {
|
|
||||||
setShowDialog(false);
|
|
||||||
signOut();
|
|
||||||
removeItem(STORAGE_KEY);
|
removeItem(STORAGE_KEY);
|
||||||
setStoredAuth(null);
|
setStoredAuth(null);
|
||||||
}, [signOut]);
|
setShowDialog(false);
|
||||||
|
setDialogStep('signin');
|
||||||
|
setSignerApprovalUrl(null);
|
||||||
|
setMessage(null);
|
||||||
|
setSignature(null);
|
||||||
|
setDebugState(null);
|
||||||
|
|
||||||
|
// Reset polling interval
|
||||||
|
if (pollingInterval) {
|
||||||
|
clearInterval(pollingInterval);
|
||||||
|
setPollingInterval(null);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Error during sign out:', error);
|
||||||
|
// Optionally handle error state
|
||||||
|
} finally {
|
||||||
|
setSignersLoading(false);
|
||||||
|
}
|
||||||
|
}, [useBackendFlow, frontendSignOut, pollingInterval]);
|
||||||
|
|
||||||
// The key fix: match the original library's authentication logic exactly
|
// The key fix: match the original library's authentication logic exactly
|
||||||
const authenticated =
|
const authenticated =
|
||||||
((isSuccess && validSignature) || storedAuth?.isAuthenticated) &&
|
((isSuccess && validSignature) || storedAuth?.isAuthenticated) &&
|
||||||
!!(storedAuth?.signers && storedAuth.signers.length > 0);
|
!!(storedAuth?.signers && storedAuth.signers.length > 0);
|
||||||
const userData = data || storedAuth?.userData;
|
const userData = {
|
||||||
|
fid: storedAuth?.user?.fid,
|
||||||
|
username: storedAuth?.user?.username || '',
|
||||||
|
pfpUrl: storedAuth?.user?.pfp_url || '',
|
||||||
|
};
|
||||||
|
|
||||||
// Show loading state while nonce is being fetched or signers are loading
|
// Show loading state while nonce is being fetched or signers are loading
|
||||||
if (!nonce || signersLoading) {
|
if (!nonce || signersLoading) {
|
||||||
return (
|
return (
|
||||||
<div className='flex items-center justify-center'>
|
<div className="flex items-center justify-center">
|
||||||
<div className='flex items-center gap-3 px-4 py-2 bg-gray-100 dark:bg-gray-800 rounded-lg'>
|
<div className="flex items-center gap-3 px-4 py-2 bg-gray-100 dark:bg-gray-800 rounded-lg">
|
||||||
<div className='spinner w-4 h-4' />
|
<div className="spinner w-4 h-4" />
|
||||||
<span className='text-sm text-gray-600 dark:text-gray-400'>
|
<span className="text-sm text-gray-600 dark:text-gray-400">
|
||||||
Loading...
|
Loading...
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@ -381,32 +560,32 @@ export function NeynarAuthButton() {
|
|||||||
<ProfileButton userData={userData} onSignOut={handleSignOut} />
|
<ProfileButton userData={userData} onSignOut={handleSignOut} />
|
||||||
) : (
|
) : (
|
||||||
<Button
|
<Button
|
||||||
onClick={handleSignIn}
|
onClick={useBackendFlow ? handleBackendSignIn : handleFrontEndSignIn}
|
||||||
disabled={!url}
|
disabled={!useBackendFlow && !url}
|
||||||
className={cn(
|
className={cn(
|
||||||
'btn btn-primary flex items-center gap-3',
|
'btn btn-primary flex items-center gap-3',
|
||||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||||
'transform transition-all duration-200 active:scale-[0.98]',
|
'transform transition-all duration-200 active:scale-[0.98]',
|
||||||
!url && 'cursor-not-allowed'
|
!url && !useBackendFlow && 'cursor-not-allowed'
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{!url ? (
|
{!useBackendFlow && !url ? (
|
||||||
<>
|
<>
|
||||||
<div className='spinner-primary w-5 h-5' />
|
<div className="spinner-primary w-5 h-5" />
|
||||||
<span>Initializing...</span>
|
<span>Initializing...</span>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<span>Sign in with Neynar</span>
|
<span>{debugState || 'Sign in with Neynar'}</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Unified Auth Dialog */}
|
{/* Unified Auth Dialog */}
|
||||||
{url && (
|
{
|
||||||
<AuthDialog
|
<AuthDialog
|
||||||
open={showDialog && !isMobile()}
|
open={showDialog}
|
||||||
onClose={() => {
|
onClose={() => {
|
||||||
setShowDialog(false);
|
setShowDialog(false);
|
||||||
setDialogStep('signin');
|
setDialogStep('signin');
|
||||||
@ -423,7 +602,7 @@ export function NeynarAuthButton() {
|
|||||||
isLoading={signersLoading}
|
isLoading={signersLoading}
|
||||||
signerApprovalUrl={signerApprovalUrl}
|
signerApprovalUrl={signerApprovalUrl}
|
||||||
/>
|
/>
|
||||||
)}
|
}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user