forked from mhajah/projekt_weppo2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
315 lines (261 loc) · 8.73 KB
/
app.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
var http = require('http');
//var authorize = require('./authorize')
//dump database
var express = require('express');
var cookieParser = require('cookie-parser');
var mssql = require('mssql');
var path = require('path');
var database_handling = require('./database_handling');
var app = express();
const crypto = require('crypto');
const { basename } = require('path');
const secret = 'mysecretkey';
const cipher = crypto.createCipher('aes256', secret);
const decipher = crypto.createDecipher('aes256', secret);
app.use( express.static( "./static" ) );
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser('sgs90890s8g90as8rg90as8g9r8a0srg8'));
app.set('view engine', 'ejs');
app.set('views', './views');
//w definicji obslugi sciezki wrzucamy middlewhare authorize i jesli on przepusci zadanie to req.user bedzie wypelniony wartoscia
//jednoczesnie authorize jest straznikiem i jesli nie przepusci żądania, to pójdziemy do endpointa końcowego - login
app.get('/', async (req, res) => {
let productsT;
try {
productsT = await database_handling.pullProductsFromDB();
} catch(e) {
console.error(e);
productsT = [];
}
if(!req.signedCookies.user) {
res.render('guest', { products: productsT });
} else {
res.render('user', { products: productsT });
}
});
app.get('/search/:name', async (req, res) => {
let productsT;
try {
productsT = await database_handling.pullProductsFromDB();
} catch(e) {
console.error(e);
productsT = [];
}
const products_found = productsT.filter(product =>
((product.name).toLowerCase()).includes((req.params.name).toLowerCase()) ||
((product.description).toLowerCase()).includes((req.params.name).toLowerCase()) );
res.render('user', { products: products_found });
});
app.post('/search/', (req, res) => {
var searchValue = req.body.searchVal;
res.redirect(`/search/${searchValue}`);
})
app.get('/cart/add/:name', (req, res) => {
var cookieValue;
if (!req.cookies.cart) {
cookieValue = [req.params.name];
res.cookie('cart', cookieValue);
} else {
cookieValue = req.params.name;
cartValue = req.cookies.cart;
console.log(cookieValue);
console.log(cartValue);
cartValue.push(cookieValue);
res.cookie('cart', cartValue);
}
res.redirect('/');
});
app.get('/cart/remove/:product', (req, res) => {
var newCart = req.cookies.cart.filter( e => req.params.product != e );
res.cookie('cart', newCart);
res.redirect('/cart');
});
app.get('/view_users/remove/:name', async (req,res) => {
let usersT;
try {
usersT = await database_handling.pullUsersFromDB();
} catch(e) {
console.error(e);
usersT = [];
}
database_handling.delete_user_from_datebase(req.params.name);
console.log(req.params.name);
index = usersT.indexOf(req.params.name);
usersT.splice(index,1);
res.redirect('/view_users');
});
app.get('/cart', async (req, res) => {
let productsT;
try {
productsT = await database_handling.pullProductsFromDB();
} catch(e) {
console.error(e);
productsT = [];
}
if (!req.cookies.cart) {
res.render('cart', { products: [] });
//powaiadom delikwenta zen ic nie ma wariacie
} else {
cartValues = req.cookies.cart;
products_found=[]
for (let i=0;i<cartValues.length;i++){
products_found.push(productsT.filter(product => ((product.name).toLowerCase()) == cartValues[i].toLowerCase())[0])
}
res.render('cart', { products: products_found });
}
})
app.get('/profile', authorize, (req, res) => {
res.cookie('user', '', { maxAge: -1 });
res.redirect('/')
});
app.get('/logout', (req, res) => {
res.cookie('user', '', {
maxAge: 0,
overwrite: true,
});
res.redirect('/');
});
app.get('/view_users',authorize, async (req, res) => {
// var answ = async () =>{
// return database_handling.select_users();
// }
//console.log(answ());
var myTab = [];
try {
myTab = await database_handling.select_users();
} catch(e) {
console.error(e);
myTab = [];
}
res.render('view_users', { users: myTab});
})
// strona logowania
//endpoint ktorego zadaniem bedzie wydanie ciastka dla nowego uzytkownika
app.get('/login', (req, res) => {
res.render('login');
});
app.post('/login', async (req, res) => {
let usersT;
try {
usersT = await database_handling.pullUsersFromDB();
} catch(e) {
console.error(e);
usersT = [];
}
var username = req.body.txtUser;
var password = req.body.txtPwd;
var cipher = crypto.createCipher('aes-128-cbc','abcdefghijklmnop')
for(i=0;i<usersT.length;i++){
if(usersT[i].name==username&& usersT[i].password==password){
let encryptedUsername = cipher.update(username, 'utf8', 'hex');
encryptedUsername += cipher.final('hex');
res.cookie('user',encryptedUsername,{signed:true});
var returnUrl = req.query.returnUrl||'/'
res.redirect(returnUrl)
}
};
res.render('login', { message: "Taki uzytkownik nie istnieje!" })
/*
if (username == password) {
// wydanie ciastka
res.cookie('user', username, { signed: true });
// przekierowanie
var returnUrl = req.query.returnUrl;
res.redirect(returnUrl);
} else {
res.render('login', { message: "Zła nazwa logowania lub hasło" }
);
}
*/
});
app.get('/register', (req, res) => {
res.render('register');
});
app.post('/register', (req, res) => {
var username = req.body.txtUser;
var password = req.body.txtPwd;
var repeated_password = req.body.repeattxtPWD;
if(password != repeated_password){
res.render('login', { message: 'Podane haslo jest inne od powtórzonego.'})
}
else{
database_handling.insert_user(username,password,1);
//usersTAB.push({'name': username,'password':password,'perm': 1});
res.redirect('/');
}
});
app.get('/admin', authorize, (req, res) => {
res.render('admin');
});
//SKŁADANIE ZAMÓWIENIA
app.post('/cart', (req, res) => {
if (!req.cookies.cart) {
res.send("Koszyk jest pusty...");
}
var orderAsString = (req.cookies.cart).join(', ');
var amount = req.body.totalPrice;
const encryptedUsername = req.signedCookies.user;
const decipher = crypto.createDecipher('aes256', secret);
let user = decipher.update(encryptedUsername, 'hex', 'utf8');
user += decipher.final('utf8');
database_handling.insert_order(orderAsString, amount, user);
res.clearCookie("cart");
res.redirect('/')
});
app.post('/add_user', (req, res) => {
var name = req.body.name;
var per = req.body.per;
var password = req.body.password
database_handling.insert_user(name,password,per);
res.redirect('/view_users')
});
app.post('/add_product', (req, res) => {
var name = req.body.name;
var description = req.body.description;
var imgLink = req.body.imgLink;
var price = req.body.price;
database_handling.insert_product(name,description,imgLink,price);
res.redirect('/view_users')
});
app.post('/remove_product', (req, res) => {
database_handling.delete_product_from_datebase(req.body.name)
res.redirect('/view_users')
});
http.createServer(app).listen(8080);
console.log('serwer działa, nawiguj do http://localhost:8080');
async function checkpermission(username){
let usersT;
try {
usersT = await database_handling.pullUsersFromDB();
} catch(e) {
console.error(e);
usersT = [];
}
for(i=0;i<usersT.length;i++)
if(usersT[i].name==username)
return usersT[i].perm
return 1;
}
async function authorize(req, res, next) {
if ( req.signedCookies.user ) {
console.log(req.signedCookies.user) //nazwa uzytkownika
if(req.url=="/admin"||"/view_users"){
const encryptedUsername = req.signedCookies.user;
const decipher = crypto.createDecipher('aes-128-cbc','abcdefghijklmnop');
//const decipher = crypto.createDecipher('aes256', secret);//var cipher = crypto.createCipher('aes-128-cbc','abcdefghijklmnop')
let username = decipher.update(encryptedUsername, 'hex', 'utf8');
username += decipher.final('utf8');
var perm = 1;
try {
perm = await checkpermission(username);
} catch (e) {
console.error(e);
}
if(perm!=2)
res.redirect('/')
}
next();
} else {
res.redirect(`/login?returnUrl=${req.url}`);
}
}