larxius commited on
Commit
058c7b9
·
verified ·
1 Parent(s): 725ca89

Update backend/routes.py

Browse files
Files changed (1) hide show
  1. backend/routes.py +155 -43
backend/routes.py CHANGED
@@ -135,6 +135,60 @@ def format_iso_timestamp(dt):
135
  return dt.isoformat() + 'Z'
136
 
137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  def token_required(f):
139
  @wraps(f)
140
  def decorated(*args, **kwargs):
@@ -271,8 +325,9 @@ def register():
271
 
272
  email_clean = str(raw_email).strip().lower()
273
 
274
- if len(password) < 8:
275
- return jsonify({'message': 'Password must be at least 8 characters!'}), 400
 
276
 
277
  if User.query.filter(func.lower(User.email) == email_clean).first():
278
  return jsonify({'message': 'User with this email already exists!'}), 400
@@ -428,6 +483,9 @@ def refresh():
428
  @auth_bp.route('/profile', methods=['GET'])
429
  @token_required
430
  def get_profile(current_user):
 
 
 
431
  org_name = None
432
  if current_user.org_id:
433
  org = db.session.get(Organization, current_user.org_id)
@@ -445,8 +503,7 @@ def get_profile(current_user):
445
  'subscription_tier': current_user.subscription_tier,
446
  'subscription_status': getattr(current_user, 'subscription_status', 'active'),
447
  'created_at': current_user.created_at.isoformat() + 'Z' if current_user.created_at else None,
448
- 'org_id': current_user.org_id,
449
- 'org_name': org_name
450
  }
451
  }), 200
452
 
@@ -464,17 +521,14 @@ def update_password(current_user):
464
  if not current_password or not new_password:
465
  return jsonify({'message': 'Missing required fields'}), 400
466
 
467
- print(f"DEBUG: Password change for {current_user.email}, provided current password: '{current_password}'")
468
  is_valid = current_user.check_password(current_password)
469
- print(f"DEBUG: check_password returned {is_valid}")
470
 
471
  if not is_valid:
472
- # We can also rate limit or add lockout here if desired,
473
- # but the route limiter handles basic brute force prevention.
474
  return jsonify({'message': 'Incorrect current password'}), 401
475
 
476
- if len(new_password) < 6:
477
- return jsonify({'message': 'New password must be at least 6 characters'}), 400
 
478
 
479
  current_user.set_password(new_password)
480
  db.session.commit()
@@ -490,10 +544,20 @@ def update_password(current_user):
490
  @auth_bp.route('/organizations/<org_id>/users', methods=['GET'])
491
  @token_required
492
  def get_org_users(current_user, org_id):
493
- if current_user.role not in ['super_admin', 'admin'] and current_user.org_id != org_id:
 
 
 
 
 
 
 
 
 
 
494
  return jsonify({'message': 'Unauthorized access to organization users.'}), 403
495
 
496
- org_users = User.query.filter_by(org_id=org_id).filter(User.role != 'super_admin').all()
497
 
