-
Notifications
You must be signed in to change notification settings - Fork 70
/
hapi.js
46 lines (37 loc) · 1.12 KB
/
hapi.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
import { Bearer } from 'permit'
import Hapi from 'hapi'
const permit = new Bearer({
basic: 'username', // Also allow a Basic Auth username as a token.
query: 'access_token', // Also allow an `?access_token=` query parameter.
})
const server = new Hapi.Server({
host: '0.0.0.0',
port: 3000,
})
server.route({
method: 'GET',
path: '/restricted',
handler: (request, reply) => {
const { req, res } = request.raw
// Try to find the bearer token in the request.
const token = permit.check(req)
// No token found, so ask for authentication.
if (!token) {
permit.fail(res)
return reply(new Error(`Authentication required!`))
}
// Perform your authentication logic however you'd like...
db.users.findByToken(token, (err, user) => {
if (err) return reply(err)
// No user found, so their token was invalid.
if (!user) {
permit.fail(res)
return reply(new Error(`Authentication invalid!`))
}
// Authentication succeeded, save the context and proceed...
request.user = user
reply('Some restricted content.')
})
},
})
server.start()