From afbc4396a8bd561c6df5da505cd64921e897c564 Mon Sep 17 00:00:00 2001 From: Giovanni Savarese Date: Tue, 4 Jun 2024 08:03:57 +0000 Subject: [PATCH] Add function to contact OPA and get roles --- fed_mng/auth.py | 26 ++++++++++++++++++++++++++ fed_mng/config.py | 3 +++ 2 files changed, 29 insertions(+) diff --git a/fed_mng/auth.py b/fed_mng/auth.py index e53810c..edb009d 100644 --- a/fed_mng/auth.py +++ b/fed_mng/auth.py @@ -1,4 +1,8 @@ """Authentication and authorization rules.""" +import os + +import requests +from fastapi import status from fastapi.security import HTTPBearer from flaat.config import AccessLevel from flaat.fastapi import Flaat @@ -95,3 +99,25 @@ def is_sla_moderator(user_infos: UserInfos) -> bool: ) flaat.set_trusted_OP_list(get_settings().TRUSTED_IDP_LIST) flaat.set_request_timeout(30) + + +def get_user_roles(token: str) -> list[str]: + """Contact OPA to get user roles. + + Args: + token (str): access token + + Raises: + resp.raise_for_status: _description_ + + Returns: + list[str]: User roles + """ + settings = get_settings() + data = {"input": {"authorization": f"Bearer {token}"}} + resp = requests.post( + os.path.join(settings.OPA_URL, settings.ROLES_ENDPOINT), json=data + ) + if resp.status_code == status.HTTP_200_OK: + return resp.json().get("result", []) + raise resp.raise_for_status() diff --git a/fed_mng/config.py b/fed_mng/config.py index 1f007ed..683c94d 100644 --- a/fed_mng/config.py +++ b/fed_mng/config.py @@ -47,6 +47,9 @@ def create_doc_url(cls, v: str | None, values: dict[str, Any]) -> str: SQLITE_DB: str = ":memory:" + OPA_URL: AnyHttpUrl = "http://localhost:8181" + ROLES_ENDPOINT: str = "v1/data/fedmgr/user_roles" + class Config: """Sub class to set attribute as case sensitive."""