1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 """Authentication Library for authorizing clients."""
21
22 from oauth import oauth
23 import json, urllib2, urllib
24 from time import sleep
25
26
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
31
33 """A base OAuthAuthenticator."""
34
35 _credentials = None
36
46
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
62 signature_method = oauth.OAuthSignatureMethod_PLAINTEXT()
63 oauth_req.sign_request(signature_method, consumer, token)
64 return oauth_req.to_header()
65
67 """Load the credentials.
68
69 To be overridden by subclasses.
70 """
71 raise NotImplementedError("load_credentials has not been implemented.")
72
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
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
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
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
122 self._authorize_credentials(email)
123
124 sleep(1)
125 self._test_credentials()
126