-
Notifications
You must be signed in to change notification settings - Fork 25
/
__init__.py
125 lines (108 loc) · 4.46 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# vim: set filetype=python ts=4 sw=4
# -*- coding: utf-8 -*-
"""tokendito module initialization."""
import json
import os
from os.path import expanduser
import sys
__version__ = "2.0.0"
__title__ = "tokendito"
__description__ = "Get AWS STS tokens from Okta SSO"
__long_description_content_type__ = "text/x-rst"
__url__ = "https://github.com/dowjones/tokendito"
__author__ = "tokendito"
__author_email__ = "tokendito@dowjones.com"
__license__ = "Apache 2.0"
class Config(object):
"""Creates configuration variables for the application."""
# Instantiated objects can get Class defaults with get_defaults()
_defaults = dict(
user=dict(
config_dir=os.path.join(expanduser("~"), ".aws"),
config_file=os.path.join(expanduser("~"), ".aws", "okta_auth"),
config_profile="default",
encoding=sys.stdin.encoding,
loglevel="INFO",
log_output_file="",
mask_items=[],
quiet=False,
),
aws=dict(
config_file=os.path.join(expanduser("~"), ".aws", "config"),
shared_credentials_file=os.path.join(expanduser("~"), ".aws", "credentials"),
output="json",
profile=None,
region="us-east-1",
role_arn=None,
),
okta=dict(
username="",
password="",
mfa_method=None,
mfa_response=None,
app_url=None,
org=None,
),
)
def __init__(self, **kwargs):
"""Create Config instance.
:param **kwargs: Keyword arguments. The argument key must be exist in the class,
and the value must be a dictionary. If no arguments are passed, an object with
defaults values is created.
:raises AttributeError: raised if the keyword passed does not exist.
:raises KeyError: raised if the value passed for a keyword is not a dictionary.
:raises ValueError: raised if the configuration value does not exist in the object.
"""
self.aws = dict()
self.user = dict()
self.okta = dict()
if kwargs:
# Argument validation
self._check_constraints(**kwargs)
# We create an object that contains only the values passed in.
for (key, val) in kwargs.items():
self.__dict__[key].update(val)
else:
self.set_defaults()
def __repr__(self):
"""Provide a reusable representation of the object."""
return json.dumps(self.__dict__, sort_keys=True, indent=4)
def __str__(self):
"""Provide a string representation of the object."""
return f"{json.dumps(self.__dict__, sort_keys=True)}"
def __eq__(self, other):
"""Test equality with another object, using the JSON representation."""
return repr(other) == repr(self)
def update(self, other):
"""Copy values from another Config object."""
self._check_constraints(**other.__dict__)
for key in other.__dict__.keys():
self.__dict__[key].update(other.__dict__[key])
return self
def _check_constraints(self, **kwargs):
"""Ensure dictionaries that are part of the object are valid.
:param self: Implicit reference to object.
:param kwargs: dictionaries to check.
:return: boolean on success, or raises an error
:raises AttributeError: raised if the keyword passed does not exist.
:raises KeyError: raised if the value passed for a keyword is not a dictionary.
:raises ValueError: raised if the configuration value does not exist in the object.
"""
for (key, val) in kwargs.items():
# Guard against improper initialization.
if key not in self._defaults:
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{key}'")
if type(val) is not dict:
raise KeyError(f"'{key}' must be a {type(dict())}, not '{type(val)}'")
for subkey in val.keys():
if subkey not in self._defaults[key]:
raise ValueError(f"'{subkey}' not available for assignment to key '{key}'")
return True
def set_defaults(self):
"""Update the object to default settings."""
for key in self._defaults.keys():
setattr(self, key, self._defaults[key])
def get_defaults(self):
"""Retrieve default settings."""
return getattr(self, "_defaults")
config = Config()