-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
1356 lines (1074 loc) · 54.6 KB
/
auth.py
File metadata and controls
1356 lines (1074 loc) · 54.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
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 jwt
import requests
from database import get_db_cursor, test_connection
from functools import wraps
from flask import request, jsonify, current_app
from jwt.exceptions import InvalidTokenError, ExpiredSignatureError
from permissions import PERMISSIONS
from logging import getLogger
logger = getLogger(__name__)
AGARI_ORG_ROLES = {
"agari-org-viewer": "org-viewer",
"agari-org-contributor": "org-contributor",
"agari-org-admin": "org-admin",
"agari-org-partial": "org-partial",
"agari-org-owner": "org-owner",
"default-roles-agari": "default-roles-agari"
}
class KeycloakAuth:
def __init__(self, keycloak_url, realm, client_id, client_secret):
self.keycloak_url = keycloak_url
self.realm = realm
self.client_id = client_id
self.client_secret = client_secret
self.public_key = None
### GET PUBLIC KEY ###
def get_public_key(self):
"""Fetch public key from Keycloak for token verification"""
try:
certs_url = f"{self.keycloak_url}/realms/{self.realm}/protocol/openid_connect/certs"
response = requests.get(certs_url)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"Error fetching public key: {e}")
return None
### VERIFY TOKEN ###
def verify_token(self, token):
"""Extract user info from JWT token without signature verification"""
try:
# Decode token without signature verification for internal services
payload = jwt.decode(token, options={"verify_signature": False})
return payload
except Exception as e:
return {'error': f'Token decode failed: {str(e)}'}
### GET ADMIN TOKEN ###
def get_admin_token(self):
"""Get admin access token for Keycloak API calls using service account"""
try:
token_url = f"{self.keycloak_url}/realms/{self.realm}/protocol/openid-connect/token"
data = {
'grant_type': 'client_credentials',
'client_id': self.client_id,
'client_secret': self.client_secret
}
response = requests.post(token_url, data=data)
response.raise_for_status()
token_data = response.json()
return token_data.get('access_token')
except requests.RequestException as e:
logger.error(f"Get admin token failed: {e}")
print(f"Error getting admin token: {e}")
return None
### GET CLIENT TOKEN ###
def get_client_token(self):
"""
Get client credentials token for service-to-service authentication
Uses the same client_id and client_secret as the admin token but
can be used for different purposes (like SONG API calls)
Returns:
str: Access token or None if failed
"""
try:
token_url = f"{self.keycloak_url}/realms/{self.realm}/protocol/openid-connect/token"
data = {
'grant_type': 'client_credentials',
'client_id': self.client_id,
'client_secret': self.client_secret
}
response = requests.post(token_url, data=data)
response.raise_for_status()
token_data = response.json()
return token_data.get('access_token')
except requests.RequestException as e:
current_app.logger.error(f"Error getting client token: {e}")
return None
### HELPER METHODS ###
def _user_has_attribute_value(self, user, attribute_name, attribute_value, exact_match=True):
"""
Check if a user has a specific attribute value (multi-valued attributes)
Args:
user (dict): User object from Keycloak
attribute_name (str): The name of the attribute to check
attribute_value (str): The value to search for
exact_match (bool): If True, search for exact match; if False, search for partial match
Returns:
bool: True if user has the attribute value, False otherwise
"""
user_attributes = user.get('attributes', {})
if attribute_name not in user_attributes:
return False
attr_values = user_attributes[attribute_name]
# Attributes are stored as lists in Keycloak (multi-valued)
if isinstance(attr_values, list):
if exact_match:
return attribute_value in attr_values
else:
return any(attribute_value.lower() in str(val).lower() for val in attr_values)
else:
# Fallback for single value (shouldn't happen with new setup)
if exact_match:
return str(attr_values) == attribute_value
else:
return attribute_value.lower() in str(attr_values).lower()
return False
def get_realm_roles(self, user_id):
admin_token = self.get_admin_token()
if not admin_token:
return {'realm_roles': [], 'client_roles': []}
try:
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
realm_roles_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}/role-mappings/realm"
realm_response = requests.get(realm_roles_url, headers=headers)
realm_response.raise_for_status()
realm_roles = realm_response.json()
return [role['name'] for role in realm_roles]
except requests.RequestException as e:
return(f"Error fetching realm roles: {e}")
def _format_user_data(self, user):
"""
Format user data similar to whoami response
Args:
user (dict): User object from Keycloak
Returns:
dict: Formatted user data with user_id, username, organisation_id, roles, attributes
"""
# Extract custom attributes (excluding standard ones)
user_attributes = {}
attributes = user.get('attributes', {})
for key, value in attributes.items():
if key != 'organisation_id': # organisation_id is handled separately
user_attributes[key] = value
# Realm role cache
# this broke org invite accept
#realm_roles = attributes.get('realm_role', None)
#if not realm_roles:
# realm_roles = self.get_realm_roles(user.get('id'))
# role_org_member_attr(user["id"], attributes.get('organisation_id')[0], AGARI_ORG_ROLES[realm_roles[0]])
#else:
# realm_roles = [f"agari-{realm_roles[0]}"]
realm_roles = self.get_realm_roles(user.get('id'))
return {
'user_id': user.get('id'),
'username': user.get('username'),
'email': user.get('email'),
'organisation_id': attributes.get('organisation_id', [None])[0] if attributes.get('organisation_id') else None,
'roles': realm_roles,
'attributes': user_attributes,
'is_authenticated': True,
}
### GET USER ###
def get_user(self, user_id):
"""Fetch user details by user ID from Keycloak"""
admin_token = self.get_admin_token()
if not admin_token:
return None
try:
user_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}"
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
response = requests.get(user_url, headers=headers)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"Error fetching user {user_id}: {e}")
return None
### GET USER ORG ###
def get_user_org(self):
"""Extract and verify JWT token from Authorization header"""
organisation_id = None
auth_header = request.headers.get('Authorization')
if auth_header:
try:
token = auth_header.split(' ')[1]
user_info_raw = self.verify_token(token)
if user_info_raw and 'error' not in user_info_raw:
user_info = extract_user_info(user_info_raw)
user_org_ids = user_info.get('organisation_id', [])
organisation_id = user_org_ids[0] if user_org_ids and len(user_org_ids) > 0 else None
else:
print(f"Token verification failed: {user_info_raw}")
except Exception as e:
print(f"Authentication failed: {str(e)}")
pass
else:
print(f"No Authorization header found")
return organisation_id
def get_user_projects(self):
"""Extract and verify JWT token from Authorization header"""
projects_ids = []
auth_header = request.headers.get('Authorization')
if auth_header:
try:
token = auth_header.split(' ')[1]
user_info_raw = self.verify_token(token)
if user_info_raw and 'error' not in user_info_raw:
user_info = extract_user_info(user_info_raw)
for role in ["project-admin", "project-contributor", "project-viewer"]:
if user_info.get("attributes"):
projects_ids.extend(user_info["attributes"].get(role, []))
else:
print(f"Token verification failed: {user_info_raw}")
except Exception as e:
print(f"Authentication failed: {str(e)}")
pass
else:
print(f"No Authorization header found")
return projects_ids
### GET USER ORGANISATION PROJECTS ###
def get_user_organisation_projects(self):
"""Extract and verify JWT token from Authorization header"""
organisation_projects = []
auth_header = request.headers.get('Authorization')
if auth_header:
try:
token = auth_header.split(' ')[1]
user_info_raw = self.verify_token(token)
if user_info_raw and 'error' not in user_info_raw:
user_info = extract_user_info(user_info_raw)
organisation_id = user_info.get('organisation_id', None)
else:
print(f"Token verification failed: {user_info_raw}")
except Exception as e:
print(f"Authentication failed: {str(e)}")
return []
if organisation_id:
with get_db_cursor() as cursor:
cursor.execute("""
SELECT id FROM projects WHERE organisation_id = %s
""", (organisation_id[0],))
organisation_projects = cursor.fetchall()
organisation_projects = [row['id'] for row in organisation_projects]
return organisation_projects
else:
print("No organisation_id found for user")
return []
else:
print(f"No Authorization header found")
return []
### GET PROJECTS PARENT ORG ###
def get_project_parent_org(self, project_id):
"""Get the parent organisation ID for a given project ID"""
with get_db_cursor() as cursor:
cursor.execute("""
SELECT organisation_id FROM projects WHERE id = %s
""", (project_id,))
result = cursor.fetchone()
if result:
return result['organisation_id']
else:
return None
### GET USERS BY ATTRIBUTE ###
def get_users_by_attribute(self, attribute_name, attribute_value, exact_match=True):
"""
Search for users by a specific attribute
Args:
attribute_name (str): The name of the attribute to search for
attribute_value (str): The value to search for
exact_match (bool): If True, search for exact match; if False, search for partial match
Returns:
list: List of users with simplified format (user_id, username, organisation_id, roles, attributes)
"""
admin_token = self.get_admin_token()
if not admin_token:
return []
try:
# Keycloak admin API endpoint for users
users_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users"
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
# For custom attributes, we need to get all users and filter client-side
# as Keycloak's search doesn't handle custom attributes well
params = {'max': 1000}
response = requests.get(users_url, headers=headers, params=params)
response.raise_for_status()
users = response.json()
# Filter users based on attribute
filtered_users = []
for user in users:
if self._user_has_attribute_value(user, attribute_name, attribute_value, exact_match):
# Format user data similar to whoami response
user_data = self._format_user_data(user)
filtered_users.append(user_data)
return filtered_users
except requests.RequestException as e:
print(f"Error searching users by attribute: {e}")
return []
### GET USER ATTRIBUTES ###
def get_user_attributes(self, user_id):
"""
Fetch user attributes by user ID from Keycloak
Args:
user_id (str): The user ID to fetch attributes for
Returns:
dict: User attributes or empty dict if none
"""
user = self.get_user(user_id)
if user:
return user.get('attributes', {})
return {}
### CHECK USER ATTRIBUTE ###
def user_has_attribute(self, user_id, attribute_name, attribute_value, exact_match=True):
admin_token = self.get_admin_token()
if not admin_token:
return False
try:
# Get specific user by ID
user_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}"
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
response = requests.get(user_url, headers=headers)
response.raise_for_status()
user = response.json()
return self._user_has_attribute_value(user, attribute_name, attribute_value, exact_match)
except requests.RequestException as e:
print(f"Error checking user attribute: {e}")
return False
### MODIFY USER ATTRIBUTES ###
def add_attribute_value(self, user_id, attribute_name, value_to_add):
"""
Add a value to a user's multi-valued attribute
Args:
user_id (str): The user ID to update
attribute_name (str): The name of the attribute (e.g., 'project-admin', 'study-contributor')
value_to_add (str): The value to add (e.g., project ID or study ID)
Returns:
bool: True if update was successful, False otherwise
"""
admin_token = self.get_admin_token()
if not admin_token:
return False
try:
# Get current user data
user_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}"
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
response = requests.get(user_url, headers=headers)
response.raise_for_status()
user = response.json()
attributes = user.get('attributes', {})
# Get current attribute values (as list)
current_values = attributes.get(attribute_name, [])
# Ensure it's a list
if not isinstance(current_values, list):
current_values = [current_values] if current_values else []
# Add new value if not already present
if value_to_add not in current_values:
current_values.append(value_to_add)
# Update attributes
attributes[attribute_name] = current_values
user['attributes'] = attributes
# Send update request
update_response = requests.put(user_url, headers=headers, json=user)
update_response.raise_for_status()
return True
except requests.RequestException as e:
print(f"Error adding attribute value: {e}")
return False
def remove_attribute_value(self, user_id, attribute_name, value_to_remove):
"""
Remove a value from a user's multi-valued attribute
Args:
user_id (str): The user ID to update
attribute_name (str): The name of the attribute (e.g., 'project-admin', 'study-contributor')
value_to_remove (str): The value to remove (e.g., project ID or study ID)
Returns:
bool: True if update was successful, False otherwise
"""
admin_token = self.get_admin_token()
if not admin_token:
return False
try:
# Get current user data
user_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}"
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
response = requests.get(user_url, headers=headers)
response.raise_for_status()
user = response.json()
attributes = user.get('attributes', {})
# Get current attribute values (as list)
current_values = attributes.get(attribute_name, [])
# Ensure it's a list
if not isinstance(current_values, list):
current_values = [current_values] if current_values else []
# Remove the value if present
if value_to_remove in current_values:
current_values.remove(value_to_remove)
# Update attributes
if current_values:
attributes[attribute_name] = current_values
elif attribute_name in attributes:
# Remove attribute entirely if no values left
del attributes[attribute_name]
user['attributes'] = attributes
# Send update request
update_response = requests.put(user_url, headers=headers, json=user)
update_response.raise_for_status()
return True
except requests.RequestException as e:
print(f"Error removing attribute value: {e}")
return False
def remove_org_attribute(self, user_id, attribute_name="organisation_id"):
admin_token = self.get_admin_token()
if not admin_token:
return False
try:
# Get current user data
user_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}"
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
response = requests.get(user_url, headers=headers)
response.raise_for_status()
user = response.json()
attributes = user.get('attributes', {})
if attribute_name in attributes:
del attributes[attribute_name]
user['attributes'] = attributes
update_response = requests.put(user_url, headers=headers, json=user)
update_response.raise_for_status()
return True
except requests.RequestException as e:
print(f"Error removing attribute value: {e}")
return False
def update_realm_roles(self, user_id, role_names):
"""
Update a user's realm roles
Args:
user_id (str): The user ID to update
role_names (list): List of role names to assign to the user
Returns:
bool: True if update was successful, False otherwise
"""
admin_token = self.get_admin_token()
if not admin_token:
return False
try:
# Get current user data
user_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}"
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
response = requests.get(user_url, headers=headers)
response.raise_for_status()
user = response.json()
# Fetch all available realm roles
roles_url = f"{self.keycloak_url}/admin/realms/{self.realm}/roles"
roles_response = requests.get(roles_url, headers=headers)
roles_response.raise_for_status()
all_roles = roles_response.json()
role_map = {role['name']: role for role in all_roles}
# Prepare roles to assign
roles_to_assign = [role_map[role_name] for role_name in role_names if role_name in role_map]
if not roles_to_assign:
print(f"No valid roles found to assign for user {user_id}")
return False
# Assign roles to user
assign_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}/role-mappings/realm"
assign_response = requests.post(assign_url, headers=headers, json=roles_to_assign)
assign_response.raise_for_status()
return True
except requests.RequestException as e:
print(f"Error updating realm roles: {e}")
return False
def remove_realm_roles(self, user_id):
admin_token = self.get_admin_token()
if not admin_token:
return False
try:
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
current_roles_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}/role-mappings/realm"
current_roles_response = requests.get(current_roles_url, headers=headers)
current_roles_response.raise_for_status()
current_roles = current_roles_response.json()
if not current_roles:
print(f"User {user_id} has no realm roles to remove")
return False
# Remove the roles using DELETE with the role objects
remove_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}/role-mappings/realm"
remove_response = requests.delete(remove_url, headers=headers, json=current_roles)
remove_response.raise_for_status()
print(f"Successfully removed {current_roles[0]['name']} realm roles from user {user_id}")
return current_roles[0]["name"]
except requests.RequestException as e:
print(f"Error updating realm roles: {e}")
return False
### GET USER INFO BY ID ###
def get_user_info_by_id(self, user_id):
"""
Get formatted user information by user ID (similar to extract_user_info but from Keycloak API)
Args:
user_id (str): The user ID to fetch
Returns:
dict: Formatted user info or None if user not found
"""
user = self.get_user(user_id)
if not user:
return None
# Extract attributes
attributes = user.get('attributes', {})
# Get organization_id from attributes (it's stored as a list in Keycloak)
org_id = None
if 'organisation_id' in attributes:
org_id_list = attributes['organisation_id']
org_id = org_id_list[0] if org_id_list and len(org_id_list) > 0 else None
# Extract custom attributes (excluding standard ones we handle separately)
user_attributes = {}
standard_attrs = {'organisation_id', 'name', 'surname', 'title', 'bio', 'preferences', 'accepted_terms'}
for key, value in attributes.items():
if key not in standard_attrs:
user_attributes[key] = value
# Get single values from attribute lists for standard fields
def get_attr_value(attr_name):
attr_list = attributes.get(attr_name, [])
return attr_list[0] if attr_list and len(attr_list) > 0 else None
return {
'user_id': user.get('id'),
'username': user.get('username'),
'email': user.get('email'),
'title': get_attr_value('title'),
'name': get_attr_value('name'),
'surname': get_attr_value('surname'),
'organisation_id': org_id,
'bio': get_attr_value('bio'),
'preferences': get_attr_value('preferences'),
'roles': [], # Would need separate API call to get user roles
'attributes': user_attributes,
'is_authenticated': True,
'accepted_terms': get_attr_value('accepted_terms') == 'true' if get_attr_value('accepted_terms') else False,
}
### UPDATE USER PROFILE ###
def update_user(self, user_id, update_data):
"""
Update user profile information including basic properties, email, roles, and attributes
Args:
user_id (str): The user ID to update
update_data (dict): Dictionary of fields to update. Can include:
- Basic fields: 'name', 'surname', 'email', 'title', 'bio'
- 'realm_roles': list of role names to assign
- 'attributes': dict of custom attributes to update
Returns:
dict: Result with success status and any errors
"""
admin_token = self.get_admin_token()
if not admin_token:
return {'success': False, 'error': 'Could not get admin token'}
results = {'success': True, 'updates': {}, 'errors': {}}
try:
user_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}"
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
# Get current user data
response = requests.get(user_url, headers=headers)
response.raise_for_status()
user = response.json()
# Separate different types of updates
basic_updates = {}
realm_roles = update_data.get('realm_roles')
attributes_update = update_data.get('attributes')
# Extract basic user properties (excluding special fields)
for key, value in update_data.items():
if key not in ['realm_roles', 'attributes']:
basic_updates[key] = value
# 1. Update basic user properties
if basic_updates:
try:
for key, value in basic_updates.items():
if key in ['name', 'surname']:
# These go to attributes in Keycloak
if 'attributes' not in user:
user['attributes'] = {}
user['attributes'][key] = [value] if value else []
elif key == 'email':
user['email'] = value
elif key in ['title', 'bio']:
# These also go to attributes
if 'attributes' not in user:
user['attributes'] = {}
user['attributes'][key] = [value] if value else []
update_response = requests.put(user_url, headers=headers, json=user)
update_response.raise_for_status()
results['updates']['basic_properties'] = f"Updated: {', '.join(basic_updates.keys())}"
except requests.RequestException as e:
results['success'] = False
results['errors']['basic_properties'] = f"Error updating basic properties: {e}"
# 2. Update realm roles if provided
if realm_roles is not None:
try:
role_success = self.update_realm_roles(user_id, realm_roles)
if role_success:
results['updates']['realm_roles'] = f"Updated roles: {', '.join(realm_roles)}" if realm_roles else "Removed all non-default roles"
else:
results['success'] = False
results['errors']['realm_roles'] = "Failed to update realm roles"
except Exception as e:
results['success'] = False
results['errors']['realm_roles'] = f"Error updating realm roles: {e}"
# 3. Update custom attributes if provided
if attributes_update is not None:
try:
current_attributes = self.get_user_attributes(user_id)
updated_attrs = []
for attr_name, attr_value in attributes_update.items():
if attr_value is None:
# Remove attribute entirely if value is None
current_values = current_attributes.get(attr_name, [])
if current_values:
for value in current_values:
remove_success = self.remove_attribute_value(user_id, attr_name, value)
if not remove_success:
results['errors'][f'attr_remove_{attr_name}'] = f"Failed to remove attribute {attr_name}"
updated_attrs.append(f"removed {attr_name}")
else:
# Ensure attribute values are lists
if not isinstance(attr_value, list):
attr_value = [str(attr_value)]
# Get current values for this attribute
current_values = current_attributes.get(attr_name, [])
# Remove values that are no longer needed
for current_val in current_values:
if current_val not in attr_value:
remove_success = self.remove_attribute_value(user_id, attr_name, current_val)
if not remove_success:
results['errors'][f'attr_remove_{attr_name}_{current_val}'] = f"Failed to remove value {current_val} from {attr_name}"
# Add new values
for new_val in attr_value:
if new_val not in current_values:
add_success = self.add_attribute_value(user_id, attr_name, new_val)
if not add_success:
results['errors'][f'attr_add_{attr_name}_{new_val}'] = f"Failed to add value {new_val} to {attr_name}"
updated_attrs.append(attr_name)
if updated_attrs:
results['updates']['attributes'] = f"Updated attributes: {', '.join(updated_attrs)}"
else:
results['updates']['attributes'] = "No attribute changes needed"
except Exception as e:
results['success'] = False
results['errors']['attributes'] = f"Error updating attributes: {e}"
return results
except requests.RequestException as e:
return {'success': False, 'error': f"Error fetching user {user_id}: {e}"}
def toggle_user_enabled(self, user_id, enabled):
admin_token = self.get_admin_token()
if not admin_token:
return {'success': False, 'error': 'Could not get admin token'}
user_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}"
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
# Get current user data
response = requests.get(user_url, headers=headers)
response.raise_for_status()
user = response.json()
user['enabled'] = enabled
requests.put(user_url, headers=headers, json=user)
# Update user attributes to reflect enabled status
self.remove_attribute_value(user_id, 'account_enabled', str(not enabled))
self.add_attribute_value(user_id, 'account_enabled', str(enabled))
def get_user_access_token(self, user_id):
"""Get an access token for a specific user using token exchange or admin token"""
try:
admin_token = self.get_client_token()
if not admin_token:
print("Failed to get admin token")
return None
token_url = f"{self.keycloak_url}/realms/{self.realm}/protocol/openid-connect/token"
exchange_data = {
'grant_type': 'urn:ietf:params:oauth:grant-type:token-exchange',
'client_id': self.client_id,
'client_secret': self.client_secret,
'subject_token': admin_token,
'requested_subject': user_id,
'audience': self.client_id,
'requested_token_type': 'urn:ietf:params:oauth:token-type:access_token'
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.post(token_url, data=exchange_data, headers=headers)
token_data = response.json()
return token_data.get('access_token')
except Exception as e:
print(f"Error getting user access token: {str(e)}")
return None
def get_user_auth_tokens(self, user_id):
"""Get an auth token for a specific user using token exchange or admin token"""
try:
admin_token = self.get_client_token()
if not admin_token:
print("Failed to get admin token")
return None
token_url = f"{self.keycloak_url}/realms/{self.realm}/protocol/openid-connect/token"
exchange_data = {
'grant_type': 'urn:ietf:params:oauth:grant-type:token-exchange',
'client_id': self.client_id,
'client_secret': self.client_secret,
'subject_token': admin_token,
'requested_subject': user_id,
'audience': self.client_id,
'requested_token_type': 'urn:ietf:params:oauth:token-type:refresh_token'
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.post(token_url, data=exchange_data, headers=headers)
token_data = response.json()
return {
'access_token': token_data.get('access_token'),
'refresh_token': token_data.get('refresh_token'),
'expires_in': token_data.get('expires_in'),
'refresh_expires_in': token_data.get('refresh_expires_in')
}
except Exception as e:
print(f"Error getting user refresh token: {str(e)}")
return None
def change_username(self, user_id, new_username):
admin_token = self.get_admin_token()
if not admin_token:
return {'success': False, 'error': 'Could not get admin token'}
try:
# First check if the new username is already taken
check_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users"
headers = {
'Authorization': f'Bearer {admin_token}',
'Content-Type': 'application/json'
}
# Search for existing user with the new username
check_params = {'username': new_username, 'exact': 'true'}
check_response = requests.get(check_url, headers=headers, params=check_params)
check_response.raise_for_status()
existing_users = check_response.json()
if existing_users:
# Check if it's the same user (updating to same username)
if len(existing_users) == 1 and existing_users[0]['id'] == user_id:
return {'success': True, 'message': 'Username is already set to this value'}
else:
return {'success': False, 'error': 'Username already exists'}
# Get current user data
user_url = f"{self.keycloak_url}/admin/realms/{self.realm}/users/{user_id}"
response = requests.get(user_url, headers=headers)
response.raise_for_status()
user = response.json()
old_username = user.get('username')
# Update the username
user['username'] = new_username
# Send update request