Skip to content

Commit

Permalink
add example (#111)
Browse files Browse the repository at this point in the history
* add example

* use timingSafeEqual
  • Loading branch information
Uzlopak authored Nov 29, 2022
1 parent 7d284bc commit 8b59623
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions example/example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
'use strict'

const fastify = require('fastify')()
const crypto = require('crypto')
const authenticate = { realm: 'Westeros' }

const validUsername = 'Tyrion'
const validPassword = 'wine'

fastify.register(require('..'), { validate, authenticate })

// perform constant-time comparison to prevent timing attacks
function compare (a, b) {
a = Buffer.from(a)
b = Buffer.from(b)
if (a.length !== b.length) {
// Delay return with cryptographically secure timing check.
crypto.timingSafeEqual(a, a)
return false
}

return crypto.timingSafeEqual(a, b)
}

// `this` inside validate is `fastify`
function validate (username, password, req, reply, done) {
let result = true
result = compare(username, validUsername) && result
result = compare(password, validPassword) && result
if (result) {
done()
} else {
done(new Error('Winter is coming'))
}
}

fastify.after(() => {
fastify.addHook('onRequest', fastify.basicAuth)

fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
})

const basicAuthCredentials = Buffer.from(`${validUsername}:${validPassword}`).toString('base64')
console.log(`curl -H "authorization: Basic ${basicAuthCredentials}" http://localhost:3000`)
fastify.listen({ port: 3000 })

0 comments on commit 8b59623

Please sign in to comment.