498
  return jsonify({
499
  'users': [{
@@ -513,40 +577,48 @@ def invite_user(current_user):
513
  if current_user.role not in ('org_admin', 'super_admin', 'admin'):
514
  return jsonify({'message': 'Permission denied'}), 403
515
 
516
- data = request.get_json()
517
  email = data.get('email')
518
  role = data.get('role', 'soc_analyst')
519
  first_name = data.get('first_name')
520
  last_name = data.get('last_name')
 
521
 
522
  if not email:
523
  return jsonify({'message': 'Email is required'}), 400
524
 
525
- existing_user = User.query.filter_by(email=email).first()
 
526
  if existing_user:
527
  return jsonify({'message': 'User already exists'}), 400
528
 
529
-
530
- import string, random
531
- # Use provided password or generate a temporary password
532
- provided_password = data.get('password')
533
- temp_password = provided_password if provided_password else ''.join(random.choices(string.ascii_letters + string.digits, k=10))
 
 
 
 
 
 
 
534
 
535
  try:
536
  new_user = User(
537
  id=str(uuid.uuid4()),
538
- email=email,
539
  role=role,
540
- org_id=current_user.org_id,
541
  first_name=first_name,
542
  last_name=last_name
543
  )
544
  new_user.set_password(temp_password)
545
  db.session.add(new_user)
546
 
547
- log = AuditLog(admin_id=current_user.id, action=f"Invited user {email} with role {role}", target_id=current_user.org_id)
548
  db.session.add(log)
549
-
550
  db.session.commit()
551
 
552
  return jsonify({
@@ -556,6 +628,10 @@ def invite_user(current_user):
556
  'id': new_user.id,
557
  'email': new_user.email,
558
  'role': new_user.role,
 
 
 
 
559
  'status': 'Active'
560
  }
561
  }), 201
@@ -624,6 +700,9 @@ def update_user_credentials(current_user, user_id):
624
  updates.append('email')
625
 
626
  if new_password:
 
 
 
627
  user.set_password(new_password)
628
  updates.append('password')
629
 
@@ -795,11 +874,33 @@ def manage_organizations(current_user):
795
  def manage_single_organization(current_user, org_id):
796
  if current_user.role not in ('super_admin', 'admin', 'org_admin'):
797
  return jsonify({'message': 'Permission denied'}), 403
798
-
799
- if current_user.role == 'org_admin' and str(current_user.org_id) != str(org_id):
800
- return jsonify({'message': 'Permission denied: Cannot modify other organizations'}), 403
801
-
802
- org = db.session.get(Organization, org_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
803
  if not org:
804
  return jsonify({'message': 'Organization not found'}), 404
805
 
@@ -815,8 +916,8 @@ def manage_single_organization(current_user, org_id):
815
 
816
  # PUT method
817
  data = request.get_json() or {}
818
- if 'name' in data:
819
- org.name = data['name']
820
 
821
  if 'tier' in data:
822
  if current_user.role not in ('super_admin', 'admin'):
@@ -826,7 +927,7 @@ def manage_single_organization(current_user, org_id):
826
  log = AuditLog(admin_id=current_user.id, action="Updated tenant configuration", target_id=org.id)
827
  db.session.add(log)
828
  db.session.commit()
829
- return jsonify({'message': 'Tenant updated successfully'}), 200
830
 
831
  @auth_bp.route('/organizations/logo', methods=['POST', 'DELETE'])
832
  @token_required
@@ -1026,14 +1127,16 @@ def impersonate_org(current_user, org_id):
1026
  @auth_bp.route('/users', methods=['GET', 'POST'])
1027
  @token_required
1028
  def manage_users(current_user):
1029
- if current_user.role not in ('super_admin', 'admin'):
1030
- return jsonify({'message': 'Permission denied'}), 403
1031
-
1032
  if request.method == 'GET':
1033
- if current_user.role == 'admin':
 
 
 
1034
  users = User.query.filter(User.role != 'super_admin').all()
1035
- else:
1036
  users = User.query.all()
 
 
1037
 
1038
  return jsonify({
1039
  'users': [{
@@ -1051,6 +1154,9 @@ def manage_users(current_user):
1051
  }), 200
1052
 
1053
  # POST method - Create/Add new member
 
 
 
1054
  if current_user.role == 'support_engineer':
1055
  return jsonify({'message': 'Permission denied. Support Engineers cannot create new members.'}), 403
1056
 
@@ -1068,8 +1174,13 @@ def manage_users(current_user):
1068
  if existing:
1069
  return jsonify({'message': f'User with email "{email_clean}" already exists'}), 400
1070
 
1071
- import secrets, uuid
1072
- temp_pw = password if password else secrets.token_urlsafe(10)
 
 
 
 
 
1073
 
1074
  target_org_id = None
1075
  if org_id and str(org_id).strip() and str(org_id).lower() not in ('none', 'null', ''):
@@ -1210,10 +1321,7 @@ def get_global_stats(current_user):
1210
  'id': p.id,
1211
  'org_name': org_name,
1212
  'user_email': user_email,
1213
- 'amount': p.amount / 100 if p.amount else 0, # Total charged, major units
1214
- 'base_amount': p.base_amount / 100 if p.base_amount is not None else None,
1215
- 'platform_fee': p.platform_fee / 100 if p.platform_fee is not None else None,
1216
- 'tax_amount': p.tax_amount / 100 if p.tax_amount is not None else None,
1217
  'currency': p.currency,
1218
  'tier_id': p.tier_id,
1219
  'status': p.status,
@@ -1503,7 +1611,11 @@ def update_user(current_user, user_id):
1503
  if 'password' in data and data['password'] and str(data['password']).strip():
1504
  if current_user.role == 'support_engineer':
1505
  return jsonify({'message': 'Permission denied. Support Engineers cannot modify user passwords.'}), 403
1506
- target.set_password(str(data['password']).strip())
 
 
 
 
1507
  if 'role' in data and data['role']:
1508
  target.role = data['role']
1509
  if 'org_id' in data:
 
135
  return dt.isoformat() + 'Z'
136
 
137
 
138
+ def validate_password_strength(password):
139
+ """
140
+ Validates password meets the 4 LarShield security requirements:
141
+ 1. At least 8 characters
142
+ 2. At least one uppercase letter (A-Z)
143
+ 3. At least one lowercase letter (a-z)
144
+ 4. At least one special character (!@#$%^&* etc.)
145
+ """
146
+ if not password or len(password) < 8:
147
+ return False, "Password must be at least 8 characters long"
148
+ if not re.search(r'[A-Z]', password):
149
+ return False, "Password must contain at least one uppercase letter"
150
+ if not re.search(r'[a-z]', password):
151
+ return False, "Password must contain at least one lowercase letter"
152
+ if not re.search(r'[^A-Za-z0-9]', password):
153
+ return False, "Password must contain at least one special character"
154
+ return True, ""
155
+
156
+
157
+ def generate_compliant_password(length=12):
158
+ """Generates a secure password guaranteed to satisfy all 4 rules."""
159
+ import secrets, string
160
+ upper = secrets.choice(string.ascii_uppercase)
161
+ lower = secrets.choice(string.ascii_lowercase)
162
+ digit = secrets.choice(string.digits)
163
+ special = secrets.choice("!@#$%^&*")
164
+ chars = string.ascii_letters + string.digits + "!@#$%^&*"
165
+ remaining = [secrets.choice(chars) for _ in range(max(4, length) - 4)]
166
+ all_chars = [upper, lower, digit, special] + remaining
167
+ shuffled = []
168
+ pool = list(all_chars)
169
+ while pool:
170
+ idx = secrets.randbelow(len(pool))
171
+ shuffled.append(pool.pop(idx))
172
+ return "".join(shuffled)
173
+
174
+
175
+ def ensure_user_org(user):
176
+ """Ensures an org_admin or user with an organization has a valid Organization record."""
177
+ if user.org_id:
178
+ existing = db.session.get(Organization, user.org_id)
179
+ if existing:
180
+ return existing
181
+
182
+ clean_name = (user.email.split('@')[0].capitalize() if user.email else "LarShield") + " Organization"
183
+ new_org = Organization(name=clean_name)
184
+ db.session.add(new_org)
185
+ db.session.flush()
186
+ user.org_id = new_org.id
187
+ db.session.commit()
188
+ return new_org
189
+
190
+
191
+
192
  def token_required(f):
193
  @wraps(f)
194
  def decorated(*args, **kwargs):
 
325
 
326
  email_clean = str(raw_email).strip().lower()
327
 
328
+ valid_pwd, pwd_err = validate_password_strength(password)
329
+ if not valid_pwd:
330
+ return jsonify({'message': pwd_err}), 400
331
 
332
  if User.query.filter(func.lower(User.email) == email_clean).first():
333
  return jsonify({'message': 'User with this email already exists!'}), 400
 
483
  @auth_bp.route('/profile', methods=['GET'])
484
  @token_required
485
  def get_profile(current_user):
486
+ if current_user.role == 'org_admin' and not current_user.org_id:
487
+ ensure_user_org(current_user)
488
+
489
  org_name = None
490
  if current_user.org_id:
491
  org = db.session.get(Organization, current_user.org_id)
 
503
  'subscription_tier': current_user.subscription_tier,
504
  'subscription_status': getattr(current_user, 'subscription_status', 'active'),
505
  'created_at': current_user.created_at.isoformat() + 'Z' if current_user.created_at else None,
506
+ 'org_id': current_user.org_id
 
507
  }
508
  }), 200
509
 
 
521
  if not current_password or not new_password:
522
  return jsonify({'message': 'Missing required fields'}), 400
523
 
 
524
  is_valid = current_user.check_password(current_password)
 
525
 
526
  if not is_valid:
 
 
527
  return jsonify({'message': 'Incorrect current password'}), 401
528
 
529
+ valid_pwd, pwd_err = validate_password_strength(new_password)
530
+ if not valid_pwd:
531
+ return jsonify({'message': pwd_err}), 400
532
 
533
  current_user.set_password(new_password)
534
  db.session.commit()
 
544
  @auth_bp.route('/organizations/<org_id>/users', methods=['GET'])
545
  @token_required
546
  def get_org_users(current_user, org_id):
547
+ is_alias = str(org_id).strip().lower() in ('current', 'null', 'undefined', 'none', '')
548
+ if is_alias or (current_user.role == 'org_admin' and str(current_user.org_id) == str(org_id)):
549
+ if current_user.role == 'org_admin':
550
+ org = ensure_user_org(current_user)
551
+ target_org_id = org.id
552
+ else:
553
+ target_org_id = current_user.org_id or org_id
554
+ else:
555
+ target_org_id = org_id
556
+
557
+ if current_user.role not in ['super_admin', 'admin'] and str(current_user.org_id) != str(target_org_id):
558
  return jsonify({'message': 'Unauthorized access to organization users.'}), 403
559
 
560
+ org_users = User.query.filter_by(org_id=target_org_id).filter(User.role != 'super_admin').all()
561
 
562
  return jsonify({
563
  'users': [{
 
577
  if current_user.role not in ('org_admin', 'super_admin', 'admin'):
578
  return jsonify({'message': 'Permission denied'}), 403
579
 
580
+ data = request.get_json() or {}
581
  email = data.get('email')
582
  role = data.get('role', 'soc_analyst')
583
  first_name = data.get('first_name')
584
  last_name = data.get('last_name')
585
+ provided_password = data.get('password')
586
 
587
  if not email:
588
  return jsonify({'message': 'Email is required'}), 400
589
 
590
+ email_clean = str(email).strip().lower()
591
+ existing_user = User.query.filter(func.lower(User.email) == email_clean).first()
592
  if existing_user:
593
  return jsonify({'message': 'User already exists'}), 400
594
 
595
+ if provided_password and str(provided_password).strip():
596
+ valid_pwd, pwd_err = validate_password_strength(str(provided_password).strip())
597
+ if not valid_pwd:
598
+ return jsonify({'message': pwd_err}), 400
599
+ temp_password = str(provided_password).strip()
600
+ else:
601
+ temp_password = generate_compliant_password(12)
602
+
603
+ target_org_id = current_user.org_id
604
+ if current_user.role == 'org_admin':
605
+ org = ensure_user_org(current_user)
606
+ target_org_id = org.id
607
 
608
  try:
609
  new_user = User(
610
  id=str(uuid.uuid4()),
611
+ email=email_clean,
612
  role=role,
613
+ org_id=target_org_id,
614
  first_name=first_name,
615
  last_name=last_name
616
  )
617
  new_user.set_password(temp_password)
618
  db.session.add(new_user)
619
 
620
+ log = AuditLog(admin_id=current_user.id, action=f"Invited user {email_clean} with role {role}", target_id=target_org_id)
621
  db.session.add(log)
 
622
  db.session.commit()
623
 
624
  return jsonify({
 
628
  'id': new_user.id,
629
  'email': new_user.email,
630
  'role': new_user.role,
631
+ 'first_name': new_user.first_name,
632
+ 'last_name': new_user.last_name,
633
+ 'org_id': new_user.org_id,
634
+ 'created_at': new_user.created_at.isoformat() + 'Z' if new_user.created_at else None,
635
  'status': 'Active'
636
  }
637
  }), 201
 
700
  updates.append('email')
701
 
702
  if new_password:
703
+ valid_pwd, pwd_err = validate_password_strength(new_password)
704
+ if not valid_pwd:
705
+ return jsonify({'message': pwd_err}), 400
706
  user.set_password(new_password)
707
  updates.append('password')
708
 
 
874
  def manage_single_organization(current_user, org_id):
875
  if current_user.role not in ('super_admin', 'admin', 'org_admin'):
876
  return jsonify({'message': 'Permission denied'}), 403
877
+
878
+ is_alias = str(org_id).strip().lower() in ('current', 'null', 'undefined', 'none', '')
879
+
880
+ if current_user.role == 'org_admin':
881
+ if is_alias:
882
+ org = ensure_user_org(current_user)
883
+ target_org_id = org.id
884
+ else:
885
+ if not current_user.org_id:
886
+ ensure_user_org(current_user)
887
+ if str(current_user.org_id) != str(org_id):
888
+ return jsonify({'message': 'Permission denied: Cannot modify other organizations'}), 403
889
+ target_org_id = org_id
890
+ else:
891
+ # super_admin or admin
892
+ if is_alias:
893
+ if current_user.org_id:
894
+ target_org_id = current_user.org_id
895
+ else:
896
+ first_org = Organization.query.first()
897
+ if not first_org:
898
+ first_org = ensure_user_org(current_user)
899
+ target_org_id = first_org.id
900
+ else:
901
+ target_org_id = org_id
902
+
903
+ org = db.session.get(Organization, target_org_id)
904
  if not org:
905
  return jsonify({'message': 'Organization not found'}), 404
906
 
 
916
 
917
  # PUT method
918
  data = request.get_json() or {}
919
+ if 'name' in data and data['name']:
920
+ org.name = str(data['name']).strip()
921
 
922
  if 'tier' in data:
923
  if current_user.role not in ('super_admin', 'admin'):
 
927
  log = AuditLog(admin_id=current_user.id, action="Updated tenant configuration", target_id=org.id)
928
  db.session.add(log)
929
  db.session.commit()
930
+ return jsonify({'message': 'Tenant updated successfully', 'org_id': org.id, 'name': org.name}), 200
931
 
932
  @auth_bp.route('/organizations/logo', methods=['POST', 'DELETE'])
933
  @token_required
 
1127
  @auth_bp.route('/users', methods=['GET', 'POST'])
1128
  @token_required
1129
  def manage_users(current_user):
 
 
 
1130
  if request.method == 'GET':
1131
+ if current_user.role == 'org_admin':
1132
+ org = ensure_user_org(current_user)
1133
+ users = User.query.filter_by(org_id=org.id).filter(User.role != 'super_admin').all()
1134
+ elif current_user.role == 'admin':
1135
  users = User.query.filter(User.role != 'super_admin').all()
1136
+ elif current_user.role == 'super_admin':
1137
  users = User.query.all()
1138
+ else:
1139
+ return jsonify({'message': 'Permission denied'}), 403
1140
 
1141
  return jsonify({
1142
  'users': [{
 
1154
  }), 200
1155
 
1156
  # POST method - Create/Add new member
1157
+ if current_user.role not in ('super_admin', 'admin'):
1158
+ return jsonify({'message': 'Permission denied'}), 403
1159
+
1160
  if current_user.role == 'support_engineer':
1161
  return jsonify({'message': 'Permission denied. Support Engineers cannot create new members.'}), 403
1162
 
 
1174
  if existing:
1175
  return jsonify({'message': f'User with email "{email_clean}" already exists'}), 400
1176
 
1177
+ if password and str(password).strip():
1178
+ valid_pwd, pwd_err = validate_password_strength(str(password).strip())
1179
+ if not valid_pwd:
1180
+ return jsonify({'message': pwd_err}), 400
1181
+ temp_pw = str(password).strip()
1182
+ else:
1183
+ temp_pw = generate_compliant_password(12)
1184
 
1185
  target_org_id = None
1186
  if org_id and str(org_id).strip() and str(org_id).lower() not in ('none', 'null', ''):
 
1321
  'id': p.id,
1322
  'org_name': org_name,
1323
  'user_email': user_email,
1324
+ 'amount': p.amount / 100 if p.amount else 0, # Assuming amount is in cents/paise
 
 
 
1325
  'currency': p.currency,
1326
  'tier_id': p.tier_id,
1327
  'status': p.status,
 
1611
  if 'password' in data and data['password'] and str(data['password']).strip():
1612
  if current_user.role == 'support_engineer':
1613
  return jsonify({'message': 'Permission denied. Support Engineers cannot modify user passwords.'}), 403
1614
+ pwd = str(data['password']).strip()
1615
+ valid_pwd, pwd_err = validate_password_strength(pwd)
1616
+ if not valid_pwd:
1617
+ return jsonify({'message': pwd_err}), 400
1618
+ target.set_password(pwd)
1619
  if 'role' in data and data['role']:
1620
  target.role = data['role']
1621
  if 'org_id' in data: