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

Bind fastify in validate #2

Merged
merged 3 commits into from
Jun 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@
npm i fastify-basic-auth
```
## Usage
This plugin decorates the fastifyinstance with a `basicAuth` function, which you can use inside a `preHandler` hook, in a `beforeHander` or with [`fastify-auth`](https://github.com/fastify/fastify-auth).
This plugin decorates the fastify instance with a `basicAuth` function, which you can use inside a `preHandler` hook, in a `beforeHander` or with [`fastify-auth`](https://github.com/fastify/fastify-auth).

```js
const fastify = require('fastify')()

fastify.register(require('fastify-basic-auth'), { validate })
// `this` inside validate is `fastify`
function validate (username, password, req, reply, done) {
if (username === 'Tyrion' && password === 'wine') {
done()
Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ function basicPlugin (fastify, opts, next) {
return next(new Error('Basic Auth: Missing validate function'))
}

const validate = opts.validate
const validate = opts.validate.bind(fastify)
fastify.decorate('basicAuth', basicAuth)

next()
Expand Down
39 changes: 39 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,45 @@ test('Missing header', t => {
})
})

test('Fastify context', t => {
t.plan(3)

const fastify = Fastify()
fastify.decorate('test', true)
fastify.register(basicAuth, { validate })

function validate (username, password, req, res, done) {
t.ok(this.test)
if (username === 'user' && password === 'pwd') {
done()
} else {
done(new Error('Unauthorized'))
}
}

fastify.after(() => {
fastify.route({
method: 'GET',
url: '/',
beforeHandler: fastify.basicAuth,
handler: (req, reply) => {
reply.send({ hello: 'world' })
}
})
})

fastify.inject({
url: '/',
method: 'GET',
headers: {
authorization: basicAuthHeader('user', 'pwd')
}
}, (err, res) => {
t.error(err)
t.strictEqual(res.statusCode, 200)
})
})

function basicAuthHeader (username, password) {
return 'Basic ' + Buffer.from(`${username}:${password}`).toString('base64')
}