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

add example #111

Merged
merged 2 commits into from
Nov 29, 2022
Merged
Changes from 1 commit
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
29 changes: 29 additions & 0 deletions example/example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict'

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

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

fastify.register(require('..'), { validate, authenticate })
// `this` inside validate is `fastify`
function validate (username, password, req, reply, done) {
if (username === validUsername && password === validPassword) {
done()
} else {
done(new Error('Winter is coming'))
}
Uzlopak marked this conversation as resolved.
Show resolved Hide resolved
}

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 })