-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
356 lines (295 loc) · 9.86 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
const express = require("express");
require('dotenv').config();
const fs = require('fs');
const Handlebars = require('handlebars');
const { MongoClient } = require('mongodb');
const { engine } = require('express-handlebars');
const cookieParser = require('cookie-parser');
const path = require('path');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
// Temp data storage
let refreshTokens = [];
const multer = require('multer'); // enable file uploads from the client
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
const core = require('./core/core.js');
core.init();
// Create an Express application
const app = express();
// Set up Handlebars
app.engine("hbs", engine({
defaultLayout: false,
}));
app.set('view engine', 'hbs');
app.set("views", __dirname);
// Handlebars Helpers
Handlebars.registerHelper('json', function(context) {
return JSON.stringify(context);
});
// Register Partials Manually
const registerPartials = () => {
const partialsDir = path.join(__dirname, 'components');
// Clear previously cached partials if necessary
Handlebars.partials = {};
fs.readdirSync(partialsDir).forEach(function (filename) {
const matches = /^([^.]+).hbs$/.exec(filename);
if (matches) {
const name = matches[1]; // File name without extension
const template = fs.readFileSync(path.join(partialsDir, filename), 'utf8');
// Use Handlebars directly to register the partial
Handlebars.registerPartial(name, template);
}
});
};
// Middleware to parse URL-encoded bodies (form data)
app.use(express.urlencoded({ extended: true }));
// Middleware to parse JSON bodies
app.use(express.json());
// Middleware to access cookies
app.use(cookieParser());
// Middleware to serve static files from the "public" directory
app.use(express.static(path.join(__dirname, "public")));
// Authenticate Token Middleware
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
// Check both headers and cookies
const token = authHeader?.split(' ')[1] || req.cookies['access_token'];
// Check if we have a token
if (token == null) {
return res.redirect('/login');
}
// Verify the token
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) {
return res.status(403).json({ message: 'Invalid or expired token' });
}
// We have a valid token
req.user = user;
next();
});
}
// Generate an access token
function generateAccessToken(user) {
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '120m' });
}
/**
* Root
* Serve the index.html file with no module loaded
*/
app.get("/", authenticateToken, async (req, res) => {
const data = {...core.coreData, user: req.user};
registerPartials();
res.render("core/index", data);
});
/**
* Login Forn
*/
app.get("/login", async (req, res) => {
registerPartials();
res.render("core/login");
});
/**
* Login and return tokens
*/
app.post("/login", async (req, res) => {
const uri = process.env.MONGO_URI;
const dbName = process.env.MONGO_DB_NAME;
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Find the user in the users collection by email
const user = await collection.findOne({ email: req.body.email });
// No user found
if (!user) {
return res.status(400).json({ message: 'Cannot find user' });
}
// Check if the user's password is valid
const isValidPassword = await bcrypt.compare(req.body.password, user.password);
if (!isValidPassword) {
return res.status(403).json({ message: 'Invalid password' });
}
// Generate tokens for the user
const userData = { name: user.name, email: user.email, role: user.role };
const accessToken = generateAccessToken(userData);
const refreshToken = jwt.sign(userData, process.env.REFRESH_TOKEN_SECRET);
// Save the refresh token
refreshTokens.push(refreshToken);
// Set the access token in an HTTP-only cookie
res.cookie('access_token', accessToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'Strict'
});
// Set the refresh token in another HTTP-only cookie
res.cookie('refresh_token', refreshToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'Strict'
});
// Return success response
return res.status(200).redirect('/');
} catch (error) {
console.error("Login error:", error);
res.status(500).json({ message: 'Internal server error' });
} finally {
await client.close();
}
});
/**
* Logout and destroy the refresh token
*/
app.delete("/logout", async (req, res) => {
// Remove the refresh token from the server's storage
refreshTokens = refreshTokens.filter(token => token !== req.cookies['refresh_token']);
// Clear the cookies (both access and refresh tokens)
res.clearCookie('access_token', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'Strict'
});
res.clearCookie('refresh_token', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'Strict'
});
// Indicate a redirect in the response header
res.set('HX-Redirect', '/login');
// Return success response
res.status(204).json({ message: 'Logout successful' });
});
/**
* Refresh access token
*/
app.post("/token", async (req, res) => {
const refreshToken = req.body.token;
// Check if refresh token exists
if (refreshToken == null) return res.sendStatus(401);
if (!refreshTokens.includes(refreshToken)) return res.sendStatus(403);
// Validate refresh token
jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
const accessToken = generateAccessToken({ name: user.name });
res.json({ accessToken: accessToken });
});
});
/**
* Register Form
*/
app.get("/register", async (req, res) => {
registerPartials();
res.render("core/register");
});
// Register a new user
app.post('/register', async (req, res) => {
const uri = process.env.MONGO_URI;
const dbName = process.env.MONGO_DB_NAME;
const client = new MongoClient(uri);
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const user = {
name: req.body.name,
email: req.body.email,
role: req.body.role,
password: hashedPassword
};
// Connect to MongoDB
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Insert the new user document
const result = await collection.insertOne(user);
if (result.insertedId) {
res.status(201).send({ message: 'User registered successfully' });
} else {
res.status(500).send({ message: 'Failed to register user' });
}
} catch (error) {
console.error("Registration error:", error);
res.status(500).send({ message: 'Internal server error' });
} finally {
await client.close();
}
});
/**
* Get Module Function
* Accept a Get request from the client and call the appropriate module function
* Return the response to the client
*/
app.get('/mod/:moduleName/:command', authenticateToken, async (req, res) => {
const { moduleName, command } = req.params;
try {
// Call the module function and wait for the response
const moduleResponse = await core.mod[moduleName][command]();
// Send the response back to the client
res.send(moduleResponse);
} catch (err) {
console.error('Error calling module command:', err);
res.status(500).send('Error executing module command');
}
});
/**
* Post Module Function
* Accept a POST request from the client and call the appropriate module function passing the data
* Return the response to the client
*/
app.post('/mod/:moduleName/:command', authenticateToken, async (req, res) => {
const { moduleName, command } = req.params;
// Set Data
const data = req.body;
try {
// Call the module function and wait for the response
const moduleResponse = await core.mod[moduleName][command](data);
// Send the response back to the client
res.send(moduleResponse);
} catch (err) {
console.error('Error calling module command:', err);
res.status(500).send('Error executing module command');
}
});
/**
* Support File Uploads
*
* Post Module Function with Multer Middleware for File Upload Support
* Accept a multipart/form-data POST request from the client and call the appropriate module function
* Return the response to the client
*/
app.post('/mod/:moduleName/:command/upload', upload.single('file'), async (req, res) => {
const { moduleName, command } = req.params;
// Set Data
const data = req.body;
data.file = req.file;
try {
// Call the module function and wait for the response
const moduleResponse = await core.mod[moduleName][command](data);
// Send the response back to the client
res.send(moduleResponse);
} catch (err) {
console.error('Error calling module command:', err);
res.status(500).send('Error executing module command');
}
});
/**
* Draw the root view with a module loaded
*/
app.get("/:moduleName/:command", authenticateToken, async (req, res) => {
const { moduleName, command } = req.params;
const data = {...core.coreData, user: req.user, currentModule: moduleName };
registerPartials();
// Call the module function and set the response in the main attribute
if (moduleName && command) {
try {
const moduleResponse = await core.mod[moduleName][command]();
data.main = moduleResponse
} catch (err) {
console.error('Error calling module command:', err);
res.status(500).send('Error executing module command');
}
}
res.render("core/index", data);
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});