fabaccess/fab_access/keycloak_handler.py

46 lines
1.4 KiB
Python
Raw Normal View History

2022-11-03 00:41:51 +01:00
from config import Config
from keycloak import KeycloakAdmin
class KeycloakHandler:
Config.keycloak_password
@staticmethod
def login():
KeycloakHandler.admin = KeycloakAdmin(
server_url=Config.keycloak_url,
2022-11-03 21:21:23 +01:00
username=Config.keycloak_user_name,
2022-11-03 00:41:51 +01:00
password=Config.keycloak_password,
realm_name=Config.keycloak_realm,
verify=True
)
@staticmethod
def get_user_by_card_id(card_id):
users = KeycloakHandler.admin.get_users()
# Filter not working for Attributes because of multidimensional JSON
user = [user for user in users if "attributes" in user and "FabCard" in user["attributes"] and user["attributes"]["FabCard"] == [card_id]]
print(f'Found {len(user)} user(s) with card_id: {card_id}')
2022-11-03 00:41:51 +01:00
match len(user):
2022-11-03 00:41:51 +01:00
case 0:
return None
case 1:
print(f'FabCard matches with user {user[0]["username"]}')
return user[0]
2022-11-03 00:41:51 +01:00
case other:
print(f'Error! too many users with card_id: {card_id}')
return None
@staticmethod
def user_is_privileged(username):
groups = KeycloakHandler.admin.get_user_groups(user_id=username)
groups = [group['name'] for group in groups]
if 'Mentoren' in groups:
print('Overrided becouse of "Mentor" group')
return True
else:
return False