-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathusers.py
More file actions
1008 lines (850 loc) · 30 KB
/
users.py
File metadata and controls
1008 lines (850 loc) · 30 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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import click
from pandas import DataFrame
from pandas import json_normalize
from py42.exceptions import Py42NotFoundError
from py42.exceptions import Py42UserRiskProfileNotFound
from code42cli.bulk import generate_template_cmd_factory
from code42cli.bulk import run_bulk_process
from code42cli.click_ext.groups import OrderedGroup
from code42cli.click_ext.options import incompatible_with
from code42cli.errors import Code42CLIError
from code42cli.errors import UserDoesNotExistError
from code42cli.file_readers import read_csv_arg
from code42cli.options import format_option
from code42cli.options import sdk_options
from code42cli.output_formats import DataFrameOutputFormatter
from code42cli.output_formats import OutputFormat
from code42cli.output_formats import OutputFormatter
from code42cli.worker import create_worker_stats
username_arg = click.argument("username")
org_uid_option = click.option(
"--org-uid",
help="Limit users to only those in the organization you specify. Note that child orgs are included.",
)
active_option = click.option(
"--active",
is_flag=True,
help="Limits results to only active users.",
default=None,
)
inactive_option = click.option(
"--inactive",
is_flag=True,
help="Limits results to only deactivated users.",
cls=incompatible_with("active"),
)
user_id_option = click.option(
"--user-id", help="The unique identifier of the user to be modified.", required=True
)
org_id_option = click.option(
"--org-id",
help="The unique identifier (UID) for the organization to which the user will be moved.",
required=True,
)
include_legal_hold_option = click.option(
"--include-legal-hold-membership",
default=False,
is_flag=True,
help="Include legal hold membership in output.",
)
def role_name_option(help):
return click.option("--role-name", help=help)
def username_option(help, required=False):
return click.option("--username", help=help, required=required)
@click.group(cls=OrderedGroup)
@sdk_options(hidden=True)
def users(state):
"""Manage users within your Code42 environment."""
pass
@users.command(name="list")
@org_uid_option
@role_name_option("Limit results to only users having the specified role.")
@active_option
@inactive_option
@include_legal_hold_option
@click.option(
"--include-roles", default=False, is_flag=True, help="Include user roles."
)
@format_option
@sdk_options()
def list_users(
state,
org_uid,
role_name,
active,
inactive,
include_legal_hold_membership,
include_roles,
format,
):
"""List users in your Code42 environment."""
if inactive:
active = False
role_id = _get_role_id(state.sdk, role_name) if role_name else None
columns = (
["userUid", "status", "username", "orgUid"]
if format == OutputFormat.TABLE
else None
)
if include_roles and columns:
columns.append("roles")
df = _get_users_dataframe(
state.sdk, columns, org_uid, role_id, active, include_roles
)
if include_legal_hold_membership:
df = _add_legal_hold_membership_to_user_dataframe(state.sdk, df)
formatter = DataFrameOutputFormatter(format)
formatter.echo_formatted_dataframes(df)
@users.command("show")
@username_arg
@include_legal_hold_option
@format_option
@sdk_options()
def show_user(state, username, include_legal_hold_membership, format):
"""Show user details."""
columns = (
["userUid", "status", "username", "orgUid", "roles"]
if format == OutputFormat.TABLE
else None
)
response = state.sdk.users.get_by_username(username, incRoles=True)
df = DataFrame.from_records(response["users"], columns=columns)
if include_legal_hold_membership and not df.empty:
df = _add_legal_hold_membership_to_user_dataframe(state.sdk, df)
formatter = DataFrameOutputFormatter(format)
formatter.echo_formatted_dataframes(df)
@users.command(name="list-risk-profiles")
@active_option
@inactive_option
@click.option(
"--manager-id",
help="Matches users whose manager has the given Code42 user ID.",
)
@click.option("--department", help="Matches users in the given department.")
@click.option("--employment-type", help="Matches users with the given employment type.")
@click.option("-r", "--region", help="Matches users the given region (state).")
@format_option
@sdk_options()
def list_user_risk_profiles(
state,
active,
inactive,
manager_id,
department,
employment_type,
region,
format,
):
"""List users in your Code42 environment."""
if inactive:
active = False
columns = (
[
"userId",
"username",
"active",
"department",
"employmentType",
"region",
"endDate",
]
if format == OutputFormat.TABLE
else None
)
users_generator = state.sdk.userriskprofile.get_all(
active=active,
manager_id=manager_id,
department=department,
employment_type=employment_type,
region=region,
)
users_list = []
for page in users_generator:
users_list.extend(page["userRiskProfiles"])
df = DataFrame.from_records(users_list, columns=columns)
formatter = DataFrameOutputFormatter(format)
formatter.echo_formatted_dataframes(df)
@users.command("show-risk-profile")
@username_arg
@format_option
@sdk_options()
def show_user_risk_profile(state, username, format):
"""Show user risk profile details."""
formatter = OutputFormatter(format)
response = state.sdk.userriskprofile.get_by_username(username)
formatter.echo_formatted_list([response.data])
@users.command()
@username_option("Username of the target user.")
@role_name_option("Name of role to add.")
@sdk_options()
def add_role(state, username, role_name):
"""Add the specified role to the user with the specified username."""
_add_user_role(state.sdk, username, role_name)
@users.command()
@role_name_option("Name of role to remove.")
@username_option("Username of the target user.")
@sdk_options()
def remove_role(state, username, role_name):
"""Remove the specified role to the user with the specified username."""
_remove_user_role(state.sdk, role_name, username)
@users.command(name="update")
@user_id_option
@click.option("--username", help="The new username for the user.")
@click.option("--password", help="The new password for the user.")
@click.option("--email", help="The new email for the user.")
@click.option("--first-name", help="The new first name for the user.")
@click.option("--last-name", help="The new last name for the user.")
@click.option("--notes", help="Notes about this user.")
@click.option(
"--archive-size-quota", help="The total size (in bytes) allowed for this user."
)
@sdk_options()
def update_user(
state,
user_id,
username,
email,
password,
first_name,
last_name,
notes,
archive_size_quota,
):
"""Update a user with the specified unique identifier."""
_update_user(
state.sdk,
user_id,
username,
email,
password,
first_name,
last_name,
notes,
archive_size_quota,
)
@users.command()
@username_arg
@sdk_options()
def deactivate(state, username):
"""Deactivate a user."""
sdk = state.sdk
_deactivate_user(sdk, username)
@users.command()
@username_arg
@sdk_options()
def reactivate(state, username):
"""Reactivate a user."""
sdk = state.sdk
_reactivate_user(sdk, username)
_bulk_user_update_headers = [
"user_id",
"username",
"email",
"password",
"first_name",
"last_name",
"notes",
"archive_size_quota",
]
_bulk_user_move_headers = ["username", "org_id"]
_bulk_user_roles_headers = ["username", "role_name"]
_bulk_user_alias_headers = ["username", "alias"]
_bulk_user_risk_profile_headers = ["username", "start_date", "end_date", "notes"]
_bulk_user_activation_headers = ["username"]
@users.command(name="move")
@username_option("The username of the user to move.", required=True)
@org_id_option
@sdk_options()
def change_organization(state, username, org_id):
"""Change the organization of the user with the given username
to the org with the given org UID."""
_change_organization(state.sdk, username, org_id)
@users.command()
@click.argument("username")
@click.argument("alias")
@sdk_options()
def add_alias(state, username, alias):
"""Add a cloud alias for a given user.
A cloud alias is the username an employee uses to access cloud services such as Google Drive or Box. Adding a cloud alias allows Incydr to link a user's cloud activity with their Code42 username. Each user has a default cloud alias of their Code42 username. You can add one additional alias."""
_add_cloud_alias(state.sdk, username, alias)
@users.command()
@click.argument("username")
@click.argument("alias")
@sdk_options()
def remove_alias(state, username, alias):
"""Remove a cloud alias for a given user."""
_remove_cloud_alias(state.sdk, username, alias)
@users.command()
@click.argument("username")
@click.argument(
"date", type=click.DateTime(formats=["%Y-%m-%d"]), required=False, metavar="DATE"
)
@click.option("--clear", is_flag=True, help="Clears the current `start_date` value.")
@sdk_options()
def update_start_date(state, username, date, clear):
"""Sets the `start_date` on a User's risk profile (useful for users on the New Hire Watchlist).
Date format: %Y-%m-%d"""
if not date and not clear:
raise Code42CLIError("Must supply DATE argument if --clear is not used.")
if clear:
date = ""
user_id = _get_user(state.sdk, username)["userId"]
state.sdk.userriskprofile.update(user_id, start_date=date)
@users.command()
@click.argument("username")
@click.argument("date", type=click.DateTime(formats=["%Y-%m-%d"]), required=False)
@click.option("--clear", is_flag=True, help="Clears the current `end_date` value.")
@sdk_options()
def update_departure_date(state, username, date, clear):
"""Sets the `end_date` on a User's risk profile (useful for users on the Departing Watchlist). Date format: %Y-%m-%d"""
if not date and not clear:
raise Code42CLIError("Must supply DATE argument if --clear is not used.")
if clear:
date = ""
user_id = _get_user(state.sdk, username)["userId"]
state.sdk.userriskprofile.update(user_id, end_date=date)
@users.command()
@click.argument("username")
@click.argument("note", required=False)
@click.option("--clear", is_flag=True, help="Clears the current `notes` value.")
@click.option(
"--append",
is_flag=True,
help="Appends provided note to existing note text as a new line.",
)
@sdk_options()
def update_risk_profile_notes(state, username, note, clear, append):
"""Sets the `notes` value of a User's risk profile.
WARNING: Overwrites any existing note value."""
if not note and not clear:
raise Code42CLIError("Must supply NOTE argument if --clear is not used.")
user = _get_user(state.sdk, username)
user_id = user["userId"]
if append and user["notes"]:
note = user["notes"] + f"\n\n{note}"
if clear:
note = ""
state.sdk.userriskprofile.update(user_id, notes=note)
@users.command()
@click.argument("username")
@sdk_options()
def list_aliases(state, username):
"""List the cloud aliases for a given user.
Each user has a default cloud alias of their Code42 username with up to one additional alias."""
user = _get_user(state.sdk, username)
aliases = user["cloudAliases"]
if aliases:
click.echo(aliases)
else:
click.echo(f"No cloud aliases for user '{username}' found.")
@users.group(cls=OrderedGroup)
@sdk_options(hidden=True)
def orgs(state):
"""Tools for viewing user orgs."""
pass
def _get_orgs_header():
return {
"orgId": "ID",
"orgUid": "UID",
"orgName": "Name",
"status": "Status",
"parentOrgId": "Parent ID",
"parentOrgUid": "Parent UID",
"type": "Type",
"classification": "Classification",
"creationDate": "Creation Date",
"settings": "Settings",
}
@orgs.command(name="list")
@format_option
@sdk_options()
def list_orgs(
state,
format,
):
"""List all orgs."""
pages = state.sdk.orgs.get_all()
formatter = OutputFormatter(format, _get_orgs_header())
orgs = [org for page in pages for org in page["orgs"]]
if orgs:
formatter.echo_formatted_list(orgs)
else:
click.echo("No orgs found.")
@orgs.command(name="show")
@click.argument("org-uid")
@format_option
@sdk_options()
def show_org(
state,
org_uid,
format,
):
"""Show org details."""
formatter = OutputFormatter(format)
try:
response = state.sdk.orgs.get_by_uid(org_uid)
formatter.echo_formatted_list([response.data])
except Py42NotFoundError:
raise Code42CLIError(f"Invalid org UID {org_uid}.")
@users.group(cls=OrderedGroup)
@sdk_options(hidden=True)
def bulk(state):
"""Tools for managing users in bulk."""
pass
users_generate_template = generate_template_cmd_factory(
group_name="users",
commands_dict={
"update": _bulk_user_update_headers,
"move": _bulk_user_move_headers,
"add-alias": _bulk_user_alias_headers,
"remove-alias": _bulk_user_alias_headers,
"update-risk-profile": _bulk_user_risk_profile_headers,
},
help_message="Generate the CSV template needed for bulk user commands.",
)
bulk.add_command(users_generate_template)
@bulk.command(
name="update",
help="Update a list of users from the provided CSV in format: "
f"{','.join(_bulk_user_update_headers)}",
)
@read_csv_arg(headers=_bulk_user_update_headers)
@format_option
@sdk_options()
def bulk_update(state, csv_rows, format):
"""Update a list of users from the provided CSV."""
# Initialize the SDK before starting any bulk processes
# to prevent multiple instances and having to enter 2fa multiple times.
sdk = state.sdk
csv_rows[0]["updated"] = "False"
formatter = OutputFormatter(format, {key: key for key in csv_rows[0].keys()})
stats = create_worker_stats(len(csv_rows))
def handle_row(**row):
try:
_update_user(
sdk, **{key: row[key] for key in row.keys() if key != "updated"}
)
row["updated"] = "True"
except Exception as err:
row["updated"] = f"False: {err}"
stats.increment_total_errors()
return row
result_rows = run_bulk_process(
handle_row,
csv_rows,
progress_label="Updating users:",
stats=stats,
raise_global_error=False,
)
formatter.echo_formatted_list(result_rows)
@bulk.command(
name="move",
help="Change the organization of the list of users from the provided CSV in format: "
f"{','.join(_bulk_user_move_headers)}",
)
@read_csv_arg(headers=_bulk_user_move_headers)
@format_option
@sdk_options()
def bulk_move(state, csv_rows, format):
"""Change the organization of the list of users from the provided CSV."""
# Initialize the SDK before starting any bulk processes
# to prevent multiple instances and having to enter 2fa multiple times.
sdk = state.sdk
csv_rows[0]["moved"] = "False"
formatter = OutputFormatter(format, {key: key for key in csv_rows[0].keys()})
stats = create_worker_stats(len(csv_rows))
def handle_row(**row):
try:
_change_organization(
sdk, **{key: row[key] for key in row.keys() if key != "moved"}
)
row["moved"] = "True"
except Exception as err:
row["moved"] = f"False: {err}"
stats.increment_total_errors()
return row
result_rows = run_bulk_process(
handle_row,
csv_rows,
progress_label="Moving users:",
stats=stats,
raise_global_error=False,
)
formatter.echo_formatted_list(result_rows)
@bulk.command(
name="deactivate",
help=f"Deactivate a list of users from the provided CSV in format: {','.join(_bulk_user_activation_headers)}",
)
@read_csv_arg(headers=_bulk_user_activation_headers)
@format_option
@sdk_options()
def bulk_deactivate(state, csv_rows, format):
"""Deactivate a list of users."""
# Initialize the SDK before starting any bulk processes
# to prevent multiple instances and having to enter 2fa multiple times.
sdk = state.sdk
csv_rows[0]["deactivated"] = "False"
formatter = OutputFormatter(format, {key: key for key in csv_rows[0].keys()})
stats = create_worker_stats(len(csv_rows))
def handle_row(**row):
try:
_deactivate_user(
sdk, **{key: row[key] for key in row.keys() if key != "deactivated"}
)
row["deactivated"] = "True"
except Exception as err:
row["deactivated"] = f"False: {err}"
stats.increment_total_errors()
return row
result_rows = run_bulk_process(
handle_row,
csv_rows,
progress_label="Deactivating users:",
stats=stats,
raise_global_error=False,
)
formatter.echo_formatted_list(result_rows)
@bulk.command(
name="reactivate",
help=f"Reactivate a list of users from the provided CSV in format: {','.join(_bulk_user_activation_headers)}",
)
@read_csv_arg(headers=_bulk_user_activation_headers)
@format_option
@sdk_options()
def bulk_reactivate(state, csv_rows, format):
"""Reactivate a list of users."""
# Initialize the SDK before starting any bulk processes
# to prevent multiple instances and having to enter 2fa multiple times.
sdk = state.sdk
csv_rows[0]["reactivated"] = "False"
formatter = OutputFormatter(format, {key: key for key in csv_rows[0].keys()})
stats = create_worker_stats(len(csv_rows))
def handle_row(**row):
try:
_reactivate_user(
sdk, **{key: row[key] for key in row.keys() if key != "reactivated"}
)
row["reactivated"] = "True"
except Exception as err:
row["reactivated"] = f"False: {err}"
stats.increment_total_errors()
return row
result_rows = run_bulk_process(
handle_row,
csv_rows,
progress_label="Reactivating users:",
stats=stats,
raise_global_error=False,
)
formatter.echo_formatted_list(result_rows)
@bulk.command(
name="add-roles",
help=f"Add roles to a list of users from the provided CSV in format: {','.join(_bulk_user_roles_headers)}",
)
@read_csv_arg(headers=_bulk_user_roles_headers)
@format_option
@sdk_options()
def bulk_add_roles(state, csv_rows, format):
"""Bulk add roles to a list of users."""
# Initialize the SDK before starting any bulk processes
# to prevent multiple instances and having to enter 2fa multiple times.
sdk = state.sdk
status_header = "role added"
csv_rows[0][status_header] = "False"
formatter = OutputFormatter(format, {key: key for key in csv_rows[0].keys()})
stats = create_worker_stats(len(csv_rows))
def handle_row(**row):
try:
_add_user_role(
sdk, **{key: row[key] for key in row.keys() if key != status_header}
)
row[status_header] = "True"
except Exception as err:
row[status_header] = f"False: {err}"
stats.increment_total_errors()
return row
result_rows = run_bulk_process(
handle_row,
csv_rows,
progress_label="Adding roles to users:",
stats=stats,
raise_global_error=False,
)
formatter.echo_formatted_list(result_rows)
@bulk.command(
name="remove-roles",
help=f"Remove roles from a list of users from the provided CSV in format: {','.join(_bulk_user_roles_headers)}",
)
@read_csv_arg(headers=_bulk_user_roles_headers)
@format_option
@sdk_options()
def bulk_remove_roles(state, csv_rows, format):
"""Bulk remove roles from a list of users."""
# Initialize the SDK before starting any bulk processes
# to prevent multiple instances and having to enter 2fa multiple times.
sdk = state.sdk
success_header = "role removed"
csv_rows[0][success_header] = "False"
formatter = OutputFormatter(format, {key: key for key in csv_rows[0].keys()})
stats = create_worker_stats(len(csv_rows))
def handle_row(**row):
try:
_remove_user_role(
sdk, **{key: row[key] for key in row.keys() if key != success_header}
)
row[success_header] = "True"
except Exception as err:
row[success_header] = f"False: {err}"
stats.increment_total_errors()
return row
result_rows = run_bulk_process(
handle_row,
csv_rows,
progress_label="Removing roles from users:",
stats=stats,
raise_global_error=False,
)
formatter.echo_formatted_list(result_rows)
@bulk.command(
name="add-alias",
help=f"Add aliases to a list of users from the provided CSV in format: {','.join(_bulk_user_alias_headers)}.\n\nA cloud alias is the username an employee uses to access cloud services such as Google Drive or Box. Adding a cloud alias allows Incydr to link a user's cloud activity with their Code42 username. Each user has a default cloud alias of their Code42 username. You can add one additional alias.",
)
@read_csv_arg(headers=_bulk_user_alias_headers)
@format_option
@sdk_options()
def bulk_add_alias(state, csv_rows, format):
"""Bulk add aliases to users"""
# Initialize the SDK before starting any bulk processes
# to prevent multiple instances and having to enter 2fa multiple times.
sdk = state.sdk
success_header = "alias added"
csv_rows[0][success_header] = "False"
formatter = OutputFormatter(format, {key: key for key in csv_rows[0].keys()})
stats = create_worker_stats(len(csv_rows))
def handle_row(**row):
try:
_add_cloud_alias(
sdk, **{key: row[key] for key in row.keys() if key != success_header}
)
row[success_header] = "True"
except Exception as err:
row[success_header] = f"False: {err}"
stats.increment_total_errors()
return row
result_rows = run_bulk_process(
handle_row,
csv_rows,
progress_label="Adding aliases to users:",
stats=stats,
raise_global_error=False,
)
formatter.echo_formatted_list(result_rows)
@bulk.command(
name="remove-alias",
help=f"Remove aliases from a list of users from the provided CSV in format: {','.join(_bulk_user_alias_headers)}",
)
@read_csv_arg(headers=_bulk_user_alias_headers)
@format_option
@sdk_options()
def bulk_remove_alias(state, csv_rows, format):
"""Bulk remove aliases from users"""
# Initialize the SDK before starting any bulk processes
# to prevent multiple instances and having to enter 2fa multiple times.
sdk = state.sdk
success_header = "alias removed"
csv_rows[0][success_header] = "False"
formatter = OutputFormatter(format, {key: key for key in csv_rows[0].keys()})
stats = create_worker_stats(len(csv_rows))
def handle_row(**row):
try:
_remove_cloud_alias(
sdk, **{key: row[key] for key in row.keys() if key != success_header}
)
row[success_header] = "True"
except Exception as err:
row[success_header] = f"False: {err}"
stats.increment_total_errors()
return row
result_rows = run_bulk_process(
handle_row,
csv_rows,
progress_label="Removing aliases from users:",
stats=stats,
raise_global_error=False,
)
formatter.echo_formatted_list(result_rows)
@bulk.command(
name="update-risk-profile",
help=f"Update user risk profile data from the provided CSV in format: {','.join(_bulk_user_risk_profile_headers)}"
"\n\nTo clear a value, set column item to the string: 'null'.",
)
@format_option
@read_csv_arg(headers=_bulk_user_risk_profile_headers)
@click.option(
"--append-notes",
is_flag=True,
help="Append provided note value to already existing note on a new line. Defaults to overwrite.",
)
@sdk_options()
def bulk_update_risk_profile(state, csv_rows, format, append_notes):
"""Bulk update User Risk Profile data."""
sdk = state.sdk
success_header = "updated_user"
formatter = OutputFormatter(
format, {key: key for key in [*csv_rows[0].keys(), success_header]}
)
stats = create_worker_stats(len(csv_rows))
def handle_row(**row):
try:
updated_user = _update_userriskprofile(
sdk, append_notes=append_notes, **row
)
row[success_header] = updated_user
except Exception as err:
row[success_header] = f"Error: {err}"
stats.increment_total_errors()
return row
result_rows = run_bulk_process(
handle_row,
csv_rows,
progress_label="Updating user risk profile data:",
stats=stats,
raise_global_error=False,
)
formatter.echo_formatted_list(result_rows)
def _add_user_role(sdk, username, role_name):
user_id = _get_legacy_user_id(sdk, username)
_get_role_id(sdk, role_name) # function provides role name validation
sdk.users.add_role(user_id, role_name)
def _remove_user_role(sdk, role_name, username):
user_id = _get_legacy_user_id(sdk, username)
_get_role_id(sdk, role_name) # function provides role name validation
sdk.users.remove_role(user_id, role_name)
def _get_legacy_user_id(sdk, username):
if not username:
# py42 returns all users when passing `None` to `get_by_username()`.
raise click.BadParameter("Username is required.")
user = sdk.users.get_by_username(username)["users"]
if len(user) == 0:
raise UserDoesNotExistError(username)
user_id = user[0]["userId"]
return user_id
@functools.lru_cache()
def _get_role_id(sdk, role_name):
try:
roles_dataframe = DataFrame.from_records(
sdk.users.get_available_roles().data, index="roleName"
)
role_result = roles_dataframe.at[role_name, "roleId"]
return str(role_result) # extract the role ID from the series
except KeyError:
raise Code42CLIError(f"Role with name '{role_name}' not found.")
def _get_users_dataframe(sdk, columns, org_uid, role_id, active, include_roles):
users_generator = sdk.users.get_all(
active=active, org_uid=org_uid, role_id=role_id, incRoles=include_roles
)
users_list = []
for page in users_generator:
users_list.extend(page["users"])
return DataFrame.from_records(users_list, columns=columns)
def _add_legal_hold_membership_to_user_dataframe(sdk, df):
columns = ["legalHold.legalHoldUid", "legalHold.name", "user.userUid"]
custodians = list(_get_all_active_hold_memberships(sdk))
if len(custodians) == 0:
return df
legal_hold_member_dataframe = (
json_normalize(custodians)[columns]
.groupby(["user.userUid"])
.agg(",".join)
.rename(
{
"legalHold.legalHoldUid": "legalHoldUid",
"legalHold.name": "legalHoldName",
},
axis=1,
)
)
df = df.merge(
legal_hold_member_dataframe,
how="left",
left_on="userUid",
right_on="user.userUid",
)
return df
def _get_all_active_hold_memberships(sdk):
for page in sdk.legalhold.get_all_matters(active=True):
for matter in page["legalHolds"]:
for _page in sdk.legalhold.get_all_matter_custodians(
legal_hold_uid=matter["legalHoldUid"], active=True
):
yield from _page["legalHoldMemberships"]
def _update_user(
sdk,
user_id,
username,
email,
password,
first_name,
last_name,
notes,
archive_size_quota,
):
return sdk.users.update_user(
user_id,
username=username,
email=email,
password=password,
first_name=first_name,
last_name=last_name,
notes=notes,
archive_size_quota_bytes=archive_size_quota,
)
def _change_organization(sdk, username, org_id):
user_id = _get_legacy_user_id(sdk, username)
org_id = _get_org_id(sdk, org_id)
return sdk.users.change_org_assignment(user_id=int(user_id), org_id=int(org_id))
def _get_org_id(sdk, org_id):
org = sdk.orgs.get_by_uid(org_id)
return org["orgId"]
def _deactivate_user(sdk, username):
user_id = _get_legacy_user_id(sdk, username)
sdk.users.deactivate(user_id)
def _reactivate_user(sdk, username):
user_id = _get_legacy_user_id(sdk, username)
sdk.users.reactivate(user_id)
def _get_user(sdk, username):
# use when retrieving the user risk profile information
try:
return sdk.userriskprofile.get_by_username(username)
except Py42UserRiskProfileNotFound:
raise UserDoesNotExistError(username)
def _add_cloud_alias(sdk, username, alias):
user = _get_user(sdk, username)
sdk.userriskprofile.add_cloud_aliases(user["userId"], alias)
def _remove_cloud_alias(sdk, username, alias):
user = _get_user(sdk, username)
sdk.userriskprofile.delete_cloud_aliases(user["userId"], alias)
def _update_userriskprofile(
sdk, append_notes=False, username=None, start_date=None, end_date=None, notes=None
):
user = _get_user(sdk, username)
user_id = user["userId"]
if append_notes and notes != "null":
notes = user["notes"] + f"\n\n{notes}"
# py42 interprets empty string as "clear this value" for kwarg values. Since empty CSV columns
# get parsed as "" we want to have user provide explicit 'null' string to indicate desire to
# clear instead of just not update value
start_date = (
None if start_date == "" else ("" if start_date == "null" else start_date)
)
end_date = None if end_date == "" else ("" if end_date == "null" else end_date)
notes = None if notes == "" else ("" if notes == "null" else notes)