Repository navigation
Expand file tree
/
Copy pathuser.py
More file actions
774 lines (621 loc) · 29.6 KB
/
Copy pathuser.py
File metadata and controls
774 lines (621 loc) · 29.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
from flask import Blueprint, request, session, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
import random
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import requests
import os
import json
from db import get_db_connection, allowed_file, ALLOWED_EXTENSIONS, create_notification
user_bp = Blueprint('user', __name__, url_prefix='/api')
import string
def generate_unique_connection_code(cursor):
"""Generate a unique AB12345-style code (2 capitals + 5 digits)."""
while True:
code = ''.join(random.choices(string.ascii_uppercase, k=2)) + \
''.join(random.choices(string.digits, k=5))
cursor.execute("SELECT id FROM users WHERE connection_code = %s", (code,))
if not cursor.fetchone():
return code
# --- CONFIGURATION ---
with open("client_secret.json", "r") as f:
config = json.load(f)
SENDER_EMAIL = config["app"]["sender_email"]
SENDER_PASSWORD = config["app"]["sender_password"]
UPLOAD_FOLDER = config["app"]["upload_folder"]
# ══════════════════════════════════════════════════════════════════════════
# POST /register
# ══════════════════════════════════════════════════════════════════════════
@user_bp.route('/register', methods=['POST'])
def register():
username = request.form.get('username')
password = request.form.get('password')
profile_pic = request.files.get('profile_pic')
if not username or not password:
return jsonify({'success': False, 'message': 'Username and password are required'}), 400
profile_pic_path = None
if profile_pic and profile_pic.filename != '' and allowed_file(profile_pic.filename):
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
filename = secure_filename(profile_pic.filename)
unique_filename = f"{username}_{filename}"
filepath = os.path.join(UPLOAD_FOLDER, unique_filename)
profile_pic.save(filepath)
profile_pic_path = f"uploads/profile_pics/{unique_filename}"
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute("SELECT id FROM users WHERE username = %s", (username,))
if cursor.fetchone():
return jsonify({'success': False, 'message': 'Username already taken!'}), 409
hashed_password = generate_password_hash(password)
cursor.execute(
"INSERT INTO users (username, password, profile_pic) VALUES (%s, %s, %s)",
(username, hashed_password, profile_pic_path)
)
connection.commit()
user_id = cursor.lastrowid
session['user_id'] = user_id
return jsonify({'success': True, 'user_id': user_id, 'username': username})
except Exception as e:
connection.rollback()
return jsonify({'success': False, 'message': str(e)}), 500
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# POST /login
# ══════════════════════════════════════════════════════════════════════════
@user_bp.route('/login', methods=['POST'])
def login():
username = request.form.get('username')
password = request.form.get('password')
print(f"DEBUG login: username={username!r} password={password!r} form={dict(request.form)}")
if not username or not password:
return jsonify({'success': False, 'message': 'Username and password are required'}), 400
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute("SELECT id, password FROM users WHERE username = %s", (username,))
user = cursor.fetchone()
print(f"DEBUG login: user_row={user!r}")
if not user:
return jsonify({'success': False, 'message': 'Invalid username or password'}), 401
stored_hash = user[1]
password_ok = False
if stored_hash:
try:
password_ok = check_password_hash(stored_hash, password)
except Exception as e:
print(f"DEBUG login: check_password_hash raised: {e!r}")
password_ok = False
print(f"DEBUG login: password_ok={password_ok}")
if not password_ok:
return jsonify({'success': False, 'message': 'Invalid username or password'}), 401
session['user_id'] = user[0]
return jsonify({'success': True, 'user_id': user[0]})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# POST /logout
# ══════════════════════════════════════════════════════════════════════════
@user_bp.route('/logout', methods=['POST'])
def logout():
session.pop('user_id', None)
return jsonify({'success': True})
# ══════════════════════════════════════════════════════════════════════════
# GET /me
# ══════════════════════════════════════════════════════════════════════════
@user_bp.route('/me')
def me():
if 'user_id' not in session:
return jsonify({'success': False, 'authenticated': False}), 401
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute(
"SELECT id, username, email, position, age, gender, profile_pic, connection_code FROM users WHERE id = %s",
(session['user_id'],)
)
user = cursor.fetchone()
if not user:
session.pop('user_id', None)
return jsonify({'success': False, 'authenticated': False}), 401
return jsonify({'success': True, 'authenticated': True, 'user': user})
finally:
cursor.close()
connection.close()
# --- GOOGLE AUTH & OTP ROUTES ---
@user_bp.route('/send_verification_otp', methods=['POST'])
def send_verification_otp():
data = request.get_json()
email = data.get('email')
if not email:
return jsonify({'success': False, 'message': 'Email is required'})
otp_code = str(random.randint(100000, 999999))
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute("DELETE FROM otp_verifications WHERE verified = 1 OR created_at < NOW() - INTERVAL 1 HOUR")
connection.commit()
try:
cursor.execute(
"INSERT INTO otp_verifications (email_address, otp_code) VALUES (%s, %s)",
(email, otp_code)
)
connection.commit()
msg = MIMEMultipart()
msg['From'] = SENDER_EMAIL
msg['To'] = email
msg['Subject'] = "Task Manager Verification"
body = f"Your verification code is: {otp_code}"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(SENDER_EMAIL, SENDER_PASSWORD)
server.send_message(msg)
server.quit()
return jsonify({'success': True})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
finally:
cursor.close()
connection.close()
@user_bp.route('/verify_otp', methods=['POST'])
def verify_otp():
data = request.get_json()
email = data.get('email')
user_otp = data.get('otp')
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute(
"""
SELECT otp_id FROM otp_verifications
WHERE email_address = %s AND otp_code = %s AND verified = 0
ORDER BY otp_id DESC LIMIT 1
""",
(email, user_otp)
)
result = cursor.fetchone()
if result:
otp_id = result[0]
cursor.execute("UPDATE otp_verifications SET verified = 1 WHERE otp_id = %s", (otp_id,))
connection.commit()
return jsonify({'success': True})
else:
return jsonify({'success': False, 'message': 'Invalid or expired code'})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# POST /google_register
# ══════════════════════════════════════════════════════════════════════════
@user_bp.route('/google_register', methods=['POST'])
def google_register():
username = request.form.get('google_username')
email = request.form.get('google_email')
google_profile_pic_url = request.form.get('google_profile_pic')
if not username or not email:
return jsonify({'success': False, 'message': 'Missing data'}), 400
profile_pic_path = None
if google_profile_pic_url:
try:
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
response = requests.get(google_profile_pic_url, timeout=10)
if response.status_code == 200:
filename = f"{username}_google_profile.jpg"
filepath = os.path.join(UPLOAD_FOLDER, filename)
with open(filepath, 'wb') as f:
f.write(response.content)
profile_pic_path = f"uploads/profile_pics/{filename}"
except Exception as e:
print(f"Error downloading Google profile picture: {e}")
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute("SELECT id FROM users WHERE username = %s", (username,))
if cursor.fetchone():
return jsonify({'success': False, 'message': 'Username already taken! Please choose another.'}), 409
code = generate_unique_connection_code(cursor)
cursor.execute(
"INSERT INTO users (username, email, password, profile_pic, connection_code) VALUES (%s, %s, NULL, %s, %s)",
(username, email, profile_pic_path, code)
)
connection.commit()
user_id = cursor.lastrowid
session['user_id'] = user_id
return jsonify({'success': True, 'user_id': user_id})
except Exception as e:
connection.rollback()
return jsonify({'success': False, 'message': f'Database Error: {e}'}), 500
finally:
cursor.close()
connection.close()
@user_bp.route('/check_google_user', methods=['POST'])
def check_google_user():
data = request.get_json()
email = data.get('email')
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute("SELECT id FROM users WHERE email = %s", (email,))
user = cursor.fetchone()
if user:
session['user_id'] = user[0]
return jsonify({'exists': True})
return jsonify({'exists': False})
finally:
cursor.close()
connection.close()
def send_security_alert(to_email, username):
try:
msg = MIMEMultipart()
msg['From'] = SENDER_EMAIL
msg['To'] = to_email
msg['Subject'] = "Security Alert: Email Address Changed"
body = (
f"Hello {username},\n\n"
"Your account email address was just changed. If this was you, you can ignore this message.\n\n"
"If you did not authorize this change, please contact support immediately."
)
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(SENDER_EMAIL, SENDER_PASSWORD)
server.send_message(msg)
server.quit()
except Exception as e:
print(f"Failed to send security alert: {e}")
# ══════════════════════════════════════════════════════════════════════════
# GET /profile
# ══════════════════════════════════════════════════════════════════════════
@user_bp.route('/profile')
def user_profile():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
user_id = session['user_id']
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute(
"SELECT id, username, email, gender, position, profile_pic, "
"age, connection_code "
"FROM users WHERE id = %s",
(user_id,)
)
user = cursor.fetchone()
if not user:
return jsonify({'success': False, 'message': 'User not found'}), 404
return jsonify({'success': True, 'user': user})
finally:
cursor.close()
connection.close()
@user_bp.route('/verify_old_email_google', methods=['POST'])
def verify_old_email_google():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
data = request.get_json()
google_email = data.get('email')
if not google_email:
return jsonify({'success': False, 'message': 'Email is required'})
user_id = session['user_id']
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute("SELECT email FROM users WHERE id = %s", (user_id,))
user = cursor.fetchone()
if not user or not user['email']:
return jsonify({'success': False, 'message': 'No email found'})
current_email = user['email']
if google_email.lower() != current_email.lower():
return jsonify({'success': False, 'message': 'Email does not match your current email'})
return jsonify({'success': True})
except Exception as e:
print(f"Error verifying old email with Google: {e}")
return jsonify({'success': False, 'message': str(e)})
finally:
cursor.close()
connection.close()
@user_bp.route('/homepage_save_email', methods=['POST'])
def homepage_save_email():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
data = request.get_json()
email = data.get('email')
if not email:
return jsonify({'success': False, 'message': 'Email is required'})
user_id = session['user_id']
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute("SELECT id FROM users WHERE email = %s AND id != %s", (email, user_id))
if cursor.fetchone():
return jsonify({'success': False, 'message': 'This email is already linked to another account.'})
cursor.execute("SELECT connection_code FROM users WHERE id = %s", (user_id,))
row = cursor.fetchone()
needs_code = row and not row[0]
if needs_code:
code = generate_unique_connection_code(cursor)
cursor.execute("UPDATE users SET email = %s, connection_code = %s WHERE id = %s", (email, code, user_id))
else:
cursor.execute("UPDATE users SET email = %s WHERE id = %s", (email, user_id))
connection.commit()
return jsonify({'success': True})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
finally:
cursor.close()
connection.close()
@user_bp.route('/update_profile', methods=['POST'])
def update_profile():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
user_id = session['user_id']
new_username = request.form.get('username')
new_email = request.form.get('email') or None
new_gender = request.form.get('gender')
new_position = request.form.get('position')
old_email_verified = request.form.get('old_email_verified') == 'true'
new_email_otp = request.form.get('new_email_otp')
file = request.files.get('profile_pic')
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
current_user = cursor.fetchone()
if not current_user:
return jsonify({'success': False, 'message': 'User not found'}), 404
current_email = current_user['email']
if new_email != current_email and new_email:
if current_email and not old_email_verified:
return jsonify({'success': False, 'message': 'Old email verification required'}), 400
if not new_email_otp:
return jsonify({'success': False, 'message': 'New email verification required'}), 400
cursor.execute("""
SELECT otp_id FROM otp_verifications
WHERE email_address = %s AND otp_code = %s AND verified = 0
ORDER BY otp_id DESC LIMIT 1
""", (new_email, new_email_otp))
new_otp_result = cursor.fetchone()
if not new_otp_result:
return jsonify({'success': False, 'message': 'Invalid verification code for new email'}), 400
cursor.execute("UPDATE otp_verifications SET verified = 1 WHERE otp_id = %s", (new_otp_result['otp_id'],))
if current_email:
send_security_alert(current_email, current_user['username'])
if not current_user.get('connection_code'):
new_code = generate_unique_connection_code(cursor)
cursor.execute("UPDATE users SET connection_code = %s WHERE id = %s", (new_code, user_id))
query = """
UPDATE users
SET username = %s, email = %s, gender = %s, position = %s
WHERE id = %s
"""
cursor.execute(query, (new_username, new_email, new_gender, new_position, user_id))
image_path = None
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
unique_filename = f"{user_id}_{int(random.random()*1000)}_{filename}"
filepath = os.path.join(UPLOAD_FOLDER, unique_filename)
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
file.save(filepath)
db_path = f"uploads/profile_pics/{unique_filename}"
cursor.execute("UPDATE users SET profile_pic = %s WHERE id = %s", (db_path, user_id))
image_path = db_path
connection.commit()
return jsonify({
'success': True,
'message': 'Profile Updated Successfully!',
'new_image_path': image_path
})
except Exception as e:
connection.rollback()
print(f"Update Error: {e}")
return jsonify({'success': False, 'message': f'Database Error: {str(e)}'}), 500
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# PROJECT CREATION — ProjectCreator.jsx (new schema: projects + project_members)
# ══════════════════════════════════════════════════════════════════════════
def save_project_image(file, project_id):
"""Saves the project cover image, returns db-ready relative path or None."""
if not file or not file.filename:
return None
ext = file.filename.rsplit('.', 1)[-1].lower() if '.' in file.filename else ''
if ext not in ALLOWED_EXTENSIONS:
return None
folder = os.path.join('static', 'uploads', 'project_images')
os.makedirs(folder, exist_ok=True)
filename = secure_filename(file.filename)
unique_name = f"{project_id}_{filename}"
file.save(os.path.join(folder, unique_name))
return f"uploads/project_images/{unique_name}"
@user_bp.route('/search_user_by_code')
def search_user_by_code():
"""Collaborator lookup for ProjectCreator.jsx — connection_code only."""
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
code = request.args.get('connection_code', '').strip().upper()
if not code:
return jsonify({'success': False, 'message': 'connection_code is required'}), 400
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT id, username, profile_pic FROM users WHERE connection_code = %s",
(code,)
)
user = cursor.fetchone()
if not user:
return jsonify({'success': False, 'message': 'No user found with that code'}), 404
if user[0] == session['user_id']:
return jsonify({'success': False, 'message': "That's your own code"}), 400
return jsonify({
'success': True,
'user': {'id': user[0], 'username': user[1], 'profile_pic': user[2]}
})
finally:
cursor.close()
connection.close()
@user_bp.route('/create_project', methods=['POST'])
def create_project():
"""
Creates a project from ProjectCreator.jsx.
Expects multipart/form-data:
- project_name (str, required)
- description (str, optional)
- project_image (file, optional)
- collaborator_ids (JSON array of user ids, optional)
"""
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
owner_id = session['user_id']
project_name = request.form.get('project_name', '').strip()
description = request.form.get('description', '').strip() or None
image_file = request.files.get('project_image')
if not project_name:
return jsonify({'success': False, 'message': 'project_name is required'}), 400
collaborator_ids_raw = request.form.get('collaborator_ids', '[]')
try:
collaborator_ids = json.loads(collaborator_ids_raw)
if not isinstance(collaborator_ids, list):
collaborator_ids = []
except json.JSONDecodeError:
collaborator_ids = []
# Dedup + never allow adding yourself as a "member" row twice
collaborator_ids = list({int(uid) for uid in collaborator_ids if str(uid).isdigit() and int(uid) != owner_id})
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute(
"INSERT INTO projects (name, description, owner_id) VALUES (%s, %s, %s)",
(project_name, description, owner_id)
)
connection.commit()
project_id = cursor.lastrowid
if image_file and image_file.filename:
image_path = save_project_image(image_file, project_id)
if image_path:
cursor.execute(
"UPDATE projects SET project_image = %s WHERE id = %s",
(image_path, project_id)
)
connection.commit()
# Collaborators get invited instead of force-added
for uid in collaborator_ids:
cursor.execute(
"""INSERT IGNORE INTO project_invitations (project_id, inviter_id, invitee_id)
VALUES (%s, %s, %s)""",
(project_id, owner_id, uid)
)
cursor.execute("SELECT LAST_INSERT_ID()")
invite_id = cursor.fetchone()[0]
# INSERT IGNORE was a no-op (duplicate invite) — skip notification
if invite_id == 0:
continue
create_notification(
cursor,
uid,
'project_invitation',
"Project Invitation",
f"You were invited to join \"{project_name}\".",
invite_id
)
connection.commit()
return jsonify({'success': True, 'project_id': project_id})
except Exception as e:
connection.rollback()
return jsonify({'success': False, 'message': f'Database Error: {e}'}), 500
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# GET /api/invitations — list the logged-in user's pending invitations
# ══════════════════════════════════════════════════════════════════════════
@user_bp.route('/invitations')
def list_invitations():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute("""
SELECT pi.id, pi.project_id, pi.status, pi.created_at,
p.name AS project_name, p.project_image,
u.username AS inviter_username, u.profile_pic AS inviter_pic
FROM project_invitations pi
JOIN projects p ON p.id = pi.project_id
JOIN users u ON u.id = pi.inviter_id
WHERE pi.invitee_id = %s
ORDER BY pi.created_at DESC
""", (session['user_id'],))
invitations = cursor.fetchall()
for inv in invitations:
inv['created_at'] = str(inv['created_at'])
return jsonify({'success': True, 'invitations': invitations})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# POST /api/respond_invitation_v2 — accept or reject a project invitation
# ══════════════════════════════════════════════════════════════════════════
@user_bp.route('/respond_invitation_v2', methods=['POST'])
def respond_invitation_v2():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
user_id = session['user_id']
invitation_id = request.form.get('invitation_id', type=int)
response = request.form.get('response', '').strip().lower()
if not invitation_id or response not in ('accept', 'reject'):
return jsonify({'success': False, 'message': 'Invalid invitation_id or response'}), 400
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute("""
SELECT id, project_id, inviter_id, status
FROM project_invitations
WHERE id = %s AND invitee_id = %s
""", (invitation_id, user_id))
inv = cursor.fetchone()
if not inv:
return jsonify({'success': False, 'message': 'Invitation not found'}), 404
if inv['status'] != 'pending':
return jsonify({'success': False, 'message': 'Already responded to this invitation'}), 409
new_status = 'accepted' if response == 'accept' else 'rejected'
cursor.execute("""
UPDATE project_invitations
SET status = %s, responded_at = NOW()
WHERE id = %s
""", (new_status, invitation_id))
if response == 'accept':
cursor.execute("""
INSERT IGNORE INTO project_members (project_id, user_id)
VALUES (%s, %s)
""", (inv['project_id'], user_id))
cursor.execute("SELECT username FROM users WHERE id = %s", (user_id,))
responder = cursor.fetchone()
responder_name = responder['username'] if responder else "Someone"
cursor.execute("SELECT name FROM projects WHERE id = %s", (inv['project_id'],))
proj = cursor.fetchone()
proj_name = proj['name'] if proj else "your project"
verb = "accepted" if response == 'accept' else "rejected"
create_notification(
cursor,
inv['inviter_id'],
'invitation_accepted' if response == 'accept' else 'invitation_rejected',
f"Invitation {verb}",
f"{responder_name} {verb} your invitation to join \"{proj_name}\".",
invitation_id
)
connection.commit()
return jsonify({'success': True, 'status': new_status})
except Exception as e:
connection.rollback()
return jsonify({'success': False, 'message': str(e)}), 500
finally:
cursor.close()
connection.close()