-
-
Notifications
You must be signed in to change notification settings - Fork 368
/
cookieAuth.js
85 lines (72 loc) · 2.18 KB
/
cookieAuth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const { FastifyAdapter } = require('@bull-board/fastify');
const { createBullBoard } = require('@bull-board/api');
const { BullMQAdapter } = require('@bull-board/api/bullMQAdapter');
const pointOfView = require('@fastify/view');
const path = require('path');
module.exports.cookieAuth = function cookieAuth(fastify, { queue }, next) {
fastify.register(require('@fastify/cookie'), {
secret: 'my-secret-key', // for cookies signature
});
fastify.register(require('@fastify/jwt'), {
secret: 'super-secret',
cookie: {
cookieName: 'token',
},
});
fastify.after(() => {
const serverAdapter = new FastifyAdapter();
createBullBoard({
queues: [new BullMQAdapter(queue)],
serverAdapter,
});
serverAdapter.setBasePath('/cookie/ui');
fastify.register(serverAdapter.registerPlugin(), { prefix: '/cookie/ui' });
fastify.register(pointOfView, {
engine: {
ejs: require('ejs'),
},
root: path.resolve('./views'),
});
fastify.route({
method: 'GET',
url: '/cookie/login',
handler: (req, reply) => {
reply.view('login.ejs');
},
});
fastify.route({
method: 'POST',
url: '/cookie/login',
handler: async (req, reply) => {
const { username = '', password = '' } = req.body;
if (username === 'bull' && password === 'board') {
const token = await reply.jwtSign({
name: 'foo',
role: ['admin', 'spy'],
});
reply
.setCookie('token', token, {
path: '/cookie',
secure: false, // send cookie over HTTPS only
httpOnly: true,
sameSite: true, // alternative CSRF protection
})
.send({ success: true, url: '/cookie/ui' });
} else {
reply.code(401).send({ error: 'invalid_username_password' });
}
},
});
fastify.addHook('preHandler', async (request, reply) => {
if (request.url === '/cookie/login') {
return;
}
try {
await request.jwtVerify();
} catch (error) {
reply.code(401).send({ error: 'Unauthorized' });
}
});
});
next();
};