-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathuser.py
More file actions
685 lines (606 loc) · 24.6 KB
/
user.py
File metadata and controls
685 lines (606 loc) · 24.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
"""User API."""
# Standard Python Libraries
from datetime import datetime
import os
# Third-Party Libraries
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Prefetch
from django.forms import model_to_dict
from fastapi import HTTPException
from xfd_mini_dl.models import Organization, Role, User
from ..auth import (
can_access_user,
is_analytics_user,
is_global_view_admin,
is_global_write_admin,
is_org_admin,
is_regional_admin,
matches_user_region,
)
from ..helpers.email import (
send_invite_email,
send_registration_approved_email,
send_registration_denied_email,
)
from ..helpers.regionStateMap import REGION_STATE_MAP
from ..helpers.uuid_helpers import is_valid_uuid
from ..tools.serializers import serialize_user
# GET: /users/me
def get_me(current_user):
"""Get current user."""
try:
# Fetch the user and related objects from the database
user = User.objects.prefetch_related(
Prefetch("roles", queryset=Role.objects.select_related("organization")),
Prefetch("api_keys"),
).get(id=str(current_user.id))
# Convert the user object to a dictionary
user_dict = model_to_dict(user)
# Add id: model_to_dict does not automatically include
user_dict["id"] = str(user.id)
# Include roles with their related organization
user_dict["roles"] = [
{
"id": role.id,
"role": role.role,
"approved": role.approved,
"organization": {
**model_to_dict(
role.organization,
fields=[
"acronym",
"name",
"root_domains",
"ip_blocks",
"is_passive",
"pending_domains",
"country",
"state",
"region_id",
"state_fips",
"state_name",
"county",
"county_fips",
"type",
"parent",
"created_by",
],
),
"id": str(role.organization.id), # Explicitly add the ID
}
if role.organization
else None,
}
for role in user.roles.all()
]
# Include API keys
user_dict["api_keys"] = list(
user.api_keys.values(
"id", "created_at", "updated_at", "last_used", "hashed_key", "last_four"
)
)
return user_dict
except User.DoesNotExist:
raise HTTPException(status_code=404, detail="User not found")
except Exception as e:
print(e)
raise HTTPException(status_code=500, detail="Unknown error")
# POST: /users/me/acceptTerms
def accept_terms(version_data, current_user):
"""Accept the latest terms of service."""
try:
version = version_data.version
if not version:
raise HTTPException(
status_code=400, detail="Missing version in request body."
)
current_user.date_accepted_terms = datetime.now()
current_user.accepted_terms_version = version
current_user.save()
return {
"id": str(current_user.id),
"cognito_id": current_user.cognito_id,
"okta_id": current_user.okta_id,
"login_gov_id": current_user.login_gov_id,
"created_at": current_user.created_at.isoformat()
if current_user.created_at
else None,
"updated_at": current_user.updated_at.isoformat()
if current_user.updated_at
else None,
"first_name": current_user.first_name,
"last_name": current_user.last_name,
"full_name": current_user.full_name,
"email": current_user.email,
"invite_pending": current_user.invite_pending,
"login_blocked_by_maintenance": current_user.login_blocked_by_maintenance,
"date_accepted_terms": current_user.date_accepted_terms.isoformat()
if current_user.date_accepted_terms
else None,
"accepted_terms_version": current_user.accepted_terms_version,
"last_logged_in": current_user.last_logged_in.isoformat()
if current_user.last_logged_in
else None,
"user_type": current_user.user_type,
"region_id": current_user.region_id,
"state": current_user.state,
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# DELETE: /users/{user_id}
def delete_user(target_user_id, current_user):
"""Delete a user by ID."""
# Validate that the user ID is a valid UUID
if not target_user_id or not is_valid_uuid(target_user_id):
raise HTTPException(status_code=404, detail="User not found")
# Check if the current user has permission to access/update this user
if not can_access_user(current_user, target_user_id):
raise HTTPException(status_code=403, detail="Unauthorized access.")
try:
# Fetch the user to be deleted
target_user = User.objects.prefetch_related("roles").get(id=target_user_id)
# Delete all associated roles before deleting the user
target_user.roles.all().delete()
# Delete the user
target_user.delete()
# Return success response
return {
"status": "success",
"message": f"User {target_user_id} and associated roles have been deleted successfully.",
"user_deleted": serialize_user(target_user),
}
except User.DoesNotExist:
raise HTTPException(status_code=404, detail="User not found.")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error deleting user: {str(e)}")
# GET: /users
def get_users(current_user):
"""Retrieve a list of all users."""
try:
# Check if user is a regional admin or global admin
if (
not is_global_view_admin(current_user)
| is_regional_admin(current_user)
| is_analytics_user(current_user)
):
raise HTTPException(status_code=401, detail="Unauthorized")
users = User.objects.all().prefetch_related("roles__organization")
# Return the updated user details
return [
{
"id": str(user.id),
"created_at": user.created_at.isoformat(),
"updated_at": user.updated_at.isoformat(),
"first_name": user.first_name,
"last_name": user.last_name,
"full_name": user.full_name,
"email": user.email,
"region_id": user.region_id,
"state": user.state,
"user_type": user.user_type,
"last_logged_in": user.last_logged_in,
"date_approved": user.date_approved,
"approved_by": {
"id": str(user.approved_by.id),
"full_name": str(user.approved_by.full_name),
"email": str(user.approved_by.email),
}
if user.approved_by
else None,
"accepted_terms_version": user.accepted_terms_version,
"date_accepted_terms": user.date_accepted_terms,
"roles": [
{
"id": str(role.id),
"approved": role.approved,
"role": role.role,
"organization": {
"id": str(role.organization.id),
"name": role.organization.name,
}
if role.organization
else None,
}
for role in user.roles.all()
],
}
for user in users
]
except HTTPException as http_exc:
raise http_exc
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# GET: /users/region_id/{region_id}
def get_users_by_region_id(region_id, current_user):
"""List users with specific region_id."""
try:
if not is_regional_admin(current_user) | is_analytics_user(current_user):
raise HTTPException(status_code=401, detail="Unauthorized")
if not region_id:
raise HTTPException(
status_code=400, detail="Missing region_id in path parameters"
)
users = User.objects.filter(region_id=region_id).prefetch_related(
"roles__organization"
)
if users:
return [
{
"id": str(user.id),
"created_at": user.created_at.isoformat(),
"updated_at": user.updated_at.isoformat(),
"first_name": user.first_name,
"last_name": user.last_name,
"full_name": user.full_name,
"email": user.email,
"region_id": user.region_id,
"state": user.state,
"user_type": user.user_type,
"last_logged_in": user.last_logged_in,
"accepted_terms_version": user.accepted_terms_version,
"roles": [
{
"id": str(role.id),
"approved": role.approved,
"role": role.role,
"organization": {
"id": str(role.organization.id),
"name": role.organization.name,
}
if role.organization
else None,
}
for role in user.roles.all()
],
}
for user in users
]
else:
raise HTTPException(
status_code=404, detail="No users found for the specified region_id"
)
except HTTPException as http_exc:
raise http_exc
except Exception as e:
print(e)
raise HTTPException(status_code=500, detail=str(e))
# GET: /users/state/{state}
def get_users_by_state(state, current_user):
"""List users with specific state."""
try:
if not is_regional_admin(current_user):
raise HTTPException(status_code=401, detail="Unauthorized")
if not state:
raise HTTPException(
status_code=400, detail="Missing state in path parameters"
)
users = User.objects.filter(state=state).prefetch_related("roles__organization")
if users:
return [
{
"id": str(user.id),
"created_at": user.created_at.isoformat(),
"updated_at": user.updated_at.isoformat(),
"first_name": user.first_name,
"last_name": user.last_name,
"full_name": user.full_name,
"email": user.email,
"region_id": user.region_id,
"state": user.state,
"user_type": user.user_type,
"last_logged_in": user.last_logged_in,
"accepted_terms_version": user.accepted_terms_version,
"roles": [
{
"id": str(role.id),
"approved": role.approved,
"role": role.role,
"organization": {
"id": str(role.organization.id),
"name": role.organization.name,
}
if role.organization
else None,
}
for role in user.roles.all()
],
}
for user in users
]
else:
raise HTTPException(
status_code=404, detail="No users found for the specified state"
)
except HTTPException as http_exc:
raise http_exc
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# GET: /v2/users
def get_users_v2(state, region_id, invite_pending, current_user):
"""Retrieve a list of users based on optional filter parameters."""
try:
# Check if user is a regional admin or global admin
if (
not is_regional_admin(current_user)
| is_global_view_admin(current_user)
| is_analytics_user(current_user)
):
raise HTTPException(status_code=401, detail="Unauthorized")
filters = {}
if state is not None:
filters["state"] = state
if region_id is not None:
filters["region_id"] = region_id
if invite_pending is not None:
# Convert string to boolean if needed
if isinstance(invite_pending, str):
invite_pending = invite_pending.lower() == "true"
filters["invite_pending"] = invite_pending
users = User.objects.filter(**filters).prefetch_related("roles__organization")
# Return the updated user details
return [
{
"id": str(user.id),
"cognito_use_case_description": user.cognito_use_case_description,
"created_at": user.created_at.isoformat(),
"updated_at": user.updated_at.isoformat(),
"first_name": user.first_name,
"last_name": user.last_name,
"full_name": user.full_name,
"email": user.email,
"region_id": user.region_id,
"state": user.state,
"user_type": user.user_type,
"last_logged_in": user.last_logged_in,
"date_approved": user.date_approved,
"approved_by": {
"id": str(user.approved_by.id),
"full_name": str(user.approved_by.full_name),
"email": str(user.approved_by.email),
}
if user.approved_by
else None,
"accepted_terms_version": user.accepted_terms_version,
"roles": [
{
"id": str(role.id),
"approved": role.approved,
"role": role.role,
"organization": {
"id": str(role.organization.id),
"name": role.organization.name,
}
if role.organization
else None,
}
for role in user.roles.all()
],
}
for user in users
]
except HTTPException as http_exc:
raise http_exc
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# PUT: /v2/users/{user_id}
def update_user_v2(user_id, user_data, current_user):
"""Update a particular user."""
try:
# Validate that the user ID is a valid UUID
if not user_id or not is_valid_uuid(user_id):
raise HTTPException(status_code=404, detail="User not found")
# Check if the current user has permission to access/update this user
if not can_access_user(current_user, user_id):
raise HTTPException(status_code=403, detail="Unauthorized access.")
# Fetch the user to be updated
try:
user = User.objects.prefetch_related("roles").get(id=user_id)
except User.DoesNotExist:
raise HTTPException(status_code=404, detail="User not found")
# Global admins only can update the userType
if not is_global_write_admin(current_user) and user_data.user_type:
raise HTTPException(
status_code=403, detail="Only global admins can update userType."
)
# Update fields
if user_data.state:
user.region_id = REGION_STATE_MAP.get(user_data.state)
print(user_data.dict())
# Check for invitePending explicitly
if user_data.invite_pending is not None:
user.invite_pending = user_data.invite_pending
for field, value in user_data.dict(exclude_defaults=True).items():
setattr(user, field, value)
# Save the updated user
user.save()
# Fetch updated user with roles and related data
updated_user = User.objects.prefetch_related("roles__organization").get(
id=user_id
)
# Return the updated user details
return {
"id": str(updated_user.id),
"created_at": updated_user.created_at.isoformat(),
"updated_at": updated_user.updated_at.isoformat(),
"first_name": updated_user.first_name,
"last_name": updated_user.last_name,
"full_name": user.full_name,
"email": updated_user.email,
"region_id": updated_user.region_id,
"state": updated_user.state,
"user_type": updated_user.user_type,
"last_logged_in": user.last_logged_in,
"accepted_terms_version": user.accepted_terms_version,
"roles": [
{
"id": str(role.id),
"approved": role.approved,
"role": role.role,
"organization": {
"id": str(role.organization.id),
"name": role.organization.name,
}
if role.organization
else None,
}
for role in updated_user.roles.all()
],
}
except HTTPException as http_exc:
raise http_exc
except Exception as e:
print("Error updating user: {}".format(e))
raise HTTPException(status_code=500, detail="An unexpected error occurred.")
# PUT: /users/{user_id}/register/approve
def approve_user_registration(user_id, current_user):
"""Approve a registered user."""
if not is_valid_uuid(user_id):
raise HTTPException(status_code=404, detail="Invalid user ID.")
try:
# Retrieve the user by ID
user = User.objects.get(id=user_id)
user.date_approved = datetime.now()
user.approved_by = current_user
user.save()
except ObjectDoesNotExist:
raise HTTPException(status_code=404, detail="User not found.")
# Ensure authorizer's region matches the user's region
if not matches_user_region(current_user, user.region_id):
raise HTTPException(status_code=403, detail="Unauthorized region access.")
# Send email notification
try:
send_registration_approved_email(
user.email,
subject="CyHy Dashboard Registration Approved",
first_name=user.first_name,
last_name=user.last_name,
template="crossfeed_approval_notification.html",
)
except HTTPException as http_exc:
raise http_exc
except Exception as e:
raise HTTPException(
status_code=500, detail="Failed to send email: {}".format(str(e))
)
return {
"status_code": 200,
"body": "User registration approved.",
}
# PUT: /users/{user_id}/register/deny
def deny_user_registration(user_id: str, current_user: User):
"""Deny a user's registration by user ID."""
# Validate UUID format for the user_id
if not is_valid_uuid(user_id):
raise HTTPException(status_code=404, detail="User not found.")
try:
# Retrieve the user object
user = User.objects.filter(id=user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found.")
# Ensure authorizer's region matches the user's region
if not matches_user_region(current_user, user.region_id):
raise HTTPException(status_code=403, detail="Unauthorized region access.")
# Send registration denial email to the user
send_registration_denied_email(
user.email,
subject="CyHy Dashboard Registration Denied",
first_name=user.first_name,
last_name=user.last_name,
template="crossfeed_denial_notification.html",
)
return {"status_code": 200, "body": "User registration denied."}
except HTTPException as http_exc:
raise http_exc
except ObjectDoesNotExist:
raise HTTPException(status_code=404, detail="User not found.")
except Exception as e:
print("Error denying registration: {}".format(e))
raise HTTPException(
status_code=500, detail="Error processing registration denial."
)
# POST: /users
def invite(new_user_data, current_user):
"""Invite a user."""
try:
# Validate permissions
if new_user_data.organization:
if not is_org_admin(current_user, new_user_data.organization):
raise HTTPException(status_code=403, detail="Unauthorized access.")
else:
if not is_global_write_admin(current_user):
raise HTTPException(status_code=403, detail="Unauthorized access.")
# Non-global admins cannot set userType
if not is_global_write_admin(current_user) and new_user_data.user_type:
raise HTTPException(status_code=403, detail="Unauthorized access.")
# Lowercase the email for consistency
new_user_data.email = new_user_data.email.lower()
# Map state to region ID if state is provided
if new_user_data.state:
new_user_data.region_id = REGION_STATE_MAP.get(new_user_data.state)
# Check if the user already exists
user = User.objects.filter(email=new_user_data.email).first()
organization = (
Organization.objects.filter(id=new_user_data.organization).first()
if new_user_data.organization
else None
)
if not user:
# Create a new user if they do not exist
user = User.objects.create(
invite_pending=True,
**new_user_data.dict(
exclude_unset=True,
exclude={"organization_admin", "organization", "user_type"},
),
)
if not os.getenv("IS_LOCAL"):
send_invite_email(user.email, organization)
elif not user.first_name and not user.last_name:
# Update first and last name if the user exists but has no name set
user.first_name = new_user_data.first_name
user.last_name = new_user_data.last_name
user.save()
# Always update userType if specified
if new_user_data.user_type:
user.user_type = new_user_data.user_type.value
user.save()
# Assign role if an organization is specified
if organization:
Role.objects.update_or_create(
user=user,
organization=organization,
defaults={
"approved": True,
"created_by": current_user,
"approved_by": current_user,
"role": "admin" if new_user_data.organization_admin else "user",
},
)
# Return the updated user with relevant details
return {
"id": str(user.id),
"first_name": user.first_name,
"last_name": user.last_name,
"email": user.email,
"user_type": user.user_type,
"roles": [
{
"id": str(role.id),
"role": role.role,
"approved": role.approved,
"organization": {
"id": str(role.organization.id),
"name": role.organization.name,
}
if role.organization
else {},
}
for role in user.roles.select_related("organization").all()
],
"invite_pending": user.invite_pending,
}
except HTTPException as http_exc:
raise http_exc
except Exception as e:
print("Error inviting user: {}".format(e))
raise HTTPException(status_code=500, detail="Error inviting user.")