-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
41 lines (34 loc) · 987 Bytes
/
app.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
const express = require('express');
const jwt = require('jsonwebtoken');
const axios = require('axios');
const config = require('./config');
const app = express();
const port = 4000;
app.use(express.json());
const authenticateToken = async (req, res, next) => {
const token = req.headers['authorization'];
if (!token) return res.sendStatus(401);
if (config.useExternalIDP) {
try {
const response = await axios.get(config.externalIDPConfig.userInfoUrl, {
headers: { Authorization: token }
});
req.user = response.data;
next();
} catch (err) {
return res.sendStatus(403);
}
} else {
jwt.verify(token, config.secretKey, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
};
app.get('/protected', authenticateToken, (req, res) => {
res.send('This is a protected route');
});
app.listen(port, () => {
console.log(`App running at http://localhost:${port}`);
});