-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkJWT.js
41 lines (31 loc) · 1.07 KB
/
checkJWT.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
const { JWT, JWK } = require(`jose`)
const pemFile = process.env.JWT_PUBLIC_KEY
const pubKey = JWK.asKey(pemFile)
module.exports = (authorization, desiredClaim, subject, issuer) => {
const [ _, token ] = authorization.split(` `)
let decodedToken
try {
decodedToken = JWT.verify(token, pubKey.trim(), {
subject,
issuer
})
} catch (e) {
console.log(`error due to invalid token`)
return false
}
const hasValidClaim = decodedToken.claims.some((tokenClaim) => {
// "*" claim is all access
if (tokenClaim === `*`) return true
if (tokenClaim === desiredClaim) return true
// Wildcard is valid as last position, to allow all claims below that level
// For instance, `trello.*` will give all access to all Trello data
if (tokenClaim.includes(`*`)) {
const tokenClaimParts = tokenClaim.split(`:`).slice(0, -1)
const desiredClaimParts = desiredClaim.split(`:`)
return tokenClaimParts.every((claimPart, index) => {
return desiredClaimParts[index] === claimPart
})
}
})
return hasValidClaim
}