Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[EDU-1654] - Add generate Ably token authentication example #2322

Merged
merged 1 commit into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions examples/auth-request-token/javascript/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
57 changes: 57 additions & 0 deletions examples/auth-request-token/javascript/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Generate an Ably Token to authenticate clients

This folder contains the code for the authentication (Typescript) - a demo of how you can authenticate with [Ably](https://ably.com/docs/auth) to use any of the products.

## Getting started

1. Clone the [Ably docs](https://github.com/ably/docs) repository where this example can be found:

```sh
git clone [email protected]:ably/docs.git
```

2. Change directory:

```sh
cd /examples/auth-request-token/javascript/
```

3. Install dependencies:

```sh
yarn install
```

4. Run the frontend client:

```sh
yarn run dev
```

5. In a new tab, change directory:

```sh
cd /examples/auth-request-token/server/
```

6. Rename the environment file:

```sh
mv .env.example .env.local
```

7. In `.env.local` update the value of `VITE_PUBLIC_ABLY_KEY` to be your Ably API key.

8. Install dependencies:

```sh
yarn install
```

9. Run the backend server:

```sh
yarn run dev
```

10. Try it out by opening two tabs to [http://localhost:5173/](http://localhost:5173/) with your browser to see the result.
48 changes: 48 additions & 0 deletions examples/auth-request-token/javascript/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='https://fonts.googleapis.com/css?family=Inter' rel='stylesheet'>
<link rel="stylesheet" href="src/styles.css" />
<title>Generate Token</title>
</head>
<body class="font-inter">
<div class="flex items-center justify-center min-h-screen bg-gray-100">
<div class="bg-white shadow-md rounded-md p-8 w-[50%] flex flex-col">
<div class="flex-grow text-center">
<h1 class="text-2xl font-bold mb-4">
Authentication with Ably
</h1>
<p id="heading-message" class="mb-8">
Press the Connect button to initialize the client:
</p>
<button id="connect" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
Connect
</button>
</div>
<div class="mt-4 text-left text-sm h-40 overflow-y-auto">
<div class="flex items-center gap-2">
<span>
<span id="message-1" class="text-red-500">✗</span>
</span>
Client requests token from server
</div>
<div class="flex items-center gap-2">
<span>
<span id="message-2" class="text-red-500">✗</span>
</span>
Client initializes connection to Ably with generated Token
</div>
<div class="flex items-center gap-2">
<span>
<span id="message-3" class="text-red-500">✗</span>
</span>
Client is connected
</div>
</div>
</div>
</div>
<script type="module" src="src/script.ts"></script>
</body>
</html>
23 changes: 23 additions & 0 deletions examples/auth-request-token/javascript/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "auth-request-token",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"devDependencies": {
"autoprefixer": "^10.4.20",
"dotenv": "^16.4.5",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.13",
"typescript": "^5.6.3"
},
"dependencies": {
"ably": "^2.3.1",
"nanoid": "^5.0.7",
"vite": "^5.4.2"
}
}
39 changes: 39 additions & 0 deletions examples/auth-request-token/javascript/src/script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as Ably from 'ably';
import './styles.css';

const connectButton = document.querySelector('button') as HTMLButtonElement;

connectButton.addEventListener('click', () => {
handleConnect();
});

function handleConnect() {
try {
const messageOne = document.getElementById('message-1');
messageOne.className = 'text-green-500';
messageOne.textContent = '✓';

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

const messageTwo = document.getElementById('message-2');
messageTwo.className = 'text-green-500';
messageTwo.textContent = '✓';

const button = document.getElementById('connect') as HTMLButtonElement;
button.disabled = true;
button.className = 'px-4 py-2 text-white rounded bg-gray-500';

realtimeClient.connection.on('connected', (stateChange) => {
const messageThree = document.getElementById('message-3');
messageThree.className = 'text-green-500';
messageThree.textContent = '✓';

const headingMessage = document.getElementById('heading-message');
headingMessage.textContent = 'The Ably client has been successfully initialized.';
});
} catch (error) {
console.error('Failed to connect client:', error);
}
}
23 changes: 23 additions & 0 deletions examples/auth-request-token/javascript/src/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

.container {
width: 100%;
display: flex;
justify-content: center;
align-items: center;
position: relative;
background-color: #f4f8fb;
height: 100vh;
}

input {
padding: 0.5rem;
width: 100%;
height: 2.5rem;
font-size: 0.875rem;
border-radius: 0.375rem;
outline: none;
transition: all 0.2s ease-in-out;
}
12 changes: 12 additions & 0 deletions examples/auth-request-token/javascript/tailwind.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./index.html",
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}

15 changes: 15 additions & 0 deletions examples/auth-request-token/javascript/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"lib": ["dom", "es2015"],
"outDir": "./lib/cjs/",
"sourceMap": true,
"declaration": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es2017",
"allowJs": true,
"moduleResolution": "node"
},
"include": ["src/**/*.ts*"],
"exclude": ["node_modules", "dist", "lib"]
}
8 changes: 8 additions & 0 deletions examples/auth-request-token/javascript/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
interface ImportMetaEnv {
readonly VITE_PUBLIC_ABLY_KEY: string;
// Add other environment variables here if needed
}

interface ImportMeta {
readonly env: ImportMetaEnv;
}
12 changes: 12 additions & 0 deletions examples/auth-request-token/javascript/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { defineConfig } from 'vite'

export default defineConfig({
css: {
postcss: {
plugins: [
require('tailwindcss'),
require('autoprefixer'),
],
}
}
})
Loading