diff --git a/secured/secured.py b/secured/secured.py index aabb0e4..bddd5c1 100644 --- a/secured/secured.py +++ b/secured/secured.py @@ -1,47 +1,53 @@ import os import yaml -from typing import Union, List +from typing import Tuple, Union, List from secure import Secure from pathlib import Path +class AttrDict(dict): + def __init__(self, *args, secure=True, **kwargs): + super(AttrDict, self).__init__(*args, **kwargs) + self.secure = secure + for key, value in self.items(): + if isinstance(value, dict): + self[key] = AttrDict(value, secure=secure) + + def __getattr__(self, item): + value = self[item] + if isinstance(value, dict): + return value + else: + return Secure(value) if self.secure else value + + def __setattr__(self, key, value): + super(AttrDict, self).__setattr__(key, value) + class Secured: - def __init__(self, key_providers: List = None, yaml_path: str | List[str] = None) -> None: - self.key_providers = key_providers or [] - self.yaml_files = {} - self.yaml_data = self.load_yaml(yaml_path) + def __init__(self, yaml_path: str | List[str] | List[Tuple] = None) -> None: - def load_yaml(self, yaml_path: Union[str, List[str]]) -> dict: - data = {} + self.yaml_files = self.load_yaml(yaml_path) + + def load_yaml(self, yaml_path: str | List[str] | List[Tuple]) -> None: if yaml_path is None: - return data + return yaml_paths = [yaml_path] if isinstance(yaml_path, str) else yaml_path for path in yaml_paths: with open(path, 'r') as file: file_data = yaml.safe_load(file) - data.update(file_data) file_name = Path(path).stem - self.yaml_files[file_name] = file_data - - return data + setattr(self, file_name, AttrDict(file_data)) def get(self, key: str, required: bool = False) -> Secure | None: # Check YAML data first - yaml_value = self.yaml_data.get(key) + yaml_value = self.yaml_files.get(key) if yaml_value is not None: return Secure(yaml_value) # Check environment variables env_value = os.getenv(key) - for provider in self.key_providers: - value = provider.get(key) - if value is not None: - if env_value is not None: - raise ValueError(f"Key '{key}' exists in both OS environment and the provider.") - return Secure(value) - if env_value is None: if required: raise ValueError(f"Key '{key}' not found in the OS environment, the provider, or the YAML file.")