-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
221 lines (167 loc) · 6.1 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
require('dotenv').config();
const fs = require("fs");
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const mongoose = require('mongoose');
const https = require('https');
const bodyParser = require('body-parser');
const helper = new(require('./functions/helper.function.js'));
const userFunction = new(require('./functions/user.function.js'));
const Role = require('./models/roles.model.js');
const winston = require('winston');
const { createLogger, format, transports} = winston;
const { combine, label, printf } = format;
const DailyRotateFile = require('winston-daily-rotate-file');
const MESSAGE = require('./textDB/messages.text')[process.env.LANGUAGE];
// const fileUpload = require('express-fileupload');
// Use the express-fileupload middleware
// app.use(fileUpload());
// Global object to store role IDs by role name
// userFunction.updateUserRank("rik", "Administrator")
// userFunction.incrementField("rik", "comments_count", 1)
// userFunction.getInfo("rik")
// userFunction.areFriends("65fab62d10ca366b23aa9a0d", "65fab62d10ca366b23aa9a0d").then(data => {
// console.log(data);
// })
// userFunction.getUserRole("rik").then(data => {
// console.log(data);
// })
global.roles = {};
// Function to populate the global roles object with role IDs
async function populateRolesObject() {
try {
// Fetch all roles from the database
const allRoles = await Role.find();
// Populate the global roles object
for (let i = 0; i < allRoles.length; i++) {
const role = allRoles[i];
global.roles[role.name] = role._id.toString();
}
console.log(global.roles);
} catch (error) {
console.error("Error populating global roles object:", error);
}
}
populateRolesObject()
// {
// Administrator: '65f1b5ed1503fb603012b964',
// Moderator: '65f1b616749e0190cea2e4f8',
// User: '65fa90d19b18b0bcf6c8b788'
// }
// Middleware to parse URL-encoded bodies
app.use(express.urlencoded({ extended: true }));
// Stel de maximale verzoekgrootte in op 10 MB
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ limit: '10mb', extended: true }));
app.use(cookieParser());
app.use(require('./middleware/sanitize.middleware'))
// app.use(require('./middleware/logger.middleware'))
app.use(require('./middleware/mobile.middleware')) // req.isMobile - use anywhere to check if user is using a phone
// Define log format
const logFormat = printf(({ level, message, label }) => {
const now = new Date();
const formattedDate = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')} - ${now.getDate().toString().padStart(2, '0')}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getFullYear()}`;
return `[${formattedDate}] ${message}`;
});
// Create Winston logger
const logger = createLogger({
format: combine( label({ label: 'WMR' }), logFormat),
transports: [
// Console transport
new transports.Console({
format: combine(
format.colorize(),
logFormat
)
}),
// DailyRotateFile transport
new DailyRotateFile({
filename: 'logs/%DATE%.log',
datePattern: 'DD-MM-YYYY',
maxSize: '20m',
maxFiles: '31d'
})
]
});
// Middleware to log requests
app.use((req, res, next) => {
try {
// URL Decoding for logging
const URL = decodeURIComponent(req.originalUrl);
let loggerText = `${req.method} ${URL}`;
if (req.method === 'POST' && req.body) {
loggerText += `\n\t\t Request Body: ${JSON.stringify(req.body)}`;
}
logger.info(loggerText);
next();
} catch (error) {
logger.error("Error logging request:", error);
}
});
// Set headers for CORS
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Max-Age', 600); // remove later
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT');
res.setHeader('Access-Control-Allow-Headers', 'Authorization, X-Requested-With, Content-Type, Accept');
next();
});
app.use(express.static(__dirname + '/public'));
app.disable('x-powered-by');
fs.readdirSync('./routes').forEach(file => {
console.log(`Loading in ./routes/${file}/${file}.controller.js`);
app.use(`/${file}/`, require(`./routes/${file}/${file}.controller`));
});
app.get("/api", (req, res) => {
const sortedRoutes = [...urls].sort((a, b) => {
// Extract path prefixes
const prefixA = a.split('/')[1];
const prefixB = b.split('/')[1];
// Compare path prefixes first
const prefixComparison = prefixA.localeCompare(prefixB);
if (prefixComparison !== 0) return prefixComparison
// If path prefixes are the same, compare full routes
return a.localeCompare(b);
});
res.json({ routes: sortedRoutes, success: true});
});
const SSL = {
key: fs.readFileSync('./certificates/ssl_private_key.key'),
cert: fs.readFileSync('./certificates/ssl_certificate.crt')
};
const server = https.createServer(SSL, app);
server.listen(process.env.PORT, () => console.log(MESSAGE.serverRunningPort(process.env.PORT)));
mongoose.connect(process.env.MONGO_URL);
mongoose.connection.on('connected', () => console.log(MESSAGE.serverConnected));
var urls = new Set()
function print(path, layer) {
if (layer.route) {
layer.route.stack.forEach(print.bind(null, path.concat(split(layer.route.path))))
} else if (layer.name === 'router' && layer.handle.stack) {
layer.handle.stack.forEach(print.bind(null, path.concat(split(layer.regexp))))
} else if (layer.method) {
let url = layer.method.toUpperCase() + " /" + path.concat(split(layer.regexp)).filter(Boolean).join('/')
urls.add(url)
}
}
function split(thing) {
if (typeof thing === 'string') {
return thing.split('/')
} else {
var match = thing.toString()
.replace('\\/?', '')
.replace('(?=\\/|$)', '$')
.match(/^\/\^((?:\\[.*+?^${}()|[\]\\\/]|[^.*+?^${}()|[\]\\\/])*)\$\//)
return match ? match[1].replace(/\\(.)/g, '$1').split('/') : '<complex:' + thing.toString() + '>'
}
}
app._router.stack.forEach(print.bind(null, []))
// print out all of the possible
urls.forEach(url => {
console.log(url);
})
// Error handler
app.get("*", (req, res, next) => {
res.status(212).json({ message: MESSAGE.URLNotFound, success: false });
});