-
Notifications
You must be signed in to change notification settings - Fork 70
/
express.js
45 lines (35 loc) · 1.08 KB
/
express.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
import { Bearer } from 'permit'
import express from 'express'
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.
})
function authenticate(req, res, next) {
// 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 next(new Error(`Authentication required!`))
}
// Perform your authentication logic however you'd like...
db.users.findByToken(token, (err, user) => {
if (err) return next(err)
// No user found, so their token was invalid.
if (!user) {
permit.fail(res)
return next(new Error(`Authentication invalid!`))
}
// Authentication succeeded, save the context and proceed...
req.user = user
next()
})
}
const app = express()
app.get('/', (req, res) => {
res.send('Some unrestricted content.')
})
app.get('/restricted', authenticate, (req, res) => {
res.send('Restricted content!')
})
app.listen(3000)