wcp-library 1.2.9__py3-none-any.whl → 1.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import logging
2
+ from abc import ABC,abstractmethod
2
3
 
3
4
  import aiohttp
4
5
  from yarl import URL
@@ -8,12 +9,12 @@ from wcp_library.async_credentials import MissingCredentialsError
8
9
  logger = logging.getLogger(__name__)
9
10
 
10
11
 
11
- class AsyncOracleCredentialManager:
12
- def __init__(self, passwordState_api_key: str):
12
+ class AsyncCredentialManager(ABC):
13
+ def __init__(self, passwordState_api_key: str, password_list_id: int):
13
14
  self.password_url = URL("https://vault.wcap.ca/api/passwords/")
14
15
  self.api_key = passwordState_api_key
15
16
  self.headers = {"APIKey": self.api_key, 'Reason': 'Python Script Access'}
16
- self._password_list_id = 207
17
+ self._password_list_id = password_list_id
17
18
 
18
19
  async def _get_credentials(self) -> dict:
19
20
  """
@@ -40,6 +41,46 @@ class AsyncOracleCredentialManager:
40
41
  logger.debug("Credentials retrieved")
41
42
  return password_dict
42
43
 
44
+ async def _get_credential(self, password_id: int) -> dict:
45
+ """
46
+ Get a specific credential from the password list
47
+
48
+ :param password_id:
49
+ :return:
50
+ """
51
+
52
+ logger.debug(f"Getting credential with ID {password_id}")
53
+ url = (self.password_url / str(password_id))
54
+ async with aiohttp.ClientSession() as session:
55
+ async with session.get(str(url), headers=self.headers) as response:
56
+ password = await response.json()
57
+
58
+ if not password:
59
+ raise MissingCredentialsError(f"No credentials found with ID {password_id}")
60
+ password = password[0]
61
+
62
+ password_info = {'PasswordID': password['PasswordID'], 'UserName': password['UserName'], 'Password': password['Password']}
63
+ for field in password['GenericFieldInfo']:
64
+ password_info[field['DisplayName']] = field['Value'].lower() if field['DisplayName'].lower() == 'username' else field['Value']
65
+ return password_info
66
+
67
+ async def _publish_new_password(self, data: dict) -> bool:
68
+ """
69
+ Publish a new password to the password list
70
+
71
+ :param data:
72
+ :return:
73
+ """
74
+
75
+ async with aiohttp.ClientSession() as session:
76
+ async with session.post(str(self.password_url), json=data, headers=self.headers) as response:
77
+ if response.status == 201:
78
+ logger.debug(f"New credentials for {data['UserName']} created")
79
+ return True
80
+ else:
81
+ logger.error(f"Failed to create new credentials for {data['UserName']}")
82
+ return False
83
+
43
84
  async def get_credentials(self, username: str) -> dict:
44
85
  """
45
86
  Get the credentials for a specific username
@@ -94,38 +135,6 @@ class AsyncOracleCredentialManager:
94
135
  logger.error(f"Failed to update credentials for {credentials_dict['UserName']}")
95
136
  return False
96
137
 
138
+ @abstractmethod
97
139
  async def new_credentials(self, credentials_dict: dict) -> bool:
