forked from Velfoy/Project_web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
390 lines (347 loc) · 12 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
import express from "express";
import bodyParser from "body-parser";
import methodOverride from "method-override";
import sql from "mssql";
import session from "express-session";
const dbConfig = {
server: "LAPTOP-BJSNAIAH",
database: "SVO_DB_PROJECT_FINAL_VERSION",
user: "anhelina",
password: "Hfge!0406",
options: {
encrypt: false,
enableArithAbort: true
}
};
const app = express();
const port = 3000;
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(bodyParser.json());
// Konfiguracja sesji
app.use(session({
secret: 'your_secret_key', // Użyj silnego klucza sekretu
resave: false,
saveUninitialized: false,
cookie: { secure: false } // Ustaw na true, jeśli używasz HTTPS
}));
const posts_index = [
{href: '/', id:'home_id',class:'active',text:'Home'},
{href: '/posts', id:'posts_id',class:'disable',text:'Posts' },
{href: '/plan', id:'plan_id',class:'disable',text:'Plan' },
{href: '/map', id:'map_id',class:'disable',text:'Map'},
]
const posts_posts = [
{href: '/', id:'home_id',class:'disable',text:'Home'},
{href: '/posts', id:'posts_id',class:'active',text:'Posts' },
{href: '/plan', id:'plan_id',class:'disable',text:'Plan' },
{href: '/map', id:'map_id',class:'disable',text:'Map'},
]
const posts_plan = [
{href: '/', id:'home_id',class:'disable',text:'Home'},
{href: '/posts', id:'posts_id',class:'disable',text:'Posts' },
{href: '/plan', id:'plan_id',class:'active',text:'Plan' },
{href: '/map', id:'map_id',class:'disable',text:'Map'},
]
const posts_map = [
{href: '/', id:'home_id',class:'disable',text:'Home'},
{href: '/posts', id:'posts_id',class:'disable',text:'Posts' },
{href: '/plan', id:'plan_id',class:'disable',text:'Plan' },
{href: '/map', id:'map_id',class:'active',text:'Map'},
]
const posts_rodo = [
{href: '/', id:'home_id',class:'disable',text:'Home'},
{href: '/posts', id:'posts_id',class:'disable',text:'Posts' },
{href: '/plan', id:'plan_id',class:'disable',text:'Plan' },
{href: '/map', id:'map_id',class:'disable',text:'Map'},
]
app.get("/", (req, res) => {
res.render("index.ejs", {
links: posts_index,
userID: req.session.userID || null
});
});
// app.get("/login", (req, res) => {
// res.render("login.ejs", {
// links: posts_index,
// userID: req.session.userID || null
// });
// });
app.post("/login", async (req, res) => {
const { uname, psw } = req.body;
req.session.userID = null;
try {
let pool = await sql.connect(dbConfig);
let result = await pool.request()
.input('UserUniversityID', sql.Int, uname)
.input('UserPassword', sql.NVarChar(255), psw)
.output('Result', sql.Int)
.execute('UserLogInValidation');
const loginResult = result.output.Result;
let message;
if (loginResult === 0) {
req.session.userID = uname; // Store the user ID in the session
message = "Login Successful";
} else if (loginResult === 1) {
message = "User does not exist";
} else if (loginResult === 2) {
message = "Incorrect password";
} else {
message = "Unexpected result";
}
res.send(`
<script>
alert("${message}");
window.location.href = "/";
</script>
`);
} catch (err) {
res.send(`
<script>
alert("Failed to log in: invalid id or password");
window.location.href = "/";
</script>
`);
} finally {
sql.close();
}
});
let posts=[];
app.get("/posts", async (req, res) => {
try {
if(req.session.userID == null){
// res.redirect('/');
//logiin();
}
let pool = await sql.connect(dbConfig);
let result = await pool.request().execute('GetAllPosts');
posts = result.recordset;
res.render("posts.ejs", {
links: posts_posts,
posts: posts,
userID: req.session.userID || null
});
} catch (err) {
res.status(500).send("Failed to load posts: " + err.message);
} finally {
sql.close();
}
});
app.get("/privacy-policy", (req, res) => {
res.render("rodo.ejs", {
links: posts_rodo,
userID: req.session.userID || null
});
});
app.post("/submit", async (req,res)=>{
const { postTitle, content } = req.body;
const userID = req.session.userID;
const date = new Date();
if (!userID) {
return res.status(401).send("Unauthorized: User not logged in.");
}
try {
let pool = await sql.connect(dbConfig);
const result = await pool.request()
.input('UserID', sql.Int, userID)
.input('Title', sql.NVarChar(50), postTitle)
.input('Content', sql.NVarChar(1000), content)
.input('Date', sql.DateTimeOffset, date)
.output('Result', sql.Int)
.execute('AddPost');
const resultCode = result.output.Result;
if (resultCode === 0) {
res.redirect("/posts");
} else if (resultCode === 2) {
res.status(400).send("Unsafe input detected.");
} else {
res.status(500).send("Failed to submit post.");
}
} catch (err) {
res.status(500).send("Failed to submit post: " + err.message);
} finally {
/*let result = await pool.request().execute('GetAllPosts');
posts = result.recordset;
res.render("posts.ejs", {
links: posts_index,
posts: posts,
});*/
sql.close();
}
});
app.patch('/comment/:id', async (req, res) => {
const { id } = req.params;
const { updatedTitle, updatedComment } = req.body;
const userID = req.session.userID;
const date = new Date();
if (!userID) {
return res.status(401).send("Unauthorized: User not logged in.");
}
try {
let pool = await sql.connect(dbConfig);
const result = await pool.request()
.input('PostID', sql.Int, id)
.input('UserID', sql.Int, userID)
.input('Title', sql.NVarChar(100), updatedTitle)
.input('Content', sql.NVarChar(1000), updatedComment)
.input('Date', sql.DateTimeOffset, date)
.output('Result', sql.Int)
.execute('UpdatePost');
const resultCode = result.output.Result;
if (resultCode === 0) {
res.redirect("/posts");
} else if (resultCode === 2) {
res.status(400).send("Unsafe input detected.");
} else if (resultCode === 1) {
res.status(404).send("Post not found or you are not the author.");
} else {
res.status(500).send("Failed to update post.");
}
} catch (err) {
res.status(500).send("Failed to update post: " + err.message);
} finally {
sql.close();
}
});
app.delete('/comment/:id', async (req, res) => {
const { id } = req.params;
const userID = req.session.userID;
if (!userID) {
return res.status(401).send("Unauthorized: User not logged in.");
}
try {
let pool = await sql.connect(dbConfig);
const result = await pool.request()
.input('PostID', sql.Int, id)
.input('UserID', sql.Int, userID)
.output('Result', sql.Int)
.execute('DeletePost');
const resultCode = result.output.Result;
if (resultCode === 0) {
res.redirect("/posts");
} else if (resultCode === 1) {
res.status(404).send("Post not found or you are not the author.");
} else {
res.status(500).send("Failed to delete post.");
}
} catch (err) {
res.status(500).send("Failed to delete post: " + err.message);
} finally {
sql.close();
}
});
app.get("/plan", (req, res) => {
res.render("plan.ejs", {
links: posts_plan,
userID: req.session.userID || null
});
});
app.get("/map", (req, res) => {
res.render("map.ejs", {
links: posts_map,
userID: req.session.userID || null
});
});
// here handling login procedure
// const sql = require('mssql');
// registration proces handling
app.post("/register", async (req, res) => {
const { UserUniversityID, UserFirstName, UserLastName, UserPassword } = req.body;
let pool;
try {
pool = await sql.connect(dbConfig); // Connect to the database
let result = await pool.request()
.input("UserUniversityID", sql.Int, UserUniversityID)
.input("UserFirstName", sql.NVarChar(30), UserFirstName)
.input("UserLastName", sql.NVarChar(30), UserLastName)
.input("UserPassword", sql.NVarChar(255), UserPassword)
.output("Result", sql.Int)
.execute("UserRegistration"); // Execute the stored procedure
const registrationResult = result.output.Result;
let message;
if (registrationResult === 0) {
message = "Registration successful!";
//res.send("Registration successful!");
} else if (registrationResult === 1) {
message = "User already exists";
// res.send("User already exists");
} else if (registrationResult === 2) {
message ="Registration failed";
// res.send("Registration failed");
} else {
res.send("Unexpected error occurred");
}
res.send(`
<script>
alert("${message}");
window.location.href = "/";
</script>
`);
} catch (err) {
res.send(`
<script>
alert("Failed to log in: invalid id or password");
window.location.href = "/";
</script>
`);
} finally {
if (pool) {
pool.close(); // Close the database connection
}
}
});
//adding events to database
async function addEvent(userID, calendarID, date, type, title, description) {
try {
let pool = await sql.connect(dbConfig);
let result = await pool.request()
.input('UserID', sql.Int, userID)
.input('CalendarID', sql.Int, calendarID)
.input('Date', sql.DateTimeOffset, date)
.input('Type', sql.Bit, type)
.input('Title', sql.NVarChar(30), title)
.input('Description', sql.NVarChar(100), description)
.execute('AddEvent');
console.log(result.recordset[0].Message);
} catch (err) {
console.error('SQL error', err);
} finally {
sql.close();
}
}
app.get("/coordinates", async (req, res) => {
const { name } = req.query;
try {
let pool = await sql.connect(dbConfig);
let result = await pool.request()
.input('Name', sql.NVarChar(255), name)
.output('Latitude', sql.Float)
.output('Longitude', sql.Float)
.execute('GetCoordinates');
const latitude = result.output.Latitude;
const longitude = result.output.Longitude;
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`); // Debugging
res.status(200).json({ Latitude: latitude, Longitude: longitude });
} catch (err) {
console.error("Error fetching coordinates:", err);
res.status(500).json({ error: "Failed to retrieve coordinates" });
} finally {
sql.close();
}
});
app.get("/building-names", async (req, res) => {
try {
let pool = await sql.connect(dbConfig);
let result = await pool.request().query('SELECT Name FROM Coordinates');
res.status(200).json(result.recordset);
} catch (err) {
console.error("Error fetching building names:", err);
res.status(500).json({ error: "Failed to retrieve building names" });
} finally {
sql.close();
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});