Skip to content

Commit

Permalink
Add fastify example with Basic Auth
Browse files Browse the repository at this point in the history
  • Loading branch information
felixmosh committed Sep 8, 2021
1 parent 4ef04ae commit f7d2b43
Show file tree
Hide file tree
Showing 5 changed files with 748 additions and 0 deletions.
14 changes: 14 additions & 0 deletions examples/with-fastify-auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Fastify example

This example shows how to use [Fastify.js](https://www.fastify.io/) as a server for bull-board.

### Notes
1. It will work with any **cookie** / **basic auth** based auth, since the browser will attach
the `session` cookie / basic auth header automatically to **each** request.


### Usage
1. Navigate to `/login`
2. Fill in username: `bull` & password: `board`

Based on: https://github.com/fastify/fastify-basic-auth
38 changes: 38 additions & 0 deletions examples/with-fastify-auth/bull-board-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const { FastifyAdapter } = require('@bull-board/fastify');
const { createBullBoard } = require('@bull-board/api');
const { BullMQAdapter } = require('@bull-board/api/bullMQAdapter');

module.exports.bullBoardWithAuth = function bullBoardWithAuth(fastify, { queue }, next) {
const authenticate = { realm: 'Westeros' };
function validate(username, password, req, reply, done) {
if (username === 'bull' && password === 'board') {
done();
} else {
done(new Error('Unauthorized'));
}
}

fastify.register(require('fastify-basic-auth'), { validate, authenticate });

fastify.after(() => {
const serverAdapter = new FastifyAdapter();

createBullBoard({
queues: [new BullMQAdapter(queue)],
serverAdapter,
});

serverAdapter.setBasePath('/ui');
fastify.register(serverAdapter.registerPlugin(), { prefix: '/ui' });
fastify.route({
method: 'GET',
url: '/login',
handler: async (req, reply) => {
reply.redirect('/ui');
},
});
fastify.addHook('onRequest', fastify.basicAuth);
});

next();
};
73 changes: 73 additions & 0 deletions examples/with-fastify-auth/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
const { bullBoardWithAuth } = require('./bull-board-plugin');
const { Queue: QueueMQ, Worker, QueueScheduler } = require('bullmq');
const fastify = require('fastify');

const sleep = (t) => new Promise((resolve) => setTimeout(resolve, t * 1000));

const redisOptions = {
port: 6379,
host: 'localhost',
password: '',
tls: false,
};

const createQueueMQ = (name) => new QueueMQ(name, { connection: redisOptions });

async function setupBullMQProcessor(queueName) {
const queueScheduler = new QueueScheduler(queueName, {
connection: redisOptions,
});
await queueScheduler.waitUntilReady();

new Worker(queueName, async (job) => {
for (let i = 0; i <= 100; i++) {
await sleep(Math.random());
await job.updateProgress(i);
await job.log(`Processing job at interval ${i}`);

if (Math.random() * 200 < 1) throw new Error(`Random error ${i}`);
}

return { jobId: `This is the return value of job (${job.id})` };
});
}

const run = async () => {
const exampleBullMq = createQueueMQ('BullMQ');

await setupBullMQProcessor(exampleBullMq.name);

const app = fastify();

app.register(bullBoardWithAuth, { queue: exampleBullMq });

app.get('/add', (req, reply) => {
const opts = req.query.opts || {};

if (opts.delay) {
opts.delay = +opts.delay * 1000; // delay must be a number
}

exampleBullMq.add('Add', { title: req.query.title }, opts);

reply.send({
ok: true,
});
});

await app.listen(3000);
// eslint-disable-next-line no-console
console.log('Running on 3000...');
console.log('For the UI of instance1, open http://localhost:3000/ui');
console.log('Make sure Redis is running on port 6379 by default');
console.log('To populate the queue, run:');
console.log(' curl http://localhost:3000/add?title=Example');
console.log('To populate the queue with custom options (opts), run:');
console.log(' curl http://localhost:3000/add?title=Test&opts[delay]=9');
};

run().catch((e) => {
// eslint-disable-next-line no-console
console.error(e);
process.exit(1);
});
17 changes: 17 additions & 0 deletions examples/with-fastify-auth/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "bull-board-with-fastify",
"version": "1.0.0",
"description": "Example of how to use Fastify server with bull-board",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "felixmosh",
"license": "ISC",
"dependencies": {
"@bull-board/fastify": "^3.5.4",
"bullmq": "^1.46.3",
"fastify-basic-auth": "^2.1.0"
}
}
Loading

0 comments on commit f7d2b43

Please sign in to comment.