-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
authentication.js
63 lines (53 loc) · 1.6 KB
/
authentication.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
'use strict'
const fastify = require('fastify')
const fastifySession = require('@fastify/session')
const fastifyCookie = require('@fastify/cookie')
const fastifyFormbody = require('@fastify/formbody')
const { loginPage, defaultPage } = require('./html')
function plugin (instance, options, next) {
// register the required plugins
instance.register(fastifyFormbody)
instance.register(fastifyCookie)
instance.register(fastifySession, {
cookieName: 'sessionId',
secret: 'a secret with minimum length of 32 characters',
cookie: { maxAge: 1800000, secure: false }
})
// add a login route that returns a login page
instance.get('/login', (request, reply) => {
reply.type('text/html')
reply.send(loginPage())
})
// add a login route that handles the actual login
instance.post('/login', (request, reply) => {
const { email, password } = request.body
if (password === 'abcdef') {
request.session.authenticated = true
reply.type('text/html')
reply.send(defaultPage(true))
} else {
reply.redirect(401, '/login')
}
});
instance.get('/', (request, reply) => {
reply.type('text/html')
reply.send(defaultPage(request.session.authenticated))
});
// add a logout route
instance.get('/logout', (request, reply) => {
if (request.session.authenticated) {
request.session.destroy((err) => {
if (err) {
reply.status(500)
reply.send('Internal Server Error')
} else {
reply.redirect('/')
}
})
} else {
reply.redirect('/')
}
});
next()
}
module.exports = plugin