98
- """
99
- Create a new credential entry
100
-
101
- Credentials dictionary must have the following keys:
102
- - UserName
103
- - Password
104
- - Host
105
- - Port
106
- - Service or SID
107
-
108
- :param credentials_dict:
109
- :return:
110
- """
111
-
112
- data = {
113
- "PasswordListID": self._password_list_id,
114
- "Title": credentials_dict['UserName'].upper() if "Title" not in credentials_dict else credentials_dict['Title'].upper(),
115
- "Notes": credentials_dict['Notes'] if 'Notes' in credentials_dict else None,
116
- "UserName": credentials_dict['UserName'].lower(),
117
- "Password": credentials_dict['Password'],
118
- "GenericField1": credentials_dict['Host'],
119
- "GenericField2": credentials_dict['Port'],
120
- "GenericField3": credentials_dict['Service'] if 'Service' in credentials_dict else None,
121
- "GenericField4": credentials_dict['SID'] if 'SID' in credentials_dict else None
122
- }
123
-
124
- async with aiohttp.ClientSession() as session:
125
- async with session.post(str(self.password_url), json=data, headers=self.headers) as response:
126
- if response.status == 201:
127
- logger.debug(f"New credentials for {credentials_dict['UserName']} created")
128
- return True
129
- else:
130
- logger.error(f"Failed to create new credentials for {credentials_dict['UserName']}")
131
- return False
140
+ raise NotImplementedError("Must override in child class")
@@ -0,0 +1,144 @@
1
+ import logging
2
+ from abc import ABC,abstractmethod
3
+
4
+ import requests
5
+ from yarl import URL
6
+
7
+ from wcp_library.credentials import MissingCredentialsError
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class CredentialManager(ABC):
13
+ def __init__(self, passwordState_api_key: str, password_list_id: int):
14
+ self.password_url = URL("https://vault.wcap.ca/api/passwords/")
15
+ self.api_key = passwordState_api_key
16
+ self.headers = {"APIKey": self.api_key, 'Reason': 'Python Script Access'}
17
+ self._password_list_id = password_list_id
18
+
19
+ def _get_credentials(self) -> dict:
20
+ """
21
+ Get all credentials from the password list
22
+
23
+ :return: Dictionary of credentials
24
+ """
25
+
26
+ logger.debug("Getting credentials from PasswordState")
27
+ url = (self.password_url / str(self._password_list_id)).with_query("QueryAll")
28
+ passwords = requests.get(str(url), headers=self.headers).json()
29
+
30
+ if not passwords:
31
+ raise MissingCredentialsError("No credentials found in this Password List")
32
+
33
+ password_dict = {}
34
+ for password in passwords:
35
+ password_info = {'PasswordID': password['PasswordID'], 'UserName': password['UserName'], 'Password': password['Password']}
36
+ for field in password['GenericFieldInfo']:
37
+ password_info[field['DisplayName']] = field['Value'].lower() if field['DisplayName'].lower() == 'username' else field['Value']
38
+ password_dict[password['UserName'].lower()] = password_info
39
+ logger.debug("Credentials retrieved")
40
+ return password_dict
41
+
42
+ def _get_credential(self, password_id: int) -> dict:
43
+ """
44
+ Get a specific credential from the password list
45
+
46
+ :param password_id:
47
+ :return:
48
+ """
49
+
50
+ logger.debug(f"Getting credential with ID {password_id}")
51
+ url = (self.password_url / str(password_id))
52
+ password = requests.get(str(url), headers=self.headers).json()
53
+
54
+ if not password:
55
+ raise MissingCredentialsError(f"No credentials found with ID {password_id}")
56
+ password = password[0]
57
+
58
+ password_info = {'PasswordID': password['PasswordID'], 'UserName': password['UserName'], 'Password': password['Password']}
59
+ for field in password['GenericFieldInfo']:
60
+ password_info[field['DisplayName']] = field['Value'].lower() if field['DisplayName'].lower() == 'username' else field['Value']
61
+ logger.debug("Credential retrieved")
62
+ return password_info
63
+
64
+ def _publish_new_password(self, data: dict) -> bool:
65
+ """
66
+ Publish a new password to the password list
67
+
68
+ :param data:
69
+ :return:
70
+ """
71
+
72
+ response = requests.post(str(self.password_url), json=data, headers=self.headers)
73
+ if response.status_code == 201:
74
+ logger.debug(f"New credentials for {data['UserName']} created")
75
+ return True
76
+ else:
77
+ logger.error(f"Failed to create new credentials for {data['UserName']}")
78
+ return False
79
+
80
+ def get_credentials(self, username: str) -> dict:
81
+ """
82
+ Get the credentials for a specific username
83
+
84
+ :param username:
85
+ :return: Dictionary of credentials
86
+ """
87
+
88
+ logger.debug(f"Getting credentials for {username}")
89
+ credentials = self._get_credentials()
90
+
91
+ try:
92
+ return_credential = credentials[username.lower()]
93
+ except KeyError:
94
+ raise MissingCredentialsError(f"Credentials for {username} not found in this Password List")
95
+ logger.debug(f"Credentials for {username} retrieved")
96
+ return return_credential
97
+
98
+ def get_credential_from_id(self, password_id: int) -> dict:
99
+ """
100
+ Get the credentials for a specific password ID
101
+
102
+ :param password_id:
103
+ :return:
104
+ """
105
+
106
+ return self._get_credential(password_id)
107
+
108
+
109
+ def update_credential(self, credentials_dict: dict) -> bool:
110
+ """
111
+ Update the credentials for a specific username
112
+
113
+ Credentials dictionary must have the following keys:
114
+ - PasswordID
115
+ - UserName
116
+ - Password
117
+
118
+ The dictionary should be obtained from the get_credentials method and modified accordingly
119
+
120
+ :param credentials_dict:
121
+ :return: True if successful, False otherwise
122
+ """
123
+
124
+ logger.debug(f"Updating credentials for {credentials_dict['UserName']}")
125
+ url = (self.password_url / str(self._password_list_id)).with_query("QueryAll")
126
+ passwords = requests.get(str(url), headers=self.headers).json()
127
+
128
+ relevant_credential_entry = [x for x in passwords if x['UserName'] == credentials_dict['UserName']][0]
129
+ for field in relevant_credential_entry['GenericFieldInfo']:
130
+ if field['DisplayName'] in credentials_dict:
131
+ credentials_dict[field['GenericFieldID']] = credentials_dict[field['DisplayName']]
132
+ credentials_dict.pop(field['DisplayName'])
133
+
134
+ response = requests.put(str(self.password_url), json=credentials_dict, headers=self.headers)
135
+ if response.status_code == 200:
136
+ logger.debug(f"Credentials for {credentials_dict['UserName']} updated")
137
+ return True
138
+ else:
139
+ logger.error(f"Failed to update credentials for {credentials_dict['UserName']}")
140
+ return False
141
+
142
+ @abstractmethod
143
+ def new_credentials(self, credentials_dict: dict) -> bool:
144
+ raise NotImplementedError("Must override in child class")
@@ -1,95 +1,49 @@
1
1
  import logging
