|
| 1 | +from urllib.parse import urlencode |
| 2 | + |
| 3 | +import requests |
| 4 | + |
| 5 | +from ..core.api.exceptions import ApiException |
| 6 | + |
| 7 | + |
| 8 | +def get_idp_url(api_host, owner): |
| 9 | + org_saml_url = "{api_host}/orgs/{owner}/saml/?{params}".format( |
| 10 | + api_host=api_host, |
| 11 | + owner=owner, |
| 12 | + params=urlencode({"redirect_url": "http://localhost:12400"}), |
| 13 | + ) |
| 14 | + |
| 15 | + org_saml_response = requests.get(org_saml_url, timeout=30) |
| 16 | + |
| 17 | + try: |
| 18 | + org_saml_response.raise_for_status() |
| 19 | + except requests.RequestException as exc: |
| 20 | + raise ApiException( |
| 21 | + org_saml_response.status_code, |
| 22 | + headers=exc.response.headers, |
| 23 | + body=exc.response.content, |
| 24 | + ) |
| 25 | + |
| 26 | + return org_saml_response.json().get("redirect_url") |
| 27 | + |
| 28 | + |
| 29 | +def exchange_2fa_token(api_host, two_factor_token, totp_token): |
| 30 | + exchange_data = {"two_factor_token": two_factor_token, "totp_token": totp_token} |
| 31 | + exchange_url = "{api_host}/user/two-factor/".format(api_host=api_host) |
| 32 | + |
| 33 | + exchange_response = requests.post( |
| 34 | + exchange_url, |
| 35 | + data=exchange_data, |
| 36 | + headers={ |
| 37 | + "Authorization": "Bearer {two_factor_token}".format( |
| 38 | + two_factor_token=two_factor_token |
| 39 | + ) |
| 40 | + }, |
| 41 | + timeout=30, |
| 42 | + ) |
| 43 | + |
| 44 | + try: |
| 45 | + exchange_response.raise_for_status() |
| 46 | + except requests.RequestException as exc: |
| 47 | + raise ApiException( |
| 48 | + exchange_response.status_code, |
| 49 | + headers=exc.response.headers, |
| 50 | + body=exc.response.content, |
| 51 | + ) |
| 52 | + |
| 53 | + exchange_data = exchange_response.json() |
| 54 | + access_token = exchange_data.get("access_token") |
| 55 | + refresh_token = exchange_data.get("refresh_token") |
| 56 | + |
| 57 | + return (access_token, refresh_token) |
| 58 | + |
| 59 | + |
| 60 | +def refresh_access_token(api_host, access_token, refresh_token): |
| 61 | + data = {"refresh_token": refresh_token} |
| 62 | + url = "{api_host}/user/refresh-token/".format(api_host=api_host) |
| 63 | + |
| 64 | + response = requests.post( |
| 65 | + url, |
| 66 | + data=data, |
| 67 | + headers={ |
| 68 | + "Authorization": "Bearer {access_token}".format(access_token=access_token) |
| 69 | + }, |
| 70 | + timeout=30, |
| 71 | + ) |
| 72 | + |
| 73 | + try: |
| 74 | + response.raise_for_status() |
| 75 | + except requests.RequestException as exc: |
| 76 | + raise ApiException( |
| 77 | + response.status_code, |
| 78 | + headers=exc.response.headers, |
| 79 | + body=exc.response.content, |
| 80 | + ) |
| 81 | + |
| 82 | + response_data = response.json() |
| 83 | + access_token = response_data.get("access_token") |
| 84 | + refresh_token = response_data.get("refresh_token") |
| 85 | + |
| 86 | + return (access_token, refresh_token) |
0 commit comments