/atom/token_store.py

http://radioappz.googlecode.com/ · Python · 117 lines · 40 code · 14 blank · 63 comment · 14 complexity · c49443de339d8a40c79d10b537c9c346 MD5 · raw file

  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2008 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """This module provides a TokenStore class which is designed to manage
  17. auth tokens required for different services.
  18. Each token is valid for a set of scopes which is the start of a URL. An HTTP
  19. client will use a token store to find a valid Authorization header to send
  20. in requests to the specified URL. If the HTTP client determines that a token
  21. has expired or been revoked, it can remove the token from the store so that
  22. it will not be used in future requests.
  23. """
  24. __author__ = 'api.jscudder (Jeff Scudder)'
  25. import atom.http_interface
  26. import atom.url
  27. SCOPE_ALL = 'http'
  28. class TokenStore(object):
  29. """Manages Authorization tokens which will be sent in HTTP headers."""
  30. def __init__(self, scoped_tokens=None):
  31. self._tokens = scoped_tokens or {}
  32. def add_token(self, token):
  33. """Adds a new token to the store (replaces tokens with the same scope).
  34. Args:
  35. token: A subclass of http_interface.GenericToken. The token object is
  36. responsible for adding the Authorization header to the HTTP request.
  37. The scopes defined in the token are used to determine if the token
  38. is valid for a requested scope when find_token is called.
  39. Returns:
  40. True if the token was added, False if the token was not added becase
  41. no scopes were provided.
  42. """
  43. if not hasattr(token, 'scopes') or not token.scopes:
  44. return False
  45. for scope in token.scopes:
  46. self._tokens[str(scope)] = token
  47. return True
  48. def find_token(self, url):
  49. """Selects an Authorization header token which can be used for the URL.
  50. Args:
  51. url: str or atom.url.Url or a list containing the same.
  52. The URL which is going to be requested. All
  53. tokens are examined to see if any scopes begin match the beginning
  54. of the URL. The first match found is returned.
  55. Returns:
  56. The token object which should execute the HTTP request. If there was
  57. no token for the url (the url did not begin with any of the token
  58. scopes available), then the atom.http_interface.GenericToken will be
  59. returned because the GenericToken calls through to the http client
  60. without adding an Authorization header.
  61. """
  62. if url is None:
  63. return None
  64. if isinstance(url, (str, unicode)):
  65. url = atom.url.parse_url(url)
  66. if url in self._tokens:
  67. token = self._tokens[url]
  68. if token.valid_for_scope(url):
  69. return token
  70. else:
  71. del self._tokens[url]
  72. for scope, token in self._tokens.iteritems():
  73. if token.valid_for_scope(url):
  74. return token
  75. return atom.http_interface.GenericToken()
  76. def remove_token(self, token):
  77. """Removes the token from the token_store.
  78. This method is used when a token is determined to be invalid. If the
  79. token was found by find_token, but resulted in a 401 or 403 error stating
  80. that the token was invlid, then the token should be removed to prevent
  81. future use.
  82. Returns:
  83. True if a token was found and then removed from the token
  84. store. False if the token was not in the TokenStore.
  85. """
  86. token_found = False
  87. scopes_to_delete = []
  88. for scope, stored_token in self._tokens.iteritems():
  89. if stored_token == token:
  90. scopes_to_delete.append(scope)
  91. token_found = True
  92. for scope in scopes_to_delete:
  93. del self._tokens[scope]
  94. return token_found
  95. def remove_all_tokens(self):
  96. self._tokens = {}