2
2
 
3
- import requests
4
- from yarl import URL
5
-
6
- from wcp_library.credentials import MissingCredentialsError
3
+ from wcp_library.credentials.credential_manager_asynchronous import AsyncCredentialManager
4
+ from wcp_library.credentials.credential_manager_synchronous import CredentialManager
7
5
 
8
6
  logger = logging.getLogger(__name__)
9
7
 
10
8
 
11
- class FTPCredentialManager:
9
+ class FTPCredentialManager(CredentialManager):
12
10
  def __init__(self, passwordState_api_key: str):
13
- self.password_url = URL("https://vault.wcap.ca/api/passwords/")
14
- self.api_key = passwordState_api_key
15
- self.headers = {"APIKey": self.api_key, 'Reason': 'Python Script Access'}
16
- self._password_list_id = 208
17
-
18
- def _get_credentials(self) -> dict:
19
- """
20
- Get all credentials from the password list
21
-
22
- :return: Dictionary of credentials
23
- """
11
+ super().__init__(passwordState_api_key, 208)
24
12
 
25
- logger.debug("Getting credentials from PasswordState")
26
- url = (self.password_url / str(self._password_list_id)).with_query("QueryAll")
27
- passwords = requests.get(str(url), headers=self.headers).json()
28
-
29
- if not passwords:
30
- raise MissingCredentialsError("No credentials found in this Password List")
31
-
32
- password_dict = {}
33
- for password in passwords:
34
- password_info = {'PasswordID': password['PasswordID'], 'UserName': password['UserName'], 'Password': password['Password']}
35
- for field in password['GenericFieldInfo']:
36
- password_info[field['DisplayName']] = field['Value'].lower() if field['DisplayName'].lower() == 'username' else field['Value']
37
- password_dict[password['UserName'].lower()] = password_info
38
- logger.debug("Credentials retrieved")
39
- return password_dict
40
-
41
- def get_credentials(self, username: str) -> dict:
42
- """
43
- Get the credentials for a specific username
44
-
45
- :param username:
46
- :return: Dictionary of credentials
47
- """
48
-
49
- logger.debug(f"Getting credentials for {username}")
50
- credentials = self._get_credentials()
51
-
52
- try:
53
- return_credential = credentials[username.lower()]
54
- except KeyError:
55
- raise MissingCredentialsError(f"Credentials for {username} not found in this Password List")
56
- logger.debug(f"Credentials for {username} retrieved")
57
- return return_credential
58
-
59
- def update_credential(self, credentials_dict: dict) -> bool:
13
+ def new_credentials(self, credentials_dict: dict) -> bool:
60
14
  """
61
- Update the credentials for a specific username
15
+ Create a new credential entry
62
16
 
63
17
  Credentials dictionary must have the following keys:
64
- - PasswordID
65
18
  - UserName
66
19
  - Password
67
-
68
- The dictionary should be obtained from the get_credentials method and modified accordingly
20
+ - Host
21
+ - Port
22
+ - FTP/SFTP (FTP or SFTP)
69
23
 
70
24
  :param credentials_dict:
71
25
  :return: True if successful, False otherwise
72
26
  """
73
27
 
