-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontacts-api.js
63 lines (52 loc) · 1.58 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
61
62
63
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,
// Replace with your Auth0 Domain
jwksUri: `https://demonstration.auth0.com/.well-known/jwks.json`
}),
// Validate the audience and the issuer
audience: 'organise',
// Replace with your Auth0 Domain
issuer: `https://demonstration.auth0.com/`,
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.send({ contacts: [
{ name: "Jane", email: "jane@example.com" },
{ name: "John", email: "john@example.com" }
] });
});
app.listen(port, function () {
console.log('Contacts API started on port: ' + port);
});