-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.py
More file actions
874 lines (666 loc) · 27.6 KB
/
Copy pathbackground.py
File metadata and controls
874 lines (666 loc) · 27.6 KB
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
from flask import Blueprint, request, session, flash, jsonify, url_for, current_app, redirect, render_template
from flask_mail import Message
import mysql.connector
from mysql.connector import Error
from datetime import datetime, timedelta
from werkzeug.utils import secure_filename
import os
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import SignatureExpired, BadSignature, URLSafeTimedSerializer
from config import Config
background_bp = Blueprint('background', __name__)
# Database connection
db = mysql.connector.connect(
host="localhost",
user="root",
password="1349U3of1393ND$",
database="test1"
)
def get_db_connection():
try:
db = mysql.connector.connect(
host="localhost",
user="root",
password="1349U3of1393ND$",
database="test1"
)
if db.is_connected():
return db
except Error as e:
print("Error connecting to MySQL database:", e)
return None
def close_db_connection(db, cursor):
if db:
db.close()
if cursor:
cursor.close()
# Shut down the scheduler when exiting the app
import atexit
atexit.register(lambda: scheduler.shutdown())
@background_bp.route('/get_services')
def get_services():
db = get_db_connection()
cursor = db.cursor(dictionary=True)
cursor.execute("SELECT service_id, service_type, service_name, price FROM services")
results = cursor.fetchall()
cursor.close()
db.close()
service_data = {}
for row in results:
service_id = row['service_id']
service_type = row['service_type']
service_name = row['service_name']
price = row['price']
# Create the formatted string "service_name - price"
service_entry = {
"service_name": f"{service_name} - {price}",
"service_id": service_id
}
if service_type not in service_data:
service_data[service_type] = []
service_data[service_type].append(service_entry)
return jsonify(service_data)
@background_bp.route('/cancel_booking', methods=['POST'])
def cancel_booking():
appt_id = request.form.get('appt_id')
if not appt_id:
return jsonify({"error": "Appointment ID is required"}), 400
db = get_db_connection()
cursor = db.cursor()
try:
cursor.execute("DELETE FROM appointments WHERE appt_id = %s", (appt_id,))
db.commit()
if cursor.rowcount == 0:
return jsonify({"error": "Booking not found"}), 404
return jsonify({"success": "Booking canceled successfully"}), 200
except Exception as e:
db.rollback()
return jsonify({"error": str(e)}), 500
finally:
close_db_connection(db, cursor)
@background_bp.route('/final-confirm', methods=['POST'])
def final_confirm():
data = request.get_json()
selected_services = data.get('services')
booking_number = data.get('bookingNumber')
start_date_str = data.get('date')
booking_details = []
for service in selected_services:
# Access `service id` and `timeSlot` properties from each entry
service_id = service['service_id']
service_name = service['service']
time_slot = service['timeSlot']
# making sure the format of time_slot is correct
start_date = datetime.strptime(time_slot, "%m/%d/%Y %I:%M:%S %p")
appt_date = start_date.date()
start_time = start_date.time()
end_date = start_date + timedelta(minutes=30)
end_time = end_date.time()
booking_details.append(f"Service: {service_name} \nDate: {appt_date} \nTime: {start_time}\n")
db = get_db_connection()
cursor = db.cursor()
cursor.execute(
'INSERT INTO appointments (booking_number, customer_id, service_id, appointment_date, appointment_start_time, appointment_end_time) VALUES (%s, %s, %s, %s, %s, %s)',
(booking_number, session['CustomerID'], service_id, appt_date, start_time, end_time)
)
db.commit()
db.close()
cursor.close()
email_body = (
f"Dear Customer,\n\n"
f"Your booking has been confirmed with the following details:\n\n"
f"Booking Number: {booking_number}\n"
f"Date: {start_date_str}\n"
f"Services:\n" + "\n".join(booking_details) + "\n\n"
f"Thank you for choosing our services!\n\n"
f"Best Regards,\nYour Company Name"
)
# Send the email
send_email_smtp(
subject="Booking Confirmation",
body=email_body,
to_email=session['Email'] # Ensure 'CustomerEmail' is stored in session
)
return jsonify({"status": "success", "bookingNumber": booking_number})
#seller side
#
#
#
@background_bp.route('/save-week-schedule', methods=['POST'])
def save_week_schedule():
data = request.get_json()
time_slot = data.get('timeSlot')
managerID = session['ManagerID']
days = data.get('days')
db = get_db_connection()
cursor = db.cursor()
# Update query using 'days' as a dictionary with the proper values
cursor.execute(
'''
UPDATE `week_schedule`
SET managerID = %s, monday = %s, tuesday = %s, wednesday = %s, thursday = %s, friday = %s, saturday = %s, sunday = %s
WHERE time_slot = %s
''',
(managerID, days['monday'], days['tuesday'], days['wednesday'], days['thursday'], days['friday'], days['saturday'], days['sunday'], time_slot)
)
db.commit()
db.close()
cursor.close()
return jsonify({"success": "successful"})
@background_bp.route('/change-store-hours', methods=['POST'])
def change_store_hours():
try:
data = request.get_json()
open_hour = data.get('open')
close_hour = data.get('close')
current_day = data.get('day')
if not open_hour or not close_hour or not current_day:
return jsonify({"error": "Missing required fields"}), 400
db = get_db_connection()
cursor = db.cursor(dictionary=True)
cursor.execute('UPDATE `business_hours` SET open_hour = %s, close_hour = %s WHERE day = %s', (open_hour, close_hour, current_day))
db.commit()
db.close()
cursor.close()
return jsonify({"success": "Successfully changed"})
except Exception as e:
# Handle any unexpected errors
return jsonify({"error": str(e)}), 500
@background_bp.route('/manage-services')
def manage_service():
return
@background_bp.route('/edit-employee-info', methods=['POST'])
def edit_employee_info():
data = request.get_json()
try:
employeeID = data.get('id')
name = data.get('name')
phone = data.get('phone')
expertise = data.get('expertise')
email = data.get('email')
db = get_db_connection()
cursor = db.cursor()
cursor.execute('UPDATE employee SET Employee_name = %s, Email = %s, Phone = %s, services_provided = %s WHERE EmployeeID = %s' , (name, email, phone, expertise, employeeID))
db.commit()
db.close()
cursor.close()
return jsonify({"success": "Succesffuly changed"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@background_bp.route('/edit-manager-info', methods=['POST'])
def edit_manager_info():
data = request.get_json()
try:
managerID = data.get('id')
name = data.get('name')
phone = data.get('phone')
email = data.get('email')
db = get_db_connection()
cursor = db.cursor()
cursor.execute('UPDATE managers SET Name = %s, email = %s, phone = %s WHERE managerID = %s' , (name, email, phone, managerID))
db.commit()
db.close()
cursor.close()
return jsonify({"success": "Succesffuly changed"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@background_bp.route('/remove-employee', methods=['POST'])
def remove_employee():
try:
data = request.get_json()
id = data.get('employeeID')
db = get_db_connection()
cursor = db.cursor()
cursor.execute('DELETE FROM employee where EmployeeID = %s', (id,))
db.commit()
db.close()
cursor.close()
return jsonify({"success": "Succesffuly changed"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@background_bp.route('/remove-manager', methods=['POST'])
def remove_manager():
try:
data = request.get_json()
id = data.get('employeeID')
print(data)
db = get_db_connection()
cursor = db.cursor()
cursor.execute('''UPDATE week_schedule SET managerID = %s WHERE managerID = %s''', ('101123', id))
cursor.execute('DELETE FROM managers where managerID = %s', (id,))
db.commit()
db.close()
cursor.close()
return jsonify({"success": "Succesffuly changed"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@background_bp.route('/add-employee', methods=['POST'])
def add_employee():
try:
data = request.get_json()
name = data.get('name')
email = data.get('email')
phone = data.get('phone')
expertise = data.get('expertise')
db = get_db_connection()
cursor = db.cursor(dictionary=True)
cursor.execute('INSERT INTO employee (Employee_name, Email, Phone, services_provided) VALUES (%s, %s, %s, %s)', (name, email, phone, expertise))
db.commit()
db.close()
cursor.close()
return jsonify({"success": "Successfully added an employee"})
except Exception as e:
return jsonify({"error": str(e)}), 500
UPLOAD_FOLDER = 'static/photos' # Ensure this folder exists
# Allowed extensions
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def get_unique_filename(upload_folder, filename):
base, ext = os.path.splitext(filename)
counter = 1
unique_filename = filename
while os.path.exists(os.path.join(upload_folder, unique_filename)):
unique_filename = f"{base}_{counter}{ext}"
counter += 1
return unique_filename
@background_bp.route('/add-service', methods=['POST'])
def upload_service_image():
if 'service_image' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files.get('service_image')
name = request.form.get('service_name')
price = request.form.get('service_price')
type = request.form.get('type')
price = price_format(price)
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
upload_folder = current_app.config['UPLOAD_FOLDER']
# Get a unique filename if it already exists
unique_filename = get_unique_filename(upload_folder, filename)
file_path = os.path.join(upload_folder, unique_filename)
file.save(file_path)
db = get_db_connection()
cursor = db.cursor()
cursor.execute('INSERT INTO services (service_type, service_name, image, price) VALUES (%s, %s, %s, %s)', (type, name, file_path, price))
db.commit()
close_db_connection(db, cursor)
return jsonify({'image_url': f'/static/photos/{unique_filename}'})
return jsonify({'error': 'File type not allowed'}), 400
@background_bp.route('/update-service', methods=['POST'])
def update_service():
image_changed = request.form.get('image_changed') == 'true'
name = request.form.get('service_name')
price = request.form.get('service_price')
type = request.form.get('type')
serviceID = request.form.get('id')
db = get_db_connection()
cursor = db.cursor()
price = price_format(price)
if (image_changed):
if 'service_image' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files.get('service_image')
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
upload_folder = current_app.config['UPLOAD_FOLDER']
# Get a unique filename if it already exists
unique_filename = get_unique_filename(upload_folder, filename)
file_path = os.path.join(upload_folder, unique_filename)
file.save(file_path)
cursor.execute('UPDATE services SET service_type = %s, service_name = %s, image = %s, price = %s WHERE service_id = %s', (type, name, file_path, price, serviceID))
db.commit()
close_db_connection(db, cursor)
return jsonify({"success": "Successfully updated"})
else:
cursor.execute('UPDATE services SET service_type = %s, service_name = %s, price = %s WHERE service_id = %s', (type, name, price, serviceID))
db.commit()
close_db_connection(db, cursor)
return jsonify({"success": "Successfully updated"})
db.commit()
close_db_connection(db, cursor)
return jsonify({"error": "File type not allowed"}), 400
@background_bp.route('/remove-service', methods=['POST'])
def remove_service():
data = request.get_json()
db = get_db_connection()
cursor = db.cursor()
cursor.execute('DELETE FROM services WHERE service_id = %s', (data,))
db.commit()
close_db_connection(db, cursor)
return jsonify({"success": "successfully removed service"})
@background_bp.route('/search-employee', methods=['GET'])
def search_employee():
search_term = request.args.get('name', '').strip()
per_page = 5
page = request.args.get('page', 1, type=int)
offset = (page - 1) * per_page
db = get_db_connection()
cursor = db.cursor(dictionary=True)
try:
# Build the query with pagination and search term if provided
if search_term:
query = 'SELECT * FROM employee WHERE Employee_name LIKE %s LIMIT %s OFFSET %s'
cursor.execute(query, ('%' + search_term + '%', per_page, offset))
else:
query = 'SELECT * FROM employee LIMIT %s OFFSET %s'
cursor.execute(query, (per_page, offset))
results = cursor.fetchall()
cursor.execute('SELECT COUNT(*) AS total FROM employee WHERE Employee_name LIKE %s', ('%' + search_term + '%',))
total = cursor.fetchone()['total']
except Exception as e:
print(f"Error querying database: {e}")
finally:
close_db_connection(db, cursor)
total_pages = (total // per_page) + (1 if total % per_page > 0 else 0)
return render_template('seller/employeeinfo.html', results=results, search_term=search_term, page=page, total=total, total_pages=total_pages, per_page=per_page)
def price_format(price):
if price and '$' not in price:
price = f'${price}'
if price.endswith('+'):
price_without_plus = price[:-1]
if '.00' not in price_without_plus and '.0' not in price_without_plus:
price = price_without_plus + '.00+'
elif '.0' in price_without_plus:
price = price_without_plus + '0+'
else:
price = price_without_plus + '+'
if '.' in price and '+' not in price:
if '.00' not in price and '.0' not in price:
price = f'{price}00'
if '.00' not in price and '.0' in price:
price = f'{price}0'
if '.' not in price:
price = f'{price}.00'
elif '$' not in price:
price_parts = price.split('.')
if len(price_parts[1]) == 1:
price = f'{price}0'
elif len(price_parts[1]) > 2:
price = f'{price_parts[0]}.{price_parts[1][:2]}'
return price
def check_user(name: str) -> bool:
db = get_db_connection()
cursor = db.cursor()
cursor.execute('SELECT * FROM users WHERE UserName = %s', (name,))
have_name = cursor.fetchone()
db.close()
cursor.close()
if have_name:
return True
else:
return False
def check_email(email: str) -> bool:
db = get_db_connection()
cursor = db.cursor()
cursor.execute('SELECT * FROM users WHERE Email = %s', (email,))
have_name = cursor.fetchone()
close_db_connection(db, cursor)
if have_name:
return True
else:
return False
def check_manager(username: str, email: str, id: int, phone: int) -> bool:
db = get_db_connection()
cursor = db.cursor()
# Check for each condition
cursor.execute('SELECT * FROM managers WHERE managerID = %s', (id,))
isID = cursor.fetchone()
cursor.execute('SELECT * FROM managers WHERE UserName = %s', (username,))
isUsername = cursor.fetchone()
cursor.execute('SELECT * FROM managers WHERE email = %s', (email,))
isEmail = cursor.fetchone()
cursor.execute('SELECT * FROM managers WHERE phone = %s', (phone,))
isPhone = cursor.fetchone()
msg = ''
if isID:
msg += 'Manager ID is already taken.'
if isUsername:
msg += 'Username is already taken.'
if isEmail:
msg += 'Email is already taken.'
if isPhone:
msg += 'Phone number is already taken.'
if msg:
return False, msg.strip()
return True, ''
def to_24_hour_format(time_str):
time_obj = datetime.strptime(time_str, "%I:%M %p")
return time_obj.strftime("%H:%M:%S")
def to_12_hour(td):
total_seconds = int(td.total_seconds())
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
hours_12 = hours % 12
if hours_12 == 0:
hours_12 = 12
am_pm = "AM" if hours < 12 else "PM"
return f"{hours_12:02}:{minutes:02}:{seconds:02} {am_pm}"
def to_12_hour_no_second(td):
total_seconds = int(td.total_seconds())
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
hours_12 = hours % 12
if hours_12 == 0:
hours_12 = 12
am_pm = "AM" if hours < 12 else "PM"
return f"{hours_12:02}:{minutes:02} {am_pm}"
def send_email_smtp(subject, body, to_email):
mail = current_app.extensions['mail']
msg = Message(subject, recipients=[to_email], body=body)
try:
mail.send(msg)
print(f"Email sent successfully to {to_email}")
except Exception as e:
print(f"Failed to send email to {to_email}. Error: {str(e)}")
def appt_reminder():
now = datetime.now()
appt = now + timedelta(hours=24)
appt_date = appt.date()
appt_time = appt.time()
day_of_week = appt_date.strftime('%A')
db = get_db_connection()
cursor = db.cursor(dictionary=True)
cursor.execute(
'''
SELECT
apt.appt_id,
apt.booking_number,
apt.customer_id,
u.Name,
u.Email,
apt.service_id,
s.service_name,
apt.appointment_date,
apt.appointment_start_time
FROM appointments AS apt
JOIN users AS u ON apt.customer_id = u.CustomerID
JOIN services AS s ON apt.service_id = s.service_id
WHERE apt.appointment_date = %s
AND apt.appointment_start_time = %s;
''',
(appt_date, appt_time,)
)
results = cursor.fetchall()
if results:
for result in results:
if result and result['Email']:
result['appointment_start_time'] = to_12_hour_no_second(result['appointment_start_time'])
send_email_smtp(
subject="Appointment Reminder",
body = (
f"Hello {result['Name']}, \n\n"
f"Just a reminder that you have an appointment at Jack&Son Nails Spa\n"
f"On {day_of_week}, {result['appointment_date']} at {result['appointment_start_time']}\n"
f"Service: {result['service_name']}"
),
to_email=result['Email']
)
scheduler = BackgroundScheduler()
scheduler.add_job(
func=appt_reminder,
trigger=CronTrigger(minute="0,30")
)
scheduler.start()
def generate_token(email):
s = URLSafeTimedSerializer(Config.SECRET_KEY)
token = s.dumps(email, salt='password-reset-salt')
return token
def get_email(token):
try:
s = URLSafeTimedSerializer(Config.SECRET_KEY)
email = s.loads(token, salt='password-reset-salt', max_age=3600)
return email
except SignatureExpired:
print('The reset link has expired.', 'danger')
return None
except BadSignature:
print('The reset link is invalid or has been tampered with.', 'danger')
return None
except Exception as e:
print(f"Error occurred: {str(e)}")
flash('An error occurred while processing your request.', 'danger')
return None
@background_bp.route('/req_password_', methods=['GET', 'POST'])
def request_reset():
msg = ''
usertype = request.args.get('usertype', '')
if usertype not in ['password', 'username']:
flash('Invalid request type.', 'danger')
return redirect(url_for('login'))
if request.method == 'POST':
email = request.form['email']
print(email)
db = get_db_connection()
cursor = db.cursor(dictionary=True)
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))
user = cursor.fetchone()
close_db_connection(db, cursor)
if user:
token = generate_token(user['Email'])
reset_link = url_for('background.reset_password', token=token, usertype=usertype, _external=True)
send_email_smtp(
subject=f"Reset {usertype.capitalize()} Request ",
body= f'Click the following link to reset your {usertype}: {reset_link}',
to_email=user['Email']
)
flash(f'A {usertype} reset email has been sent.', 'info')
print('GET request received')
return redirect(url_for('login'))
else:
msg = f"The email you entered ({email}) does not belong to an account."
return redirect(url_for('background.req_password', msg=msg, usertype=usertype))
return redirect(url_for('background.req_password', usertype=usertype))
@background_bp.route('/maanegr_req_password_', methods=['GET', 'POST'])
def manager_request_reset():
msg = ''
usertype = request.args.get('usertype', '')
if usertype not in ['password', 'username']:
flash('Invalid request type.', 'danger')
return redirect(url_for('login'))
if request.method == 'POST':
email = request.form['email']
id = request.form['ID']
print(email)
db = get_db_connection()
cursor = db.cursor(dictionary=True)
cursor.execute("SELECT * FROM managers WHERE email = %s AND managerID = %s", (email, id,))
user = cursor.fetchone()
close_db_connection(db, cursor)
if user:
token = generate_token(user['email'])
reset_link = url_for('background.manager_reset_password', token=token, usertype=usertype, _external=True)
send_email_smtp(
subject=f"Reset {usertype.capitalize()} Request ",
body= f'Click the following link to reset your {usertype}: {reset_link}',
to_email=user['email']
)
flash(f'A {usertype} reset email has been sent.', 'info')
print('GET request received')
return redirect(url_for('employee_login'))
else:
msg = f"The email ({email}) or ID ({id}) you entered does not belong to an account."
return redirect(url_for('manager_req_password', msg=msg, usertype=usertype))
return redirect(url_for('manager_req_password', usertype=usertype))
@background_bp.route('/resetpass/<token>', methods=['GET', 'POST'])
def reset_password(token):
msg = ''
usertype = request.args.get('usertype', '')
if usertype not in ('password', 'username'):
usertype = ''
email = get_email(token)
if not email:
flash('Invalid or expired token.', 'danger')
return redirect(url_for('login'))
if request.method == 'GET':
print('method is GET')
return render_template('client/resetpass.html', token=token, usertype=usertype)
if request.method == 'POST':
try:
new_form = request.form.get('password') if usertype == 'password' else request.form.get('username')
db = get_db_connection()
cursor = db.cursor()
if usertype == 'password':
hashed_password = generate_password_hash(new_form)
cursor.execute("UPDATE users SET passcode = %s WHERE Email = %s", (hashed_password, email))
db.commit()
msg = 'Password updated successfully'
else:
cursor.execute('SELECT * FROM users WHERE UserName = %s', (new_form,))
result = cursor.fetchone()
if result:
msg = 'Username taken'
return render_template('client/resetpass.html', msg=msg)
cursor.execute("UPDATE users SET UserName = %s WHERE Email = %s", (new_form, email))
db.commit()
msg = 'Username updated successfully'
close_db_connection(db, cursor)
return render_template('client/login.html', msg=msg)
except Exception as e:
print(f"Error updating password: {str(e)}")
flash('Failed to update the password. Please try again.', 'danger')
return render_template('client/req_password.html')
@background_bp.route('/manager-resetpass/<token>', methods=['GET', 'POST'])
def manager_reset_password(token):
msg = ''
usertype = request.args.get('usertype', '')
if usertype not in ('password', 'username'):
usertype = ''
email = get_email(token)
if not email:
flash('Invalid or expired token.', 'danger')
return redirect(url_for('login'))
if request.method == 'GET':
print('method is GET')
return render_template('seller/resetpass.html', token=token, usertype=usertype)
if request.method == 'POST':
try:
new_form = request.form.get('password') if usertype == 'password' else request.form.get('username')
db = get_db_connection()
cursor = db.cursor()
if usertype == 'password':
hashed_password = generate_password_hash(new_form)
cursor.execute("UPDATE managers SET password = %s WHERE email = %s", (hashed_password, email))
db.commit()
msg = 'Password updated successfully'
else:
cursor.execute('SELECT * FROM managers WHERE UserName = %s', (new_form,))
result = cursor.fetchone()
if result:
msg = 'Username taken'
return render_template('seller/resetpass.html', token=token, usertype=usertype, msg=msg)
cursor.execute("UPDATE managers SET UserName = %s WHERE Email = %s", (new_form, email))
db.commit()
msg = 'Username updated successfully'
close_db_connection(db, cursor)
return render_template('seller/sellerlogin.html', msg=msg)
except Exception as e:
print(f"Error updating password: {str(e)}")
flash('Failed to update the password. Please try again.', 'danger')
return render_template('seller/sellerlogin.html')