Skip to content

Commit

Permalink
feat: introducing subsriber authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
ErwannLeRoux committed Apr 6, 2023
1 parent 4b4bb5e commit dc022bc
Show file tree
Hide file tree
Showing 10 changed files with 1,301 additions and 7 deletions.
7 changes: 5 additions & 2 deletions .env.dist
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ MYSQL_DATABASE=databasorus
MYSQL_USER=user
MYSQL_PASSWORD=password

MERCURE_URL=http://localhost:81/mercure
MERCURE_PUBLIC_URL=http://localhost:81/mercure
MERCURE_SERVER_NAME=:80
MERCURE_URL=http://mercure/.well-known/mercure
MERCURE_PUBLIC_URL=http://localhost:81/.well-known/mercure
MERCURE_PUBLISHER_JWT_KEY=!ChangeThisMercureHubJWTSecretKey!
MERCURE_SUBSCRIBER_JWT_KEY=!ChangeThisMercureHubJWTSecretKey!
MERCURE_CORS_ALLOW_ORIGIN="cors_origin http://localhost:80"

34 changes: 34 additions & 0 deletions public/js/activity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const activityContainer = document.querySelector('#activity')

fetch(`/api/activity`)
.then(async response => {
const bearer = response.headers.get('x-mercure-token')

if (!bearer) return

const hubUrl = response.headers.get('Link').match(/<([^>]+)>;\s+rel=(?:mercure|"[^"]*mercure[^"]*")/)[1]

const hub = new URL(hubUrl, window.origin);
const body = await response.json()

hub.searchParams.append('topic', body.topic)

const es = new EventSourcePolyfill(hub, {
headers: {
'Authorization': bearer,
}
})

es.onmessage = event => {
const data = JSON.parse(event.data)

const item = document.createElement('div')

item.setAttribute('class', 'alert alert-primary')
item.setAttribute('role', 'alert')

item.innerHTML = data.message

activityContainer.append(item)
}
});
20 changes: 15 additions & 5 deletions public/js/dinosaur.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,26 @@ const dinosaurId = dinosaurSection.dataset.id

fetch(`/api/dinosaurs/${dinosaurId}`)
.then(async response => {
// Extract the hub URL from the Link header
const bearer = response.headers.get('x-mercure-token')

/*
* If no JWT is provided, it means that the user won't
* be able to subscribe to the updates.
*/
if (!bearer) return

const hubUrl = response.headers.get('Link').match(/<([^>]+)>;\s+rel=(?:mercure|"[^"]*mercure[^"]*")/)[1]

const hub = new URL(hubUrl, window.origin);
const body = await response.json()

console.log(body)
hub.searchParams.append('topic', body.topic)

// Subscribe to updates
const eventSource = new EventSource(hub);
eventSource.onmessage = event => window.location.reload()
const es = new EventSourcePolyfill(hub, {
headers: {
'Authorization': bearer,
}
})

es.onmessage = event => console.log(event)
});
Loading

0 comments on commit dc022bc

Please sign in to comment.