74
- logger.debug(f"Updating credentials for {credentials_dict['UserName']}")
75
- url = (self.password_url / str(self._password_list_id)).with_query("QueryAll")
76
- passwords = requests.get(str(url), headers=self.headers).json()
28
+ data = {
29
+ "PasswordListID": self._password_list_id,
30
+ "Title": credentials_dict['UserName'].upper() if "Title" not in credentials_dict else credentials_dict['Title'].upper(),
31
+ "Notes": credentials_dict['Notes'] if 'Notes' in credentials_dict else None,
32
+ "UserName": credentials_dict['UserName'].lower(),
33
+ "Password": credentials_dict['Password'],
34
+ "GenericField1": credentials_dict['Host'],
35
+ "GenericField2": credentials_dict['Port'],
36
+ "GenericField3": credentials_dict['FTP/SFTP']
37
+ }
77
38
 
78
- relevant_credential_entry = [x for x in passwords if x['UserName'] == credentials_dict['UserName']][0]
79
- for field in relevant_credential_entry['GenericFieldInfo']:
80
- if field['DisplayName'] in credentials_dict:
81
- credentials_dict[field['GenericFieldID']] = credentials_dict[field['DisplayName']]
82
- credentials_dict.pop(field['DisplayName'])
39
+ return self._publish_new_password(data)
83
40
 
84
- response = requests.put(str(self.password_url), json=credentials_dict, headers=self.headers)
85
- if response.status_code == 200:
86
- logger.debug(f"Credentials for {credentials_dict['UserName']} updated")
87
- return True
88
- else:
89
- logger.error(f"Failed to update credentials for {credentials_dict['UserName']}")
90
- return False
91
41
 
92
- def new_credentials(self, credentials_dict: dict) -> bool:
42
+ class AsyncFTPCredentialManager(AsyncCredentialManager):
43
+ def __init__(self, passwordState_api_key: str):
44
+ super().__init__(passwordState_api_key, 208)
45
+
46
+ async def new_credentials(self, credentials_dict: dict) -> bool:
93
47
  """
94
48
  Create a new credential entry
95
49
 
@@ -101,7 +55,7 @@ class FTPCredentialManager:
101
55
  - FTP/SFTP (FTP or SFTP)
102
56
 
103
57
  :param credentials_dict:
104
- :return: True if successful, False otherwise
58
+ :return:
105
59
  """
106
60
 
107
61
  data = {
@@ -115,10 +69,4 @@ class FTPCredentialManager:
115
69
  "GenericField3": credentials_dict['FTP/SFTP']
116
70
  }
117
71
 
118
- response = requests.post(str(self.password_url), json=data, headers=self.headers)
119
- if response.status_code == 201:
120
- logger.debug(f"New credentials for {credentials_dict['UserName']} created")
121
- return True
122
- else:
123
- logger.error(f"Failed to create new credentials for {credentials_dict['UserName']}")
124
- return False
72
+ return await self._publish_new_password(data)
@@ -1,95 +1,52 @@
1
1
  import logging
2
2
 
3
- import requests
4
- from yarl import URL
3
+ import aiohttp
5
4
 
6
- from wcp_library.credentials import MissingCredentialsError
5
+ from wcp_library.credentials.credential_manager_asynchronous import AsyncCredentialManager
6
+ from wcp_library.credentials.credential_manager_synchronous import CredentialManager
7
7
 
8
8
  logger = logging.getLogger(__name__)
9
9
 
10
10
 
11
- class OracleCredentialManager:
11
+ class OracleCredentialManager(CredentialManager):
12
12
  def __init__(self, passwordState_api_key: str):
13
- self.password_url = URL("https://vault.wcap.ca/api/passwords/")
14
- self.api_key = passwordState_api_key
15
- self.headers = {"APIKey": self.api_key, 'Reason': 'Python Script Access'}
16
- self._password_list_id = 207
13
+ super().__init__(passwordState_api_key, 207)
17
14
 
