Skip to content

Commit 37ff9bf

Browse files
add authentication to ditto
1 parent 94fa13f commit 37ff9bf

File tree

2 files changed

+26
-9
lines changed

2 files changed

+26
-9
lines changed

Diff for: src/App.js

+16-7
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import './App.css';
33
import Ditto from "./ditto"
44
import { useAuth0 } from "@auth0/auth0-react"
55

6+
const domain = "YOUR_AUTH0_DOMAIN_HERE";
7+
68
let ditto
79
function App() {
810
const { user, loginWithRedirect, getAccessTokenSilently, isAuthenticated, logout } = useAuth0()
@@ -11,23 +13,30 @@ function App() {
1113

1214
useEffect(() => {
1315
let liveQuery
14-
async function startDitto() {
15-
ditto = Ditto()
16-
liveQuery = ditto.store
17-
.collection('cars')
16+
async function refreshToken () {
17+
const accessToken = await getAccessTokenSilently({
18+
audience: `https://${domain}/api/v2/`,
19+
scope: "read:current_user",
20+
});
21+
22+
ditto = Ditto(accessToken)
23+
liveQuery = ditto.store.collection('cars')
1824
.findAll()
1925
.observeLocal((tickets) => {
2026
setCars(tickets.length)
2127
})
2228
}
23-
startDitto()
29+
30+
if (user) {
31+
refreshToken()
32+
}
2433
return () => {
2534
liveQuery?.stop()
2635
}
27-
}, []);
36+
}, [user, getAccessTokenSilently]);
2837

2938
function onAddClick (){
30-
if (!ditto) return setError('No Ditto.')
39+
if (!ditto || !user) return setError('You must log in first.')
3140
setError('')
3241
ditto.store.collection('cars').upsert({
3342
"name": 'Toyota'

Diff for: src/ditto.js

+10-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
11
import { Ditto } from '@dittolive/ditto'
22

33
let ditto
4-
export default function get() {
4+
export default function get(token) {
55
if (!ditto) {
6+
const authHandler = {
7+
authenticationRequired: async function (authenticator) {
8+
authenticator.loginWithToken(token, 'replit-auth')
9+
},
10+
authenticationExpiringSoon: function (authenticator, secondsRemaining) {
11+
authenticator.loginWithToken(token, 'replit-auth')
12+
},
13+
}
614
const identity = {
715
type: 'onlineWithAuthentication',
816
appID: 'YOUR_DITTO_APP_ID_HERE',
9-
token: 'YOUR_DITTO_TOKEN_HERE'
17+
authHandler: authHandler
1018
}
1119
ditto = new Ditto(identity, '/ditto')
1220
ditto.startSync()

0 commit comments

Comments
 (0)