-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
238 lines (187 loc) · 6.92 KB
/
server.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
import express from 'express';
import fs from 'fs';
import dotenv from 'dotenv';
import backRouter from './backend/backendRouter.js';
import commiteeRouter from './backend/commiteeRouter.js';
dotenv.config();
const port = process.env.PORT || 3000;
const app = express();
// Serve static files from the 'public' folder
app.use(express.static('public'));
app.use(express.json());
const dataFolderPath = "data/";
export const pathToCommiteeFile = dataFolderPath + "commitee.json";
export const pathToPatetosImages = "public/img/profileImages";
export const pathToPostImages = "public/img/postImages/";
export const pathToPostsFile = dataFolderPath + "posts.json";
export const pathToPatetosFile = dataFolderPath + "patetos.json";
export const pathToCredentialsFile = dataFolderPath + "credentials.json";
const pathToAdminkeysFile = dataFolderPath + "adminKeys.json";
const adminKeysLifeTime = 10 * 24 * 60 * 60 * 1000; // 10 days in milliseconds
// UPLOAD NEW POST
app.use('/api', backRouter)
app.use('/api/commitee', commiteeRouter)
export async function initialize_files(directories, files) {
directories.forEach((path) => {
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
});
files.forEach((path) => {
if (!fs.existsSync(path)) {
fs.writeFileSync(path, JSON.stringify([], null, 2));
}
});
// Create credentials file if it doesn't exist
if (!fs.existsSync(pathToCredentialsFile)) {
fs.writeFileSync(pathToCredentialsFile, JSON.stringify([
{
"name": process.env.MAIN_USERNAME || "Göken",
"password": process.env.MAIN_USER_PASSWORD || "1234",
"id": process.env.MAIN_USER_ID || "1"
}
], null, 2));
}
}
async function initiate_commitee_file() {
if (!fs.existsSync(pathToCommiteeFile)) {
fs.writeFileSync(pathToCommiteeFile, JSON.stringify({
"name": "FikIT",
"logo": "img/logos/fikit23.png",
"established": "2017",
"fallbackProfileImage": "img/logos/fikit.png",
"socialMedia": [
{
"name": "Instagram",
"url": "https://www.instagram.com/fikit_chalmers/",
"logo": "img/logos/instagram.png"
},
{
"name": "wikIT",
"url": "https://wiki.chalmers.it/index.php/FikIT",
"logo": "img/logos/it.svg"
}
],
"contact": [
{
"type": "email",
"value": "[email protected]"
}
]
}, null, 2));
}
}
initialize_files([dataFolderPath, pathToPatetosImages, pathToPostImages], [pathToPostsFile, pathToPatetosFile, pathToAdminkeysFile]);
initiate_commitee_file();
// LOGIN SYSTEM
app.post('/login', (req, res) => {
removeUnvalidAdminKeys();
const username = req.body.username; // Extract username from request body
const password = req.body.password; // Extract password from request body
console.log('Username:', username);
console.log('Password:', password);
if (credentialsIsValid(username, password)) {
let adminKey = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
saveAdminKey(adminKey, username);
console.log('Admin key:', adminKey);
res.status(200).json({ adminKey }); // Send the content back to the client
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
});
app.post('/testAdminKey', (req, res) => {
const adminKey = req.body.adminKey; // Extract admin key from request body
if (isAdminKeyValid(adminKey)) {
res.status(200).json("Adminkey is valid");
} else {
res.status(401).json("Adminkey is not valid");
}
});
function getCredentials() {
let credentials = fs.readFileSync(pathToCredentialsFile);
console.log(credentials);
return JSON.parse(credentials);
}
function getAdminKeys() {
if (fs.existsSync(pathToAdminkeysFile)) {
const adminKeys = fs.readFileSync(pathToAdminkeysFile, 'utf8');
return JSON.parse(adminKeys);
}
else {
throw new Error('Adminkeys file not found');
}
}
function credentialsIsValid(username, pass) {
const userCredentials = getCredentials();
for (const user of userCredentials) {
if (user.name === username && user.password === pass) {
console.log('User:', user.name, "pass:", user.password);
return true;
}
}
return false;
}
export function getUsernameFromAdminKey(adminKey) {
let adminKeys = getAdminKeys();
adminKeys.forEach(key => {
if (key.key === adminKey){
return key.username
}
});
}
function saveAdminKey(adminKey, username) {
const currentDate = new Date().toISOString();
const adminKeyData = { key: adminKey, username: username, date: currentDate };
// Read existing admin keys from file, or create an empty array if the file doesn't exist
let adminKeys = getAdminKeys();
// Add the new admin key data to the array
adminKeys.push(adminKeyData);
// Write the updated admin keys array back to the file
fs.writeFileSync(pathToAdminkeysFile, JSON.stringify(adminKeys, null, 2));
}
export function isAdminKeyValid(adminKey) {
const currentDate = new Date();
const tenDaysAgo = new Date(currentDate.getTime() - (adminKeysLifeTime));
const adminKeys = getAdminKeys();
// Find the admin key in the adminKeys array
const adminKeyData = adminKeys.find(keyData => keyData.key === adminKey);
if (!adminKeyData) {
return false; // Admin key not found
}
// Parse the saved date and compare it with ten days ago
const savedDate = new Date(adminKeyData.date);
return savedDate >= tenDaysAgo;
}
function removeUnvalidAdminKeys() {
const currentDate = new Date();
const tenDaysAgo = new Date(currentDate.getTime() - (adminKeysLifeTime));
let adminKeys = getAdminKeys();
adminKeys = adminKeys.filter(keyData => {
const savedDate = new Date(keyData.date);
return savedDate >= tenDaysAgo;
});
fs.writeFileSync(pathToAdminkeysFile, JSON.stringify(adminKeys, null, 2));
}
backRouter.post('/updateUserCredentials', (req, res) => {
if (!isAdminKeyValid(req.body.adminKey)) return res.status(403).send("Adminkey not valid");
const newUsername = req.body.username;
const newPassword = req.body.password;
let adminKeys = fs.readFileSync(pathToAdminkeysFile);
adminKeys = JSON.parse(adminKeys);
adminKeys.filter(keyData => keyData.key !== req.body.adminKey);
fs.writeFileSync(pathToAdminkeysFile, JSON.stringify(adminKeys, null, 2));
let credentials = fs.readFileSync(pathToCredentialsFile);
credentials = JSON.parse(credentials);
try {
credentials.find(user => user.name === getUsernameFromAdminKey()).password = newPassword;
credentials.find(user => user.name === getUsernameFromAdminKey).username = newUsername;
} catch (error) {
return res.status(404).send("User not found");
}
fs.writeFileSync(pathToCredentialsFile, JSON.stringify(credentials, null, 2));
res.send(200).send("Credentials updated successfully!");
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});