18
- def _get_credentials(self) -> dict:
19
- """
20
- Get all credentials from the password list
21
-
22
- :return: Dictionary of credentials
23
- """
24
-
25
- logger.debug("Getting credentials from PasswordState")
26
- url = (self.password_url / str(self._password_list_id)).with_query("QueryAll")
27
- passwords = requests.get(str(url), headers=self.headers).json()
28
-
29
- if not passwords:
30
- raise MissingCredentialsError("No credentials found in this Password List")
31
-
32
- password_dict = {}
33
- for password in passwords:
34
- password_info = {'PasswordID': password['PasswordID'], 'UserName': password['UserName'], 'Password': password['Password']}
35
- for field in password['GenericFieldInfo']:
36
- password_info[field['DisplayName']] = field['Value'].lower() if field['DisplayName'].lower() == 'username' else field['Value']
37
- password_dict[password['UserName'].lower()] = password_info
38
- logger.debug("Credentials retrieved")
39
- return password_dict
40
-
41
- def get_credentials(self, username: str) -> dict:
42
- """
43
- Get the credentials for a specific username
44
-
45
- :param username:
46
- :return: Dictionary of credentials
47
- """
48
-
49
- logger.debug(f"Getting credentials for {username}")
50
- credentials = self._get_credentials()
51
-
52
- try:
53
- return_credential = credentials[username.lower()]
54
- except KeyError:
55
- raise MissingCredentialsError(f"Credentials for {username} not found in this Password List")
56
- logger.debug(f"Credentials for {username} retrieved")
57
- return return_credential
58
-
59
- def update_credential(self, credentials_dict: dict) -> bool:
15
+ def new_credentials(self, credentials_dict: dict) -> bool:
60
16
  """
61
- Update the credentials for a specific username
17
+ Create a new credential entry
62
18
 
63
19
  Credentials dictionary must have the following keys:
64
- - PasswordID
65
20
  - UserName
66
21
  - Password
67
-
68
- The dictionary should be obtained from the get_credentials method and modified accordingly
22
+ - Host
23
+ - Port
24
+ - Service or SID
69
25
 
70
26
  :param credentials_dict:
71
27
  :return: True if successful, False otherwise
72
28
  """
73
29
 
74
- logger.debug(f"Updating credentials for {credentials_dict['UserName']}")
75
- url = (self.password_url / str(self._password_list_id)).with_query("QueryAll")
76
- passwords = requests.get(str(url), headers=self.headers).json()
30
+ data = {
31
+ "PasswordListID": self._password_list_id,
32
+ "Title": credentials_dict['UserName'].upper() if "Title" not in credentials_dict else credentials_dict['Title'].upper(),
33
+ "Notes": credentials_dict['Notes'] if 'Notes' in credentials_dict else None,
34
+ "UserName": credentials_dict['UserName'].lower(),
35
+ "Password": credentials_dict['Password'],
36
+ "GenericField1": credentials_dict['Host'],
37
+ "GenericField2": credentials_dict['Port'],
38
+ "GenericField3": credentials_dict['Service'] if 'Service' in credentials_dict else None,
39
+ "GenericField4": credentials_dict['SID'] if 'SID' in credentials_dict else None
40
+ }
77
41
 
78
- relevant_credential_entry = [x for x in passwords if x['UserName'] == credentials_dict['UserName']][0]
79
- for field in relevant_credential_entry['GenericFieldInfo']:
80
- if field['DisplayName'] in credentials_dict:
81
- credentials_dict[field['GenericFieldID']] = credentials_dict[field['DisplayName']]
82
- credentials_dict.pop(field['DisplayName'])
42
+ return self._publish_new_password(data)
83
43
 
84
- response = requests.put(str(self.password_url), json=credentials_dict, headers=self.headers)
85
- if response.status_code == 200:
86
- logger.debug(f"Credentials for {credentials_dict['UserName']} updated")
87
- return True
88
- else:
89
- logger.error(f"Failed to update credentials for {credentials_dict['UserName']}")
90
- return False
91
44
 
92
- def new_credentials(self, credentials_dict: dict) -> bool:
45
+ class AsyncOracleCredentialManager(AsyncCredentialManager):
46
+ def __init__(self, passwordState_api_key: str):
47
+ super().__init__(passwordState_api_key, 207)
48
+
49
+ async def new_credentials(self, credentials_dict: dict) -> bool:
93
50
  """
94
51
  Create a new credential entry
95
52
 
@@ -101,7 +58,7 @@ class OracleCredentialManager:
101
58
  - Service or SID
102
59
 
103
60
  :param credentials_dict:
104
- :return: True if successful, False otherwise
61
+ :return:
105
62
  """
106
63
 
107
64
  data = {
@@ -116,10 +73,5 @@ class OracleCredentialManager:
116
73
  "GenericField4": credentials_dict['SID'] if 'SID' in credentials_dict else None
117
74
  }
118
75
 
119
- response = requests.post(str(self.password_url), json=data, headers=self.headers)
120
- if response.status_code == 201:
121
- logger.debug(f"New credentials for {credentials_dict['UserName']} created")
122
- return True
123
- else:
124
- logger.error(f"Failed to create new credentials for {credentials_dict['UserName']}")
125
- return False
76
+ return await self._publish_new_password(data)
77
+