function AuthComponent() {
const { signMessage, publicKey } = useWallet();
const [isAuthenticated, setIsAuthenticated] = useState(false);
const authenticate = async () => {
try {
const nonce = crypto.randomUUID();
const message = `Sign in to MyDApp\nNonce: ${nonce}`;
const encodedMessage = new TextEncoder().encode(message);
const signature = await signMessage(encodedMessage);
// Send to backend for verification
const response = await fetch('/api/auth/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
publicKey: publicKey?.toBase58(),
message,
signature: Array.from(signature),
}),
});
if (response.ok) {
const { token } = await response.json();
localStorage.setItem('auth-token', token);
setIsAuthenticated(true);
}
} catch (error) {
console.error('Authentication failed:', error);
}
};
return (
<div>
{isAuthenticated ? (
<p>Authenticated!</p>
) : (
<button onClick={authenticate}>Sign In</button>
)}
</div>
);
}