|
| 1 | +import os |
| 2 | + |
| 3 | +import dotenv |
| 4 | +from keycloak import KeycloakOpenID |
| 5 | +from keycloak.pkce_utils import generate_code_challenge, generate_code_verifier |
| 6 | + |
| 7 | +from python_interface_to_workflows.auth.open_auth_url import open_auth_url |
| 8 | + |
| 9 | + |
| 10 | +def set_token_env_variable(staging: bool) -> str: |
| 11 | + match staging: |
| 12 | + case True: |
| 13 | + keycloak_openid = KeycloakOpenID( |
| 14 | + server_url="https://identity-test.diamond.ac.uk/", |
| 15 | + client_id="workflows-ui-dev", |
| 16 | + realm_name="dls", |
| 17 | + client_secret_key="", |
| 18 | + pool_maxsize=1, |
| 19 | + ) |
| 20 | + case False: |
| 21 | + keycloak_openid = KeycloakOpenID( |
| 22 | + client_id="workflows-dashboard", |
| 23 | + server_url="https://identity.diamond.ac.uk/", |
| 24 | + realm_name="dls", |
| 25 | + client_secret_key="", |
| 26 | + pool_maxsize=1, |
| 27 | + ) |
| 28 | + code_verifier = generate_code_verifier() |
| 29 | + code_challenge, code_challenge_method = generate_code_challenge(code_verifier) |
| 30 | + auth_url = keycloak_openid.auth_url( |
| 31 | + redirect_uri="http://localhost:5173/", |
| 32 | + scope="openid posix-uid profile email fedid", |
| 33 | + state="", |
| 34 | + code_challenge=code_challenge, |
| 35 | + code_challenge_method=code_challenge_method, |
| 36 | + ) |
| 37 | + open_auth_url(auth_url) |
| 38 | + token: dict[str, str] = ( # pyright: ignore[reportUnknownVariableType] |
| 39 | + keycloak_openid.token( # pyright: ignore[reportUnknownMemberType] |
| 40 | + grant_type="authorization_code", |
| 41 | + code=os.environ["AUTH"], |
| 42 | + redirect_uri="http://localhost:5173/", |
| 43 | + code_verifier=code_verifier, |
| 44 | + ) |
| 45 | + ) |
| 46 | + dotenv.set_key("src/.env", "TOKEN", token["access_token"].strip("'")) |
| 47 | + return token["access_token"] # pyright: ignore[reportUnknownArgumentType] |
0 commit comments