-
Notifications
You must be signed in to change notification settings - Fork 0
/
contacts-api.js
60 lines (51 loc) · 1.54 KB
/
contacts-api.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
const express = require('express');
const app = express();
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
const cors = require('cors');
require('dotenv').config();
const port = process.env.CONTACTS_API_PORT;
const domain = process.env.AUTH0_DOMAIN;
app.use(cors());
// Validate the access token and enable the use of the jwtCheck middleware
app.use(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://${domain}/.well-known/jwks.json`
}),
// Validate the audience and the issuer
audience: 'organise',
issuer: `https://${domain}/`,
algorithms: [ 'RS256' ]
}));
// Middleware to check scopes
const checkPermissions = function (req, res, next) {
switch (req.path) {
case '/api/contacts': {
var permissions = ['read:contacts'];
for (var i = 0; i < permissions.length; i++) {
if (req.user.scope.includes(permissions[i])) {
next();
} else {
res.status(403).send({message: 'Forbidden'});
}
}
break;
}
}
};
app.use(checkPermissions);
app.get('/api/contacts', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send({ contacts: [
{ name: 'Jane', email: '[email protected]' },
{ name: 'John', email: '[email protected]' }
] });
});
app.listen(port, function () {
console.log('Contacts API started on port: ' + port);
});