-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
515 lines (436 loc) · 19.1 KB
/
app.py
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
import bcrypt
import os
import psycopg2
import psycopg2.extras
import re
from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.secret_key = 'marksuuuu' # Set a secret key for session management
# Database configuration
db_config = {
'host': 'localhost',
'port': '5432',
'dbname': 'inventory_system_flask',
'user': 'flask_user',
'password': '-clear1125'
}
# Flask-Login setup
login_manager = LoginManager(app)
login_manager.login_view = 'login'
class User(UserMixin):
def __init__(self, user_id, username, firstname, lastname, password, role, profile, email, itemInCartCount):
self.id = user_id
self.username = username
self.firstname = firstname
self.lastname = lastname
self.password = password
self.role = role
self.profile = profile
self.email = email
self.itemInCartCount = itemInCartCount
@login_manager.user_loader
def load_user(user_id):
# Load user from the database based on the user ID
with psycopg2.connect(**db_config) as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM public.login_details_tbl WHERE id = %s", (user_id,))
user_data = cur.fetchone()
if user_data:
user_id, username, firstname, lastname, password, role, profile, email = user_data
cur.execute("SELECT count(*) FROM public.cart_details_tbl WHERE userid = %s", (user_id,))
cart_data = cur.fetchone()
itemInCartCount = cart_data[0] if cart_data else 0
return User(user_id, username, firstname, lastname, password, role, profile, email, itemInCartCount)
return None
def allowed_file(filename):
# Define a list of allowed file extensions
allowed_extensions = {'png', 'jpg', 'jpeg', 'gif', 'jfif'}
# Check if the file extension is in the allowed list
return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions
@app.route('/getUsers')
def getUsers():
with psycopg2.connect(**db_config) as conn:
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("SELECT * FROM public.login_details_tbl")
user_datas = cursor.fetchall()
userData = []
for data in user_datas:
userData.append({
'id': data[0],
'username': data[1],
'firstname': data[2],
'lastname': data[3],
'user_role': data[5],
'user_pfp': data[6],
'email': data[7]
})
cursor.close()
return jsonify({'data': userData})
@app.route('/inventory')
def get_inventory():
with psycopg2.connect(**db_config) as conn:
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("SELECT * FROM public.product_details_tbl")
rows = cursor.fetchall()
category_data = []
for row in rows:
category_data.append({
'id': row[0],
'productName': row[1],
'productCount': row[2],
'fileUploaded': row[3],
'productPrice': row[4],
'productDescription': row[5],
'productTypes': row[6],
})
cursor.close()
return jsonify({'data': category_data})
@app.route('/register', methods=['POST'])
def register_insert():
try:
username = request.form['personUsername']
firstname = request.form['firstname']
lastname = request.form['lastname']
email = request.form['email']
password = request.form['password']
uploaded_img = request.files['fileInput']
role = request.form['role']
# Check if all form fields are provided
if not (username and firstname and lastname and email and password and uploaded_img and role):
return jsonify({'error': 'Missing form fields'}), 400
# Generate a valid salt
salt = bcrypt.gensalt().decode('utf-8')
# Hash the password with the salt
hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt.encode('utf-8')).decode('utf-8')
if uploaded_img.filename == '' or not allowed_file(uploaded_img.filename):
return jsonify({'error': 'Invalid file format. Only image files are allowed.'}), 400
filename = secure_filename(uploaded_img.filename)
file_path = os.path.join('static/assets/img', filename).replace("\\", "/")
uploaded_img.save(file_path)
with psycopg2.connect(**db_config) as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO public.login_details_tbl (username, firstname, lastname, password, user_role, profile, email) VALUES (%s, %s, %s, %s, %s, %s, %s)",
(username, firstname, lastname, hashed_password, role, file_path, email))
conn.commit()
msg = "INSERT SUCCESS"
return jsonify({'message': msg}), 200
except KeyError:
return jsonify({'error': 'Invalid form data'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/updateUserData', methods=['POST'])
def update_user_data():
input_username = request.form['inputUsername']
input_first_name = request.form['inputFirstName']
input_last_name = request.form['inputLastName']
input_email_address = request.form['inputEmailAddress']
password = request.form['passwordID'] # New password entered by the user
user_id = request.form['userId']
if 'profileImg' in request.files:
profile_img = request.files['profileImg']
if profile_img.filename == '':
msg = 'No file selected.'
elif profile_img and allowed_file(profile_img.filename):
filename = secure_filename(profile_img.filename)
file_path = os.path.join('static/assets/img', filename).replace("\\", "/")
profile_img.save(file_path)
with psycopg2.connect(**db_config) as conn:
with conn.cursor() as cur:
if password:
# Generate a valid salt
salt = bcrypt.gensalt().decode('utf-8')
# Hash the new password with the salt
hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt.encode('utf-8')).decode('utf-8')
cur.execute(
f"UPDATE public.login_details_tbl SET username='{input_username}', firstname='{input_first_name}', lastname='{input_last_name}', password='{hashed_password}', profile='{file_path}', email='{input_email_address}' WHERE id = {user_id};")
else:
cur.execute(
f"UPDATE public.login_details_tbl SET username='{input_username}', firstname='{input_first_name}', lastname='{input_last_name}', profile='{file_path}', email='{input_email_address}' WHERE id = {user_id};")
conn.commit() # commit the transaction
msg = 'UPDATE SUCCESS'
else:
msg = 'Invalid file format. Only image files are allowed.'
else:
msg = False
return jsonify(msg)
@app.route('/process-csv', methods=['POST'])
def process_csv():
file = request.files['file']
lines = file.read().decode('utf-8').split('\n')
# Process the CSV data and insert into the database table
for line in lines:
columns = line.split(',')
if len(columns) != 6:
# Handle the case where the number of columns is incorrect
continue # Skip this row and move to the next
productName = columns[0]
productCount = columns[1]
file_path = columns[2]
productPrice = columns[3]
productDescription = columns[4]
productTypes = columns[5]
# Validate productPrice as an integer
if not productPrice.isdigit():
# Handle the case where productPrice is not a valid integer
productPrice = 0 # Assign a default value or handle it as appropriate
# Execute the SQL query to insert data into the table
with psycopg2.connect(**db_config) as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO public.product_details_tbl (productname, productcount, fileuploaded, productprice, productdescription, producttypes) VALUES (%s, %s, %s, %s, %s, %s)",
(productName, productCount, file_path, int(productPrice), productDescription, productTypes))
conn.commit() # commit the transaction
msg = "INSERT SUCCESS"
return jsonify(msg)
@app.route('/deleteProducts', methods=['POST'])
def delete_products():
data = request.get_json()
id = data.get('id')
with psycopg2.connect(**db_config) as conn:
with conn.cursor() as cur:
cur.execute(f'DELETE FROM public.product_details_tbl WHERE id = {id}')
conn.commit()
msg = 'DELETE SUCCESS'
return jsonify({'message': msg})
@app.route('/upload', methods=['POST'])
def upload_insert():
productName = request.form['productName']
productCount = request.form['productCount']
fileUploaded = request.files['fileUploaded']
productPrice = request.form['productPrice']
productDescription = request.form['productDescription']
productTypes = request.form['productTypes']
# Check if the product already exists in the database
with psycopg2.connect(**db_config) as conn:
with conn.cursor() as cur:
cur.execute("SELECT COUNT(*) FROM public.product_details_tbl WHERE productname = %s", (productName,))
count = cur.fetchone()[0]
if count > 0:
msg = "Product already exists in the database."
return jsonify(msg)
if fileUploaded and allowed_file(fileUploaded.filename):
filename = secure_filename(fileUploaded.filename)
file_path = os.path.join('static/assets/img/products', filename).replace("\\", "/")
fileUploaded.save(file_path)
with psycopg2.connect(**db_config) as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO public.product_details_tbl (productname, productcount, fileuploaded, productprice, productdescription, producttypes) VALUES (%s, %s, %s, %s, %s, %s)",
(productName, productCount, file_path, productPrice, productDescription, productTypes))
conn.commit() # commit the transaction
msg = "INSERT SUCCESS"
else:
msg = "Invalid file format. Only image files are allowed."
return jsonify(msg)
@app.route('/showCart', methods=['POST'])
def showCart():
data = request.get_json()
id = data.get('userId')
with psycopg2.connect(**db_config) as conn:
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(f"""
SELECT
cdt.id as ID,
cdt.productprice as PRODPRICE,
pdt.productname as PRODNAME,
cdt.productcount as PRODCOUNT,
cdt.fileuploaded as FILEUP,
pdt.productdescription as PRODDESC
FROM
public.product_details_tbl as pdt
INNER JOIN
public.cart_details_tbl as cdt
ON
cdt.itemid = pdt.id
LEFT JOIN
public.login_details_tbl as ldt ON ldt.id = cdt.userid
WHERE ldt.id = {id}
""")
rows = cursor.fetchall()
category_data = []
for row in rows:
category_data.append({
'ID': row[0],
'PRODPRICE': row[1],
'PRODNAME': row[2],
'PRODCOUNT': row[3],
'FILEUP': row[4],
'PRODDESC': row[5]
})
cursor.close()
return jsonify({'data': category_data})
@app.route('/addtocart', methods=['POST'])
def add_to_cart():
user_id = request.form['userId']
item_id = request.form['data_id']
prodCount = request.form['prodCount']
itemImg = request.form['itemImg']
productPrice = request.form['productPrice']
productName = request.form['productName']
itemImgPath = '../static/assets/img/products/' + itemImg
# Remove "Price: 0" using regex
productPrice = re.sub(r'Price: ', '', productPrice)
print(productPrice)
with psycopg2.connect(**db_config) as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO public.cart_details_tbl (itemid, userid, productname, productcount, fileuploaded, productprice) VALUES (%s, %s, %s, %s, %s, %s)",
(int(item_id), int(user_id), productName, int(prodCount), itemImgPath, int(productPrice)))
conn.commit() # commit the transaction
msg = "INSERT SUCCESS"
return jsonify(msg)
@app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
with psycopg2.connect(**db_config) as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM public.login_details_tbl WHERE username = %s", (username,))
user_data = cur.fetchone()
if user_data:
stored_password = user_data[4] # Get the hashed password from the database
if bcrypt.checkpw(password.encode('utf-8'), stored_password.encode('utf-8')):
user_id, username, firstname, lastname, password, role, profile, email = user_data
itemInCartCount = 0 # Assign a value to itemInCartCount
user = User(user_id, username, firstname, lastname, password, role, profile, email, itemInCartCount)
login_user(user)
if role == 1:
return redirect(url_for('admin'))
else:
return redirect(url_for('overview'))
else:
return jsonify("Invalid username or password")
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user() # Log out the user
return redirect(url_for('login'))
@app.route('/viewInventory')
@login_required
def viewInventory():
itemInCartCount = current_user.itemInCartCount
print(itemInCartCount)
user_id = current_user.id
profile = current_user.profile
role = current_user.role
add_dot = '../' + profile
print(user_id)
return render_template('inventory.html', profile=add_dot, role=role, user_id=user_id,
itemInCartCount=itemInCartCount)
@app.route('/uploadProducts')
@login_required
def uploadProducts():
itemInCartCount = current_user.itemInCartCount
user_id = current_user.id
print('id', user_id)
profile = current_user.profile
add_dot = '../' + profile
role = current_user.role
firstname = current_user.firstname
lastname = current_user.lastname
email = current_user.email
password = current_user.password
if current_user.role == 1:
return render_template('uploadProducts.html', profile=add_dot, role=role, firstname=firstname, password=password,
user_id=user_id)
else:
return jsonify('WHY YOUR TRYING TO ACCESS THIS PAGE?')
@app.route('/myAccount')
@login_required
def myAccount():
itemInCartCount = current_user.itemInCartCount
user_id = current_user.id
print('id', user_id)
profile = current_user.profile
add_dot = '../' + profile
role = current_user.role
firstname = current_user.firstname
lastname = current_user.lastname
email = current_user.email
password = current_user.password
return render_template('account.html', profile=add_dot, role=role, firstname=firstname, password=password,
user_id=user_id)
@app.route('/view_users')
@login_required
def view_users():
itemInCartCount = current_user.itemInCartCount
user_id = current_user.id
profile = current_user.profile
add_dot = '../' + profile
role = current_user.role
firstname = current_user.firstname
lastname = current_user.lastname
email = current_user.email
password = current_user.password
return render_template('user.html', profile=add_dot, role=role, firstname=firstname, password=password,
user_id=user_id)
@app.route('/admin')
@login_required # Secure the route, only logged in users can access it
def admin():
itemInCartCount = current_user.itemInCartCount
user_id = current_user.id
profile = current_user.profile
add_dot = '../' + profile
role = current_user.role
firstname = current_user.firstname
lastname = current_user.lastname
email = current_user.email
password = current_user.password
if current_user.role == 1:
return render_template('admin.html', profile=add_dot, role=role, firstname=firstname, password=password,
user_id=user_id)
else:
return jsonify('WHY YOUR TRYING TO ACCESS THIS PAGE?')
@app.route('/overview')
@login_required # Secure the route, only logged in users can access it
def overview():
itemInCartCount = current_user.itemInCartCount
user_id = current_user.id
profile = current_user.profile
add_dot = '../' + profile
role = current_user.role
firstname = current_user.firstname
lastname = current_user.lastname
email = current_user.email
password = current_user.password
return render_template('overview.html', profile=add_dot, role=role, firstname=firstname, password=password,
user_id=user_id)
@app.route('/displayProducts')
@login_required # Secure the route, only logged in users can access it
def displayProducts():
itemInCartCount = current_user.itemInCartCount
user_id = current_user.id
profile = current_user.profile
add_dot = '../' + profile
role = current_user.role
firstname = current_user.firstname
lastname = current_user.lastname
email = current_user.email
password = current_user.password
return render_template('display_products.html', profile=add_dot, role=role, firstname=firstname, password=password,
user_id=user_id)
@app.route('/user')
@login_required # Secure the route, only logged in users can access it
def user():
itemInCartCount = current_user.itemInCartCount
user_id = current_user.id
profile = current_user.profile
add_dot = '../' + profile
role = current_user.role
firstname = current_user.firstname
lastname = current_user.lastname
email = current_user.email
password = current_user.password
return render_template('user.html', profile=add_dot, role=role, firstname=firstname, password=password,
user_id=user_id)
@app.route('/register', methods=['GET'])
def register():
# User logic here
return render_template('register.html')
if __name__ == '__main__':
app.run(host='10.0.2.150', port=3000, debug=True)