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}
|
||||
>
|
||||
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
|
||||
<AuthKitProvider config={{}}>
|
||||
{children}
|
||||
</AuthKitProvider>
|
||||
<AuthKitProvider config={{}}>{children}</AuthKitProvider>
|
||||
</SafeFarcasterSolanaProvider>
|
||||
</MiniAppProvider>
|
||||
</WagmiProvider>
|
||||
|
||||
84
src/auth.ts
84
src/auth.ts
@ -1,8 +1,8 @@
|
||||
import { AuthOptions, getServerSession } from "next-auth"
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
import { createAppClient, viemConnector } from "@farcaster/auth-client";
|
||||
import { AuthOptions, getServerSession } from 'next-auth';
|
||||
import CredentialsProvider from 'next-auth/providers/credentials';
|
||||
import { createAppClient, viemConnector } from '@farcaster/auth-client';
|
||||
|
||||
declare module "next-auth" {
|
||||
declare module 'next-auth' {
|
||||
interface Session {
|
||||
user: {
|
||||
fid: number;
|
||||
@ -26,43 +26,50 @@ function getDomainFromUrl(urlString: string | undefined): string {
|
||||
}
|
||||
|
||||
export const authOptions: AuthOptions = {
|
||||
// Configure one or more authentication providers
|
||||
// Configure one or more authentication providers
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
name: "Sign in with Farcaster",
|
||||
name: 'Sign in with Farcaster',
|
||||
credentials: {
|
||||
message: {
|
||||
label: "Message",
|
||||
type: "text",
|
||||
placeholder: "0x0",
|
||||
label: 'Message',
|
||||
type: 'text',
|
||||
placeholder: '0x0',
|
||||
},
|
||||
signature: {
|
||||
label: "Signature",
|
||||
type: "text",
|
||||
placeholder: "0x0",
|
||||
label: 'Signature',
|
||||
type: 'text',
|
||||
placeholder: '0x0',
|
||||
},
|
||||
nonce: {
|
||||
label: 'Nonce',
|
||||
type: 'text',
|
||||
placeholder: 'Custom nonce (optional)',
|
||||
},
|
||||
// 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.
|
||||
// question: should these natively use the Neynar API?
|
||||
name: {
|
||||
label: "Name",
|
||||
type: "text",
|
||||
placeholder: "0x0",
|
||||
label: 'Name',
|
||||
type: 'text',
|
||||
placeholder: '0x0',
|
||||
},
|
||||
pfp: {
|
||||
label: "Pfp",
|
||||
type: "text",
|
||||
placeholder: "0x0",
|
||||
label: 'Pfp',
|
||||
type: 'text',
|
||||
placeholder: '0x0',
|
||||
},
|
||||
},
|
||||
async authorize(credentials, req) {
|
||||
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;
|
||||
}
|
||||
|
||||
const appClient = createAppClient({
|
||||
ethereum: viemConnector(),
|
||||
});
|
||||
@ -73,8 +80,9 @@ export const authOptions: AuthOptions = {
|
||||
message: credentials?.message as string,
|
||||
signature: credentials?.signature as `0x${string}`,
|
||||
domain,
|
||||
nonce: csrfToken,
|
||||
nonce,
|
||||
});
|
||||
|
||||
const { success, fid } = verifyResponse;
|
||||
|
||||
if (!success) {
|
||||
@ -100,30 +108,30 @@ export const authOptions: AuthOptions = {
|
||||
name: `next-auth.session-token`,
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: "none",
|
||||
path: "/",
|
||||
secure: true
|
||||
}
|
||||
sameSite: 'none',
|
||||
path: '/',
|
||||
secure: true,
|
||||
},
|
||||
},
|
||||
callbackUrl: {
|
||||
name: `next-auth.callback-url`,
|
||||
options: {
|
||||
sameSite: "none",
|
||||
path: "/",
|
||||
secure: true
|
||||
}
|
||||
sameSite: 'none',
|
||||
path: '/',
|
||||
secure: true,
|
||||
},
|
||||
},
|
||||
csrfToken: {
|
||||
name: `next-auth.csrf-token`,
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: "none",
|
||||
path: "/",
|
||||
secure: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sameSite: 'none',
|
||||
path: '/',
|
||||
secure: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const getSession = async () => {
|
||||
try {
|
||||
@ -132,4 +140,4 @@ export const getSession = async () => {
|
||||
console.error('Error getting server session:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@ -12,7 +12,7 @@ export function AuthDialog({
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
url: string;
|
||||
url?: string;
|
||||
isError: boolean;
|
||||
error?: Error | null;
|
||||
step: 'signin' | 'access' | 'loading';
|
||||
@ -47,49 +47,49 @@ export function AuthDialog({
|
||||
return {
|
||||
title: 'Grant Access',
|
||||
description: (
|
||||
<div className='space-y-3'>
|
||||
<p className='text-gray-600 dark:text-gray-400'>
|
||||
<div className="space-y-3">
|
||||
<p className="text-gray-600 dark:text-gray-400">
|
||||
Allow this app to access your Farcaster account:
|
||||
</p>
|
||||
<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='w-6 h-6 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center'>
|
||||
<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="w-6 h-6 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center">
|
||||
<svg
|
||||
className='w-3 h-3 text-green-600 dark:text-green-400'
|
||||
fill='currentColor'
|
||||
viewBox='0 0 20 20'
|
||||
className="w-3 h-3 text-green-600 dark:text-green-400"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path
|
||||
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'
|
||||
clipRule='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"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</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
|
||||
</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
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<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="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">
|
||||
<svg
|
||||
className='w-3 h-3 text-blue-600 dark:text-blue-400'
|
||||
fill='currentColor'
|
||||
viewBox='0 0 20 20'
|
||||
className="w-3 h-3 text-blue-600 dark:text-blue-400"
|
||||
fill="currentColor"
|
||||
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>
|
||||
</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
|
||||
</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
|
||||
</div>
|
||||
</div>
|
||||
@ -118,43 +118,43 @@ export function AuthDialog({
|
||||
const content = getStepContent();
|
||||
|
||||
return (
|
||||
<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='flex justify-between items-center mb-4'>
|
||||
<h2 className='text-lg font-semibold text-gray-900 dark:text-gray-100'>
|
||||
<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="flex justify-between items-center mb-4">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
{isError ? 'Error' : content.title}
|
||||
</h2>
|
||||
<button
|
||||
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
|
||||
className='w-6 h-6'
|
||||
fill='none'
|
||||
stroke='currentColor'
|
||||
viewBox='0 0 24 24'
|
||||
className="w-6 h-6"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap='round'
|
||||
strokeLinejoin='round'
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d='M6 18L18 6M6 6l12 12'
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{isError ? (
|
||||
<div className='text-center'>
|
||||
<div className='text-red-600 dark:text-red-400 mb-4'>
|
||||
<div className="text-center">
|
||||
<div className="text-red-600 dark:text-red-400 mb-4">
|
||||
{error?.message || 'Unknown error, please try again.'}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className='text-center'>
|
||||
<div className='mb-6'>
|
||||
<div className="text-center">
|
||||
<div className="mb-6">
|
||||
{typeof content.description === 'string' ? (
|
||||
<p className='text-gray-600 dark:text-gray-400'>
|
||||
<p className="text-gray-600 dark:text-gray-400">
|
||||
{content.description}
|
||||
</p>
|
||||
) : (
|
||||
@ -162,23 +162,23 @@ export function AuthDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className='mb-6 flex justify-center'>
|
||||
<div className="mb-6 flex justify-center">
|
||||
{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 */}
|
||||
<img
|
||||
src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(
|
||||
content.qrUrl
|
||||
)}`}
|
||||
alt='QR Code'
|
||||
className='w-48 h-48'
|
||||
alt="QR Code"
|
||||
className="w-48 h-48"
|
||||
/>
|
||||
</div>
|
||||
) : 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='flex flex-col items-center gap-3'>
|
||||
<div className='spinner w-8 h-8' />
|
||||
<span className='text-sm text-gray-500 dark:text-gray-400'>
|
||||
<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="spinner w-8 h-8" />
|
||||
<span className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{step === 'loading'
|
||||
? 'Setting up access...'
|
||||
: 'Loading...'}
|
||||
@ -204,7 +204,7 @@ export function AuthDialog({
|
||||
'_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 →
|
||||
</button>
|
||||
|
||||
@ -20,7 +20,7 @@ export function ProfileButton({
|
||||
const pfpUrl = userData?.pfpUrl ?? 'https://farcaster.xyz/avatar.png';
|
||||
|
||||
return (
|
||||
<div className='relative' ref={ref}>
|
||||
<div className="relative" ref={ref}>
|
||||
<button
|
||||
onClick={() => setShowDropdown(!showDropdown)}
|
||||
className={cn(
|
||||
@ -33,14 +33,14 @@ export function ProfileButton({
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={pfpUrl}
|
||||
alt='Profile'
|
||||
className='w-6 h-6 rounded-full object-cover flex-shrink-0'
|
||||
alt="Profile"
|
||||
className="w-6 h-6 rounded-full object-cover flex-shrink-0"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).src =
|
||||
'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 : '...'}
|
||||
</span>
|
||||
<svg
|
||||
@ -48,39 +48,39 @@ export function ProfileButton({
|
||||
'w-4 h-4 transition-transform flex-shrink-0',
|
||||
showDropdown && 'rotate-180'
|
||||
)}
|
||||
fill='none'
|
||||
stroke='currentColor'
|
||||
viewBox='0 0 24 24'
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap='round'
|
||||
strokeLinejoin='round'
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d='M19 9l-7 7-7-7'
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{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
|
||||
onClick={() => {
|
||||
onSignOut();
|
||||
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
|
||||
className='w-4 h-4'
|
||||
fill='none'
|
||||
stroke='currentColor'
|
||||
viewBox='0 0 24 24'
|
||||
className="w-4 h-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap='round'
|
||||
strokeLinejoin='round'
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
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>
|
||||
Sign out
|
||||
|
||||
@ -10,25 +10,78 @@ import { ProfileButton } from '~/components/ui/NeynarAuthButton/ProfileButton';
|
||||
import { AuthDialog } from '~/components/ui/NeynarAuthButton/AuthDialog';
|
||||
import { getItem, removeItem, setItem } from '~/lib/localStorage';
|
||||
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 FARCASTER_FID = 9152;
|
||||
|
||||
interface StoredAuthState {
|
||||
isAuthenticated: boolean;
|
||||
userData?: {
|
||||
fid?: number;
|
||||
pfpUrl?: string;
|
||||
username?: string;
|
||||
};
|
||||
lastSignInTime?: number;
|
||||
signers?: {
|
||||
user: {
|
||||
object: 'user';
|
||||
fid: number;
|
||||
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;
|
||||
}>;
|
||||
};
|
||||
location?: {
|
||||
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';
|
||||
signer_uuid: string;
|
||||
public_key: string;
|
||||
status: 'approved';
|
||||
fid: number;
|
||||
}[]; // Store the list of signers
|
||||
}[];
|
||||
}
|
||||
|
||||
// Main Custom SignInButton Component
|
||||
@ -48,6 +101,12 @@ export function NeynarAuthButton() {
|
||||
const [pollingInterval, setPollingInterval] = useState<NodeJS.Timeout | 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
|
||||
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
|
||||
const generateSignedKeyRequest = useCallback(
|
||||
async (signerUuid: string, publicKey: string) => {
|
||||
@ -123,13 +200,19 @@ export function NeynarAuthButton() {
|
||||
const signerData = await response.json();
|
||||
|
||||
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
|
||||
const existingAuth = getItem<StoredAuthState>(STORAGE_KEY);
|
||||
const updatedState: StoredAuthState = {
|
||||
...existingAuth,
|
||||
isAuthenticated: true,
|
||||
isAuthenticated: !!user,
|
||||
signers: signerData.signers || [],
|
||||
lastSignInTime: existingAuth?.lastSignInTime || Date.now(),
|
||||
user,
|
||||
};
|
||||
setItem<StoredAuthState>(STORAGE_KEY, updatedState);
|
||||
setStoredAuth(updatedState);
|
||||
@ -225,8 +308,7 @@ export function NeynarAuthButton() {
|
||||
const existingAuth = getItem<StoredAuthState>(STORAGE_KEY);
|
||||
const authState: StoredAuthState = {
|
||||
isAuthenticated: true,
|
||||
userData: res as StoredAuthState['userData'],
|
||||
lastSignInTime: Date.now(),
|
||||
user: res as StoredAuthState['user'],
|
||||
signers: existingAuth?.signers || [], // Preserve existing signers
|
||||
};
|
||||
setItem<StoredAuthState>(STORAGE_KEY, authState);
|
||||
@ -246,8 +328,8 @@ export function NeynarAuthButton() {
|
||||
});
|
||||
|
||||
const {
|
||||
signIn,
|
||||
signOut,
|
||||
signIn: frontendSignIn,
|
||||
signOut: frontendSignOut,
|
||||
connect,
|
||||
reconnect,
|
||||
isSuccess,
|
||||
@ -259,63 +341,97 @@ export function NeynarAuthButton() {
|
||||
validSignature,
|
||||
} = signInState;
|
||||
|
||||
// Connect when component mounts and we have a nonce
|
||||
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();
|
||||
}
|
||||
}, [nonce, channelToken, connect]);
|
||||
}, [useBackendFlow, nonce, channelToken, connect]);
|
||||
|
||||
// Handle fetching signers after successful authentication
|
||||
useEffect(() => {
|
||||
if (data?.message && data?.signature) {
|
||||
if (message && signature) {
|
||||
const handleSignerFlow = async () => {
|
||||
try {
|
||||
// Ensure we have message and signature
|
||||
if (!data.message || !data.signature) {
|
||||
console.error('❌ Missing message or signature');
|
||||
return;
|
||||
}
|
||||
// // Ensure we have message and signature
|
||||
// if (!message || !signature) {
|
||||
// console.error('❌ Missing message or signature');
|
||||
// return;
|
||||
// }
|
||||
|
||||
// Step 1: Change to loading state
|
||||
setDialogStep('loading');
|
||||
setSignersLoading(true);
|
||||
|
||||
// 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
|
||||
if (!signers || signers.length === 0) {
|
||||
// Step 1: Create a signer
|
||||
const newSigner = await createSigner();
|
||||
|
||||
setDebugState('Created new signer...');
|
||||
|
||||
// Step 2: Generate signed key request
|
||||
const signedKeyData = await generateSignedKeyRequest(
|
||||
newSigner.signer_uuid,
|
||||
newSigner.public_key
|
||||
);
|
||||
|
||||
setDebugState('Generated signed key request...');
|
||||
|
||||
// Step 3: Show QR code in access dialog for signer approval
|
||||
if (signedKeyData.signer_approval_url) {
|
||||
setDebugState('Setting signer approval URL...');
|
||||
setSignerApprovalUrl(signedKeyData.signer_approval_url);
|
||||
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);
|
||||
window.open(signedKeyData.signer_approval_url, '_blank');
|
||||
await sdk.actions.openUrl(
|
||||
signedKeyData.signer_approval_url.replace(
|
||||
'https://client.farcaster.xyz/deeplinks/',
|
||||
'farcaster://'
|
||||
)
|
||||
);
|
||||
} 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
|
||||
startPolling(newSigner.signer_uuid, data.message, data.signature);
|
||||
startPolling(newSigner.signer_uuid, message, signature);
|
||||
}
|
||||
} else {
|
||||
setDebugState('Signers already exist, proceeding to signin...');
|
||||
// If signers exist, close the dialog
|
||||
setSignersLoading(false);
|
||||
setShowDialog(false);
|
||||
setDialogStep('signin');
|
||||
}
|
||||
} catch (error) {
|
||||
setDebugState('Error in signer flow:');
|
||||
console.error('❌ Error in signer flow:', error);
|
||||
// On error, reset to signin step
|
||||
setDialogStep('signin');
|
||||
@ -326,48 +442,111 @@ export function NeynarAuthButton() {
|
||||
handleSignerFlow();
|
||||
}
|
||||
}, [
|
||||
data?.message,
|
||||
data?.signature,
|
||||
message,
|
||||
signature,
|
||||
fetchAllSigners,
|
||||
createSigner,
|
||||
generateSignedKeyRequest,
|
||||
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) {
|
||||
reconnect();
|
||||
}
|
||||
setDialogStep('signin');
|
||||
setShowDialog(true);
|
||||
signIn();
|
||||
frontendSignIn();
|
||||
|
||||
// Open mobile app if on mobile and URL is available
|
||||
if (url && isMobile()) {
|
||||
window.open(url, '_blank');
|
||||
}
|
||||
}, [isError, reconnect, signIn, url]);
|
||||
}, [isError, reconnect, frontendSignIn, url]);
|
||||
|
||||
const handleSignOut = useCallback(() => {
|
||||
setShowDialog(false);
|
||||
signOut();
|
||||
removeItem(STORAGE_KEY);
|
||||
setStoredAuth(null);
|
||||
}, [signOut]);
|
||||
const handleSignOut = useCallback(async () => {
|
||||
try {
|
||||
setSignersLoading(true);
|
||||
|
||||
if (useBackendFlow) {
|
||||
await backendSignOut({ redirect: false });
|
||||
} else {
|
||||
frontendSignOut();
|
||||
}
|
||||
|
||||
removeItem(STORAGE_KEY);
|
||||
setStoredAuth(null);
|
||||
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
|
||||
const authenticated =
|
||||
((isSuccess && validSignature) || storedAuth?.isAuthenticated) &&
|
||||
!!(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
|
||||
if (!nonce || signersLoading) {
|
||||
return (
|
||||
<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='spinner w-4 h-4' />
|
||||
<span className='text-sm text-gray-600 dark:text-gray-400'>
|
||||
<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="spinner w-4 h-4" />
|
||||
<span className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Loading...
|
||||
</span>
|
||||
</div>
|
||||
@ -381,32 +560,32 @@ export function NeynarAuthButton() {
|
||||
<ProfileButton userData={userData} onSignOut={handleSignOut} />
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleSignIn}
|
||||
disabled={!url}
|
||||
onClick={useBackendFlow ? handleBackendSignIn : handleFrontEndSignIn}
|
||||
disabled={!useBackendFlow && !url}
|
||||
className={cn(
|
||||
'btn btn-primary flex items-center gap-3',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed',
|
||||
'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>Sign in with Neynar</span>
|
||||
<span>{debugState || 'Sign in with Neynar'}</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Unified Auth Dialog */}
|
||||
{url && (
|
||||
{
|
||||
<AuthDialog
|
||||
open={showDialog && !isMobile()}
|
||||
open={showDialog}
|
||||
onClose={() => {
|
||||
setShowDialog(false);
|
||||
setDialogStep('signin');
|
||||
@ -423,7 +602,7 @@ export function NeynarAuthButton() {
|
||||
isLoading={signersLoading}
|
||||
signerApprovalUrl={signerApprovalUrl}
|
||||
/>
|
||||
)}
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user