-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
126 lines (104 loc) · 3.24 KB
/
index.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
const cookieParser = require('cookie-parser');
const bcrypt = require('bcrypt');
const express = require('express');
const app = express();
const DB = require('./database.js');
const { PeerProxy } = require('./peerProxy.js');
const authCookieName = 'token';
// The service port may be set on the command line
const port = process.argv.length > 2 ? process.argv[2] : 3000;
// JSON body parsing using built-in middleware
app.use(express.json());
// Use the cookie parser middleware for tracking authentication tokens
app.use(cookieParser());
// Serve up the applications static content
app.use(express.static('public'));
// Router for service endpoints
var apiRouter = express.Router();
app.use(`/api`, apiRouter);
// CreateAuth token for a new user
apiRouter.post('/auth/create', async (req, res) => {
if (await DB.getUser(req.body.email)) {
res.status(409).send({ msg: 'Existing user' });
} else {
const user = await DB.createUser(req.body.email, req.body.password);
// Set the cookie
setAuthCookie(res, user.token);
res.send({
id: user._id,
});
}
});
// GetAuth token for the provided credentials
apiRouter.post('/auth/login', async (req, res) => {
const user = await DB.getUser(req.body.email);
if (user) {
if (await bcrypt.compare(req.body.password, user.password)) {
setAuthCookie(res, user.token);
res.send({ id: user._id });
return;
}
}
res.status(401).send({ msg: 'Unauthorized' });
});
// DeleteAuth token if stored in cookie
apiRouter.delete('/auth/logout', (_req, res) => {
res.clearCookie(authCookieName);
res.status(204).end();
});
// GetUser returns information about a user
apiRouter.get('/user/:email', async (req, res) => {
const user = await DB.getUser(req.params.email);
if (user) {
const token = req?.cookies.token;
res.send({ email: user.email, authenticated: token === user.token });
return;
}
res.status(404).send({ msg: 'Unknown' });
});
// secureApiRouter verifies credentials for endpoints
var secureApiRouter = express.Router();
apiRouter.use(secureApiRouter);
secureApiRouter.use(async (req, res, next) => {
authToken = req.cookies[authCookieName];
const user = await DB.getUserByToken(authToken);
if (user) {
next();
} else {
res.status(401).send({ msg: 'Unauthorized' });
}
});
// GetScores
secureApiRouter.get('/scores', async (req, res) => {
const scores = await DB.getHighScores();
res.send(scores);
});
// SubmitScore
secureApiRouter.post('/score', async (req, res) => {
await DB.addScore(req.body);
const scores = await DB.getHighScores();
res.send(scores);
});
// Default error handler
app.use(function (err, req, res, next) {
res.status(500).send({ type: err.name, message: err.message });
});
// Return the application's default page if the path is unknown
app.use((_req, res) => {
res.sendFile('index.html', { root: 'public' });
});
// setAuthCookie in the HTTP response
function setAuthCookie(res, authToken) {
res.cookie(authCookieName, authToken, {
secure: true,
httpOnly: true,
sameSite: 'strict',
});
}
// app.listen(port, () => {
// console.log(`Listening on port ${port}`);
// });
const httpService = app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
new PeerProxy(httpService);