Skip to content

Commit

Permalink
Record redirect events (github#16181)
Browse files Browse the repository at this point in the history
* Record redirect events

* Update index.js

* Update record-redirect.js

* Only run when it can send to Hydro

* Update record-redirect.js
  • Loading branch information
heiskr authored Oct 26, 2020
1 parent 222d419 commit 9384979
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
7 changes: 7 additions & 0 deletions lib/hydro.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ module.exports = class Hydro {
this.schemas = SCHEMAS
}

/**
* Can check if it can actually send to Hydro
*/
maySend () {
return Boolean(this.secret && this.endpoint)
}

/**
* Generate a SHA256 hash of the payload using the secret
* to authenticate with Hydro
Expand Down
5 changes: 3 additions & 2 deletions middleware/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ module.exports = function (app) {
app.use(require('morgan')('dev', { skip: (req, res) => !isDevelopment }))
app.use(require('./rate-limit'))
if (isDevelopment) app.use(require('./webpack'))
app.use(require('./cookie-parser'))
app.use(require('./req-utils'))
app.use(require('./record-redirect'))
app.use(require('./redirects/external'))
app.use(require('./redirects/help-to-docs'))
app.use(require('./set-fastly-cache-headers'))
Expand All @@ -24,9 +27,7 @@ module.exports = function (app) {
app.use(require('./cors'))
app.use(require('./csp'))
app.use(require('helmet')())
app.use(require('./req-utils'))
app.use(require('./robots'))
app.use(require('./cookie-parser'))
app.use(express.json()) // Must come before ./csrf
app.use(require('./csrf'))
app.use(require('./handle-csrf-errors'))
Expand Down
27 changes: 27 additions & 0 deletions middleware/record-redirect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const { v4: uuidv4 } = require('uuid')
const { inRange } = require('lodash')

module.exports = function (req, res, next) {
if (!req.hydro.maySend()) return next()

res.on('finish', async function recordRedirect () {
if (!inRange(res.statusCode, 300, 400)) return
const schemaName = req.hydro.schemas.redirect
const redirectEvent = {
context: {
user: req.cookies['_docs-events'] || uuidv4(),
event_id: uuidv4(),
version: '1.0.0',
created: new Date().toISOString(),
path: req.path,
referrer: req.get('referer')
},
redirect_from: req.originalUrl,
redirect_to: res.get('location')
}
const hydroRes = await req.hydro.publish(schemaName, redirectEvent)
if (!hydroRes.ok) console.log('Failed to record redirect to Hydro')
})

return next()
}

0 comments on commit 9384979

Please sign in to comment.