-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
395 lines (345 loc) · 13.2 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
//Imports
const express = require("express");
const app = express();
const mysql = require('mysql2/promise');
const path = require("node:path");
const fs = require("node:fs");
app.use(express.urlencoded({extended: true}));
app.use(express.json());
let currentUser = null;
//Static files
app.use("/images", express.static(path.resolve(__dirname, "./public/images")));
app.use("/scripts", express.static(path.resolve(__dirname, "./public/scripts")));
app.use("/styles", express.static(path.resolve(__dirname, "./public/styles")));
//Functions
/*Pages*/
app.get("/", (req, res) => {
res.sendFile(path.resolve(__dirname, "./app/html/index.html"));
});
app.get("/Community", (req, res) => {
res.sendFile(path.resolve(__dirname, "./app/html/community.html"));
});
app.get("/Post", (req, res) => {
res.sendFile(path.resolve(__dirname, "./app/html/post.html"));
});
app.get("/CreatePost", (req, res) => {
res.sendFile(path.resolve(__dirname, "./app/html/createPost.html"));
});
app.get("/Construction", (req, res) => {
res.sendFile(path.resolve(__dirname, "./app/html/construction.html"));
});
// app.get("/about", (req, res) => {
// res.sendFile(path.resolve(__dirname, "./app/html/about.html"));
// });
app.get("/login", (req, res) => {
let filePath = currentUser ? "./app/html/profile.html" : "./app/html/login.html";
res.sendFile(path.resolve(__dirname, filePath));
});
app.get("/profile", (req, res) => {
let filePath = currentUser ? "./app/html/profile.html" : "./app/html/login.html";
res.sendFile(path.resolve(__dirname, filePath));
});
/*Snippets of HTML*/
app.get("/get-header", (req, res) => {
res.sendFile(path.resolve(__dirname, "./app/data/header.html"));
});
app.get("/get-navbar", (req, res) => {
res.sendFile(path.resolve(__dirname, "./app/data/navbar.html"));
});
app.get("/get-footer", (req, res) => {
res.sendFile(path.resolve(__dirname, "./app/data/footer.html"));
});
/*construction.html
* */
/*Snippets of HTML*/
app.get("/get-constructionList", (req, res) => {
res.sendFile(path.resolve(__dirname, "./app/data/constructionList.html"));
});
app.get("/get-constructionList-data", (req, res) => {
res.sendFile(path.resolve(__dirname, "./app/data/constructionList_data.json"));
});
/*Interactions*/
app.get("/languages", (req, res) => {
const languageDir = path.resolve(__dirname, "./app/data/language");
fs.readdir(languageDir, (err, files) => {
if (err) {
console.error("Could not list the directory.", err);
res.status(500).send("Server error when listing languages");
return;
}
const languages = files.map(file => {
const code = file.split(".")[0];
const name = code; // 简单示例,直接使用code作为显示名称
return {code, name};
});
res.json(languages);
});
});
app.get("/languages/:lang", (req, res) => {
const lang = req.params.lang;
const languageFilePath = path.resolve(__dirname, `./app/data/language/${lang}.json`);
if (fs.existsSync(languageFilePath)) {
res.sendFile(languageFilePath);
} else {
res.status(404).send({error: "Language file not found."});
}
});
app.post("/add-construction", (req, res) => {
const newBuilding = req.body;
const filePath = path.resolve(__dirname, "./app/data/constructionList_data.json");
fs.readFile(filePath, (err, data) => {
if (err) {
console.error("Error reading construction list data:", err);
return res.status(500).send("Error reading construction data");
}
const constructionData = JSON.parse(data.toString());
constructionData.buildings.push(newBuilding);
fs.writeFile(filePath, JSON.stringify(constructionData, null, 2), (err) => {
if (err) {
console.error("Error writing construction list data:", err);
return res.status(500).send("Error updating construction data");
}
res.status(200).send("Construction added successfully");
});
});
});
/*Database*/
/**
* Creates a new connection to the MySQL database with the specified configuration.
*
* @return {Promise<Connection>} A Promise that resolves with the MySQL Connection object.
*/
async function createConnection() {
return mysql.createConnection({
host: "localhost", user: "root", password: "Xjr@66773738", database: "assignment6"
});
}
/**
* Handles the login form submission and redirects to the profile page if the credentials are valid.
*/
app.post('/user-login', async (req, res) => {
const {username, password} = req.body;
const connection = await createConnection();
const [rows] = await connection.execute('SELECT * FROM a01354731_user WHERE user_name = ? AND password = ?', [username, password]);
if (rows.length > 0) {
currentUser = rows[0];
res.redirect('/profile');
} else {
res.send(`
<p>Username or password is incorrect. Please try again.</p>
<a href="/login">Back to Log in</a>
`);
}
});
/**
* Handles the registration form submission
* and redirects to the login page if the registration is successful.
*/
app.post('/user-register', async (req, res) => {
const {email, username, password, confirmPassword} = req.body;
if (password !== confirmPassword) {
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<title>Passwords Do Not Match</title>
<script type="text/javascript">
alert("Passwords do not match. Please try again.");
window.location.href = '/login';
</script>
</head>
<body>
</body>
</html>
`);
return;
}
try {
const connection = await createConnection();
const [users] = await connection.execute('SELECT * FROM a01354731_user WHERE email = ? OR user_name = ?', [email, username]);
if (users.length > 0) {
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<title>Email or Username Already Exists</title>
<script type="text/javascript">
alert("Email or username already exists. Please login or try again .");
window.location.href = '/login';
</script>
</head>
<body>
</body>
</html>
`);
return;
}
await connection.execute('INSERT INTO a01354731_user (email, user_name, password) VALUES (?, ?, ?)', [email, username, password]);
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<title>Registration Successful</title>
<script type="text/javascript">
alert("Registration successful! Redirecting to login page.");
window.location.href = '/login';
</script>
</head>
<body>
</body>
</html>
`);
} catch (error) {
console.error("Database operation error:", error);
res.status(500).send('An error occurred.');
}
});
/*
* Function to edit profile
* */
app.post('/update-profile', async (req, res) => {
if (!currentUser) {
return res.status(401).json({success: false, message: "User not logged in"});
}
const {username, email, firstName, lastName, oldPassword, newPassword} = req.body;
try {
const connection = await createConnection();
let updates = [];
let params = [];
if (username && username !== currentUser.user_name) {
const [userCheck] = await connection.execute('SELECT * FROM a01354731_user WHERE user_name = ?', [username]);
if (userCheck.length > 0) {
return res.json({success: false, message: "Username is already taken."});
} else {
updates.push("user_name = ?");
params.push(username);
}
}
if (email && email.trim()) {
updates.push("email = ?");
params.push(email.trim());
}
if (firstName && firstName.trim()) {
updates.push("first_name = ?");
params.push(firstName.trim());
}
if (lastName && lastName.trim()) {
updates.push("last_name = ?");
params.push(lastName.trim());
}
if (oldPassword && newPassword && oldPassword.trim() && newPassword.trim()) {
const [user] = await connection.execute('SELECT * FROM a01354731_user WHERE user_name = ? AND password = ?', [currentUser.user_name, oldPassword.trim()]);
if (user.length === 0) {
return res.json({success: false, message: "Old password is incorrect"});
} else {
updates.push("password = ?");
params.push(newPassword.trim());
}
}
if (updates.length > 0) {
params.push(currentUser.user_name);
const query = `UPDATE a01354731_user
SET ${updates.join(", ")}
WHERE user_name = ?`;
await connection.execute(query, params);
const [updatedRows] = await connection.execute('SELECT * FROM a01354731_user WHERE user_name = ?', [currentUser.user_name]);
if (updatedRows.length > 0) {
currentUser = updatedRows[0];
}
res.json({success: true, message: "Profile updated successfully"});
} else {
res.json({success: false, message: "No changes were made"});
}
} catch (error) {
console.error("Database operation error:", error);
res.status(500).json({success: false, message: "An error occurred while updating profile"});
}
});
/**
* Function to get current user information
*/
app.get('/get-current-user', async (req, res) => {
if (!currentUser) {
return res.status(401).send("User not logged in");
}
try {
const connection = await createConnection();
const [rows] = await connection.execute('SELECT * FROM a01354731_user WHERE user_name = ?', [currentUser.user_name]);
if (rows.length > 0) {
const userInfo = {
username: rows[0].user_name,
email: rows[0].email,
firstName: rows[0].first_name || '',
lastName: rows[0].last_name || '',
};
res.json(userInfo);
} else {
res.status(404).send("User not found");
}
} catch (error) {
console.error("Database operation error:", error);
res.status(500).send("An error occurred while fetching user info");
}
});
/**
* Function to add a new post.
*/
app.post('/post-timeline', async (req, res) => {
if (!currentUser) {
return res.status(401).json({success: false, message: "User not logged in"});
}
const {postTitle, postText} = req.body;
try {
const connection = await createConnection();
await connection.execute('INSERT INTO a01354731_user_timeline (user_id, post_title, post_text, post_date, post_time, post_views) VALUES (?, ?, ?, CURDATE(), CURTIME(), 0)', [currentUser.id, postTitle, postText]);
res.json({success: true, message: "Post successfully added"});
} catch (error) {
console.error("Database operation error:", error);
res.status(500).json({success: false, message: "Failed to add post"});
}
});
/**
* Function to get all posts.
*/
app.get('/get-posts', async (req, res) => {
try {
const connection = await createConnection();
const [posts] = await connection.execute(`
SELECT ut.*, u.user_name
FROM a01354731_user_timeline ut
JOIN a01354731_user u ON ut.user_id = u.id
ORDER BY ut.post_date DESC, ut.post_time DESC
`);
res.json(posts);
} catch (error) {
console.error("Error fetching posts:", error);
res.status(500).send("Error fetching posts from the database.");
}
});
/**
* Function to get post-details.
*/
app.get('/get-post-details', async (req, res) => {
const postId = req.query.postId;
if (!postId) {
return res.status(400).send("Post ID is required");
}
try {
const connection = await createConnection();
await connection.execute('UPDATE a01354731_user_timeline SET post_views = post_views + 1 WHERE id = ?', [postId]);
const [postDetails] = await connection.execute('SELECT a01354731_user_timeline.*, a01354731_user.user_name FROM a01354731_user_timeline JOIN a01354731_user ON a01354731_user_timeline.user_id = a01354731_user.id WHERE a01354731_user_timeline.id = ?', [postId]);
if (postDetails.length > 0) {
res.json(postDetails[0]);
} else {
res.status(404).send("Post not found");
}
} catch (error) {
console.error("Error fetching post details:", error);
res.status(500).send("Error fetching post details from the database.");
}
});
/**
* Start the server.
*/
app.listen(8000);
console.log("Server running on port 8000");