portainer_host: use different way of handling tokens

This commit is contained in:
tylen 2025-03-04 21:03:52 +00:00
parent 99040eccb2
commit 02ea437f6e

View File

@ -20,14 +20,15 @@ class PortainerHost(BaseCLi):
super().__init__()
self.host_url = host_url
self.api_url = f'{host_url}/api'
self.jwt_config = []
self.jwt_config = {}
self.jwt_token = ''
home_directory = os.path.expanduser("~")
config_file_path = os.path.join(home_directory, DEFAULT_PORTAINER_JWT_CONFIG_FILE)
try:
self.__read_current_config(config_file_path)
except EmptyConfigException:
self.__create_config(config_file_path)
def __read_current_config(self, file_path):
try:
with open(file_path, 'r') as file:
@ -36,17 +37,17 @@ class PortainerHost(BaseCLi):
except FileNotFoundError:
print(f"Configuration does not exist. Creating...")
raise EmptyConfigException()
hostnames = [config['hostname'] for config in self.jwt_config]
if self.host_url not in hostnames:
try:
self.jwt_token = self.jwt_config[self.host_url]
except KeyError:
print(f"No token present in configuration file for host {self.host_url}. Creating...")
raise EmptyConfigException()
def __create_config(self, file_path):
config = {
"hostname": self.host_url,
"jwt": self.__get_jwt_token(),
self.jwt_token = self.__get_jwt_token()
self.jwt_config[self.host_url] = {
"jwt": self.jwt_token,
}
self.jwt_config.append(config)
with open(file_path, 'w') as file:
json.dump(self.jwt_config, file, indent=4)
@ -74,3 +75,4 @@ class PortainerHost(BaseCLi):
data = response.json()
return data['jwt']