|
| 1 | +import yaml |
| 2 | +import os |
| 3 | + |
| 4 | + |
| 5 | +class AuthController: |
| 6 | + def __init__(self, env_token: str | None, env_url: str | None) -> None: |
| 7 | + self.env_token = env_token |
| 8 | + self.env_url = env_url |
| 9 | + |
| 10 | + def get_cf_credentials( |
| 11 | + self, |
| 12 | + ) -> dict[str, dict[str, str] | str] | None: |
| 13 | + env_token = self.env_token |
| 14 | + env_url = self.env_url |
| 15 | + cf_credentials: dict[str, dict[str, str] | str] | None = None |
| 16 | + |
| 17 | + if env_token and env_url: |
| 18 | + auth_header: dict[str, str] = {"Authorization": env_token} |
| 19 | + |
| 20 | + cf_credentials = { |
| 21 | + "headers": auth_header, |
| 22 | + "base_url": f"{env_url}/api", |
| 23 | + } |
| 24 | + |
| 25 | + else: |
| 26 | + config_path = ( |
| 27 | + f"{os.getenv('USERPROFILE')}/.cfconfig" |
| 28 | + if os.name == "nt" |
| 29 | + else f"{os.getenv('HOME')}/.cfconfig" |
| 30 | + ) |
| 31 | + |
| 32 | + with open(config_path, "r") as config_file: |
| 33 | + config = yaml.safe_load(config_file) |
| 34 | + |
| 35 | + current_context = config["contexts"].get(config["current-context"]) |
| 36 | + |
| 37 | + if current_context: |
| 38 | + context_token = current_context["token"] |
| 39 | + context_url = current_context["url"] |
| 40 | + |
| 41 | + if context_token and context_url: |
| 42 | + auth_header = {"Authorization": context_token} |
| 43 | + cf_credentials = { |
| 44 | + "headers": auth_header, |
| 45 | + "base_url": f"{context_url}/api", |
| 46 | + } |
| 47 | + |
| 48 | + return cf_credentials |
0 commit comments