-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathserver.js
More file actions
67 lines (54 loc) · 1.69 KB
/
server.js
File metadata and controls
67 lines (54 loc) · 1.69 KB
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
const bodyParser = require('body-parser');
const express = require('express');
const Authentication = require('./auth');
const authConfig = require('./auth-config');
class InMemoryUserStore {
constructor() {
this.users = [];
}
push(user) {
this.users.push(user);
}
get(userId) {
return this.users.find(u => u.id === userId);
}
}
const userStore = new InMemoryUserStore();
const auth = new Authentication({ routes: authConfig });
const PORT = process.env.PORT || 5000;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(auth.filter());
const handleProtectedResource = (req, res) => {
const principal = res.locals.principal;
const localUser = userStore.get(principal.sub);
const name = localUser ? localUser.name : principal.sub;
res.json({
user: name
}).end();
}
const handleTokenRequest = (req, res) => {
try {
const login = req.body;
auth.authenticate(login).then(credentials => {
userStore.push(credentials.user);
res.json(credentials).end();
});
} catch (error) {
res.status(500).json({ error: 'Internal server error' }).end();
} finally {
}
}
const handlePublicResource = (req, res) => {
res.json({ hello: 'from server' }).end();
}
app.post('/auth/token', handleTokenRequest);
app.get('/protected', handleProtectedResource);
app.get('/public', handlePublicResource);
app.use(express.static('static'));
const server = app.listen(PORT, () => {
console.log(
`server is listening on http://localhost:${server.address().port}`
);
});