Skip to content

Commit

Permalink
fixup! Add generate JWT authentication example
Browse files Browse the repository at this point in the history
  • Loading branch information
GregHolmes committed Dec 18, 2024
1 parent 355032a commit e73db59
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 40 deletions.
89 changes: 89 additions & 0 deletions examples/auth-generate-token/react/src/app/authenticated/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
'use client';

import * as Ably from 'ably';
import { AblyProvider, useConnectionStateListener } from 'ably/react';
import { useState, useEffect } from 'react';

interface StatusMessage {
id: number;
success: boolean;
message: string;
}
interface StatusMessagesProps {
messages: StatusMessage[];
setMessages: React.Dispatch<React.SetStateAction<StatusMessage[]>>;
}

const StatusMessages = ({ messages, setMessages }: StatusMessagesProps) => {
useConnectionStateListener((stateChange) => {
if (stateChange.current === 'connected') {
setMessages(prevMessages =>
prevMessages.map(msg =>
msg.id === 3 ? { ...msg, success: true } : msg
)
);
}
});

return (
<div className="flex items-center justify-center min-h-screen bg-gray-100">
<div className="bg-white shadow-md rounded-md p-8 w-[50%] flex flex-col">
<div className="flex-grow text-center">
<h1 className="text-2xl font-bold mb-4">Authentication with Ably</h1>
<p className="mb-8">The Ably client has been successfully initialized.</p>
</div>

<div className="mt-4 text-left text-sm h-40 overflow-y-auto">
{messages.map((msg) => (
<div key={msg.id} className="flex items-center gap-2">
<span>
{msg.success ?
<span className="text-green-500"></span> :
<span className="text-red-500"></span>
}
</span>
{msg.message}
</div>
))}
</div>
</div>
</div>
);
};

export default function Authenticated() {
const [messages, setMessages] = useState<StatusMessage[]>([
{ id: 1, success: false, message: "Client requests token from server" },
{ id: 2, success: false, message: "Client initializes connection to Ably with generated Token" },
{ id: 3, success: false, message: "Client is connected"}
]);
const [client, setClient] = useState<Ably.Realtime | null>(null);

useEffect(() => {
try {
setMessages(prevMessages =>
prevMessages.map(msg =>
msg.id === 1 ? { ...msg, success: true } : msg
)
);

const newClient = new Ably.Realtime({ authUrl: 'http://localhost:3001/request-token' });
setClient(newClient);
setMessages(prevMessages =>
prevMessages.map(msg =>
msg.id === 2 ? { ...msg, success: true } : msg
)
);
} catch (error) {
console.error('Failed to initialise client:', error);
}
}, []);

if (!client) return null;

return (
<AblyProvider client={client}>
<StatusMessages messages={messages} setMessages={setMessages} />
</AblyProvider>
);
}
46 changes: 6 additions & 40 deletions examples/auth-generate-token/react/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import * as Ably from 'ably';
import { useState } from 'react';
import { useRouter } from 'next/navigation';

interface StatusMessage {
id: number;
Expand All @@ -16,57 +17,22 @@ export default function Home() {
{ id: 2, success: false, message: "Client initializes connection to Ably with generated Token" },
{ id: 3, success: false, message: "Client is connected"}
]);
const [isLoading, setIsLoading] = useState(false);

const router = useRouter();
const handleConnect = async () => {
setIsLoading(true);

setMessages(prevMessages =>
prevMessages.map(msg =>
msg.id === 1 ? { ...msg, success: true } : msg
)
);

try {
const ablyClient = new Ably.Realtime({ authUrl: 'http://localhost:3001/request-token' });
setClient(ablyClient);

setMessages(prevMessages =>
prevMessages.map(msg =>
msg.id === 2 ? { ...msg, success: true } : msg
)
);

ablyClient.connection.on('connected', (stateChange) => {
setMessages(prevMessages =>
prevMessages.map(msg =>
msg.id === 3 ? { ...msg, success: true } : msg
)
);
});
} catch (error) {
console.error('Failed to initialise client:', error);
} finally {
setIsLoading(false);
}
router.push('/authenticated');
};

return (
<div className="flex items-center justify-center min-h-screen bg-gray-100">
<div className="bg-white shadow-md rounded-md p-8 w-[50%] flex flex-col">
<div className="flex-grow text-center">
<h1 className="text-2xl font-bold mb-4">Authentication with Ably</h1>
{client ? (
<p className="mb-8">The Ably client has been successfully initialized.</p>
) : (
<p className="mb-8">Press the Connect button to initialize the client:</p>
)}
<p>Press the Connect button to initialize the client:</p>
<button
onClick={handleConnect}
className={`px-4 py-2 text-white rounded ${isLoading || client !== null ? 'bg-gray-500' : 'bg-blue-500 hover:bg-blue-600' }`}
disabled={client !== null || isLoading}
className='px-4 py-2 text-white rounded bg-blue-500 hover:bg-blue-600'
>
{isLoading ? 'Connecting...' : 'Connect'}
Connect
</button>
</div>

Expand Down

0 comments on commit e73db59

Please sign in to comment.