diff --git a/index.js b/index.js index 87b2c2b..84fdc4d 100644 --- a/index.js +++ b/index.js @@ -2,7 +2,13 @@ const fp = require('fastify-plugin') const auth = require('basic-auth') -const { Unauthorized } = require('http-errors') +const createError = require('@fastify/error') + +const MissingOrBadAuthorizationHeader = createError( + 'FST_BASIC_AUTH_MISSING_OR_BAD_AUTHORIZATION_HEADER', + 'Missing or bad formatted authorization header', + 401 +) async function basicPlugin (fastify, opts) { if (typeof opts.validate !== 'function') { @@ -17,7 +23,7 @@ async function basicPlugin (fastify, opts) { function basicAuth (req, reply, next) { const credentials = auth.parse(req.headers[header]) if (credentials == null) { - done(new Unauthorized('Missing or bad formatted authorization header')) + done(new MissingOrBadAuthorizationHeader()) } else { const result = validate(credentials.name, credentials.pass, req, reply, done) if (result && typeof result.then === 'function') { diff --git a/package.json b/package.json index 0f47ecd..9da6054 100644 --- a/package.json +++ b/package.json @@ -33,9 +33,9 @@ "tsd": "^0.22.0" }, "dependencies": { + "@fastify/error": "^3.0.0", "basic-auth": "^2.0.1", - "fastify-plugin": "^3.0.0", - "http-errors": "^2.0.0" + "fastify-plugin": "^3.0.0" }, "publishConfig": { "access": "public" diff --git a/test.js b/test.js index 401fe41..bd3159b 100644 --- a/test.js +++ b/test.js @@ -4,7 +4,6 @@ const { test } = require('tap') const Fastify = require('fastify') const basicAuth = require('./index') const fastifyAuth = require('@fastify/auth') -const { Unauthorized } = require('http-errors') test('Basic', t => { t.plan(2) @@ -476,6 +475,7 @@ test('Missing header', t => { t.equal(res.statusCode, 401) t.same(JSON.parse(res.payload), { statusCode: 401, + code: 'FST_BASIC_AUTH_MISSING_OR_BAD_AUTHORIZATION_HEADER', error: 'Unauthorized', message: 'Missing or bad formatted authorization header' }) @@ -567,7 +567,7 @@ test('setErrorHandler custom error and 401', t => { }) test('Missing header and custom error handler', t => { - t.plan(4) + t.plan(6) const fastify = Fastify() fastify.register(basicAuth, { validate }) @@ -592,7 +592,9 @@ test('Missing header and custom error handler', t => { }) fastify.setErrorHandler(function (err, req, reply) { - t.ok(err instanceof Unauthorized) + t.ok(err instanceof Error) + t.ok(err.statusCode === 401) + t.ok(err.code === 'FST_BASIC_AUTH_MISSING_OR_BAD_AUTHORIZATION_HEADER') reply.send(err) }) @@ -604,6 +606,7 @@ test('Missing header and custom error handler', t => { t.equal(res.statusCode, 401) t.same(JSON.parse(res.payload), { statusCode: 401, + code: 'FST_BASIC_AUTH_MISSING_OR_BAD_AUTHORIZATION_HEADER', error: 'Unauthorized', message: 'Missing or bad formatted authorization header' })