Skip to content

Commit

Permalink
Revise and document api_key_access
Browse files Browse the repository at this point in the history
Simplifies the logic added in f68d0a2 (no need for try/catch)
  • Loading branch information
Deconstrained committed Feb 4, 2020
1 parent acd2138 commit 949d335
Showing 1 changed file with 27 additions and 17 deletions.
44 changes: 27 additions & 17 deletions pdpyras.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,33 @@ def api_key(self, api_key):
self.headers.update(self.auth_header)
self.after_set_api_key()

@property
def api_key_access(self):
"""
Memoized API key access type getter.
Will be "user" if the API key is a user-level token (all users should
have permission to create an API key with the same permissions as they
have in the PagerDuty web UI).
If the API key in use is an account-level API token (as only a global
administrator user can create), this property will be "account".
"""
if not hasattr(self, '_api_key_access') or self._api_key_access is None:
response = self.get('/users/me')
if response.status_code == 400:
message = try_decoding(response).get('error', '')
if 'account-level access token' in message:
self._api_key_access = 'account'
else:
self._api_key_access = None
self.log.error("Failed to obtain API key access level; "
"the API did not respond as expected.")
self.log.debug("Body = %s", response.text[:99])
else:
self._api_key_access = 'user'
return self._api_key_access

@property
def auth_header(self):
"""
Expand All @@ -399,23 +426,6 @@ def auth_header(self):
def cooldown_factor(self):
return self.sleep_timer_base*(1+self.stagger_cooldown*random())

@property
def api_key_access(self):
if not hasattr(self, '_api_key_access') or self._api_key_access is None:
try:
response = self.rget('/users/me')
self._api_key_access = 'user'
except PDClientError as e:
if e.response is not None:
message = e.response.json().get('error')
if e.response.status_code == 400 and 'account-level access token' in message:
self._api_key_access = 'account'
return self._api_key_access
self.log.error("Failed to obtain API key access level; encountered error")
self._api_key_access = None
raise e
return self._api_key_access

def postprocess(self, response):
"""
Perform supplemental actions immediately after receiving a response.
Expand Down

0 comments on commit 949d335

Please sign in to comment.