Sample user-management (signup, login) with Fastify and JWT, on top of MongoDB.
This plugin sends credentials in plain text, and it implies that HTTPS is used to protect the application.
npm i @matteo.collina/fastify-auth-mongo-jwt
'use strict'
const Fastify = require('fastify')
const AuthMongoJwt = require('@matteo.collina/fastify-auth-mongo-jwt')
const app = Fastify()
app.register(AuthMongoJwt, {
auth: {
secret: 'thisisalongsecretjustfortests'
},
mongodb: {
url: 'mongodb://mongo/mydb',
w: 1,
useNewUrlParser: true
}
})
app.register(async function (app, opts) {
app.addHook('preHandler', function (req, reply) {
return req.jwtVerify()
})
app.get('/username', async function (req, reply) {
return req.user.username
})
}, { prefix: '/protected' })
This fastify plugin offers the following routes.
Accepts the following body:
{
"username": 'a unique thing',
"password": 'a long password'
}
It will return a JWT token, encapsulated with an object:
{
"status": 'ok',
"token": 'a jwt token'
}
Requires the Authorization: Bearer TOKEN
header.
Returns the current user if the token is valid
{
"username": 'a unique thing'
}
Accepts the following body:
{
"username": 'a unique thing',
"password": 'a long password'
}
It will return a JWT token, encapsulated with an object:
{
"status": 'ok',
"token": 'a jwt token'
}
It adds the same decorators of fastify-jwt.
Utility function to help writing unit tests against this module. It
returns a JWT token
for the given user and an inject
function to
call HTTP endpoint with that token.
Example:
const Fastify = require('fastify')
const AuthMongoJwt = require('@matteo.collina/fastify-auth-mongo-jwt')
const { createUser } = AuthMongoJwt
async function run () {
const app = Fastify({
logger: {
level: 'error'
}
})
app.register(AuthMongoJwt, {
auth: {
secret: 'thisisalongsecretjustfortests'
},
mongodb: {
url: 'mongodb://mongo/mydb',
w: 1,
useNewUrlParser: true
}
})
app.register(async function (app, opts) {
app.addHook('preValidation', function (req, reply) {
return req.jwtVerify()
})
app.get('/username', async function (req, reply) {
return req.user.username
})
}, { prefix: '/protected' })
const {
token, // this is the JWT token
inject // utility function to inject with that token
} = await createUser(app)
const res = await inject({
url: '/username',
method: 'GET'
})
console.log(JSON.parse(res.body))
}
run()
MIT