-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
67 lines (56 loc) · 1.74 KB
/
index.ts
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
/// <reference path="./typings/express.d.ts" />
import * as express from 'express'
import * as jwt from 'express-jwt'
var jwksRsa = require('jwks-rsa')
var compose = require('compose-middleware').compose
//
// And Here We Test Our Powers of Observation
// - The Bad Plus
//
export interface AuthOptions {
audience: string,
requireRole?: string | string[],
}
export default function parseAuth0Jwt (options: AuthOptions) {
if ( typeof options.requireRole === 'string' ) {
options.requireRole = [options.requireRole]
}
const requireRole = options.requireRole
return compose([
jwt({
// Dynamically provide a signing key
// based on the kid in the header and
// the singing keys provided by the JWKS endpoint.
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: 'https://hackreactor.auth0.com/.well-known/jwks.json'
}),
// Validate the audience and the issuer.
audience: options.audience,
issuer: 'https://hackreactor.auth0.com/',
algorithms: ['RS256'],
requestProperty: 'idTokenPayload',
}),
function (req: express.Request, res: express.Response, next: express.NextFunction) {
var payload = req.idTokenPayload
if ( payload ) {
req.apiUser = {
auth0_id: payload.sub,
roles: payload['https://my.hackreactor.com/roles'] || [],
}
if ( requireRole ) {
//
// Attempt to find a valid role
//
var found = req.apiUser.roles.find( r => requireRole.indexOf(r) >= 0 )
if ( ! found ) {
return res.status(403).send({ role_required: requireRole })
}
}
}
next()
}
])
}