-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
75 lines (63 loc) · 1.52 KB
/
index.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
const querystring = require('querystring')
const axios = require('axios')
const { sendError } = require('micro')
const assert = require('assert')
const introspectToken = async ({
introspectionUrl,
clientId,
clientSecret,
accessToken,
debug
}) => {
const { data } = await axios({
method: 'post',
url: introspectionUrl,
auth: {
username: clientId,
password: clientSecret
},
data: querystring.stringify({
token: accessToken
})
})
if (debug) {
console.log(data)
}
const { active, scope, sub: userId } = data
if (!active) {
throw Error('Access token has expired or been revoked')
}
return { userId, scope }
}
module.exports = exports = config => fn => {
const { introspectionUrl, clientId, clientSecret } = config
if (!introspectionUrl || !clientId || !clientSecret) {
throw Error(
'Must provide config with introspectionUrl, clientId, and clientSecret properties'
)
}
return async (req, res) => {
const bearerToken = req.headers.authorization
if (!bearerToken) {
return sendError(req, res, {
statusCode: 401,
message: 'missing Authorization header'
})
}
const accessToken = bearerToken.replace('Bearer ', '')
try {
req.userData = await introspectToken({
clientId,
clientSecret,
introspectionUrl,
accessToken
})
return fn(req, res)
} catch (error) {
return sendError(req, res, {
statusCode: 403,
status: 403
})
}
}
}