Package u1rest :: Package lib :: Package auth :: Module baseauth
[hide private]
[frames] | no frames]

Source Code for Module u1rest.lib.auth.baseauth

  1  #Copyright (C) 2011 by John O'Brien 
  2  # 
  3  #Permission is hereby granted, free of charge, to any person obtaining a copy 
  4  #of this software and associated documentation files (the "Software"), to deal 
  5  #in the Software without restriction, including without limitation the rights 
  6  #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
  7  #copies of the Software, and to permit persons to whom the Software is 
  8  #furnished to do so, subject to the following conditions: 
  9  # 
 10  #The above copyright notice and this permission notice shall be included in 
 11  #all copies or substantial portions of the Software. 
 12  # 
 13  #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 14  #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 15  #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 16  #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 17  #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 18  #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 19  #THE SOFTWARE. 
 20  """Authentication Library for authorizing clients.""" 
 21   
 22  from oauth import oauth 
 23  import json, urllib2, urllib 
 24  from time import sleep 
 25  # pylint: disable=C0301 
 26  # URLS used for SSO and Ubuntu One OAuth token creation and authorization 
 27  REQUEST_URL = "https://login.ubuntu.com/api/1.0/authentications?ws.op=authenticate&token_name=Ubuntu%%20One%%20@%%20%(token_name)s" 
 28  AUTHORIZE_URL = 'https://one.ubuntu.com/oauth/sso-finished-so-get-tokens/%(email)s' 
 29  TEST_URL = "https://one.ubuntu.com/api/account/" 
 30  # pylint: enable=C0301 
 31   
32 -class BaseAuthenticator(object):
33 """A base OAuthAuthenticator.""" 34 35 _credentials = None 36
37 - def get_consumer_and_token(self):
38 """Get consumer and token from credentials.""" 39 if self._credentials is None: 40 self.load_credentials() 41 consumer = oauth.OAuthConsumer(self._credentials['consumer_key'], 42 self._credentials['consumer_secret']) 43 token = oauth.OAuthToken(self._credentials['token'], 44 self._credentials['token_secret']) 45 return consumer, token
46
47 - def get_auth_headers(self, url, params, http_method):
48 """Get authentication headers to be sent with the request. 49 50 @param url: The URL being requested. 51 @param params: A {dict} of quesry string parameters 52 @param http_method: The HTTP Method being used. 53 """ 54 consumer, token = self.get_consumer_and_token() 55 oauth_req = oauth.OAuthRequest.from_consumer_and_token( 56 http_url=url, 57 http_method=http_method, 58 token=token, 59 oauth_consumer=consumer, 60 parameters=params) 61 # using PLAINTEXT, because HMAC doesn't work for all urls 62 signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() 63 oauth_req.sign_request(signature_method, consumer, token) 64 return oauth_req.to_header()
65
66 - def load_credentials(self):
67 """Load the credentials. 68 69 To be overridden by subclasses. 70 """ 71 raise NotImplementedError("load_credentials has not been implemented.")
72
73 - def simple_signed_get_request(self, url):
74 """Handle a simple signed request. 75 76 @param url: The URL to sign and get. 77 """ 78 consumer, token = self.get_consumer_and_token() 79 req = oauth.OAuthRequest.from_consumer_and_token( 80 consumer, 81 token=token, 82 http_url=url) 83 req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), 84 consumer, token) 85 return urllib.urlopen(req.to_url())
86
87 - def _authorize_credentials(self, email):
88 """Authorize the OAuth SSO Request Token.""" 89 url = AUTHORIZE_URL % dict(email=email) 90 response = self.simple_signed_get_request(url) 91 if response.code == 200: 92 print "Token Succesfully Authorized" 93 else: 94 raise Exception( 95 "There was a problem Authorizing the Token\n%s" % response.read)
96
97 - def _test_credentials(self):
98 """Test the OAuth token against Ubuntu One.""" 99 response = self.simple_signed_get_request(TEST_URL) 100 if response.code == 200: 101 print "Auth token tested OK" 102 else: 103 raise Exception( 104 "There was a problem Testing the Token.\n%s" % response.read)
105
106 - def get_request_token(self, token_name, email, password):
107 """Get an OAuth request token from SSO. 108 109 @param token_name: A Name to give the OAuth Token. 110 @param email: Your SSO Email. 111 @param password: Your SSO Password. 112 """ 113 password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() 114 top_level_url = "https://login.ubuntu.com/api/1.0" 115 password_mgr.add_password(None, top_level_url, email, password) 116 handler = urllib2.HTTPBasicAuthHandler(password_mgr) 117 opener = urllib2.build_opener(handler) 118 response = opener.open(REQUEST_URL % dict(token_name=token_name)) 119 req_token = response.read() 120 self._credentials = json.loads(req_token) 121 # authorize the request token 122 self._authorize_credentials(email) 123 # give a moment for some SSO -> U1 chatter 124 sleep(1) 125 self._test_credentials()
126