Skip to content

Clean up (mostly PEP8) #206

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@
coverage.xml
nosetests.xml
.tox
.idea
*.iml
19 changes: 12 additions & 7 deletions example/appengine_oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,12 @@
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import util
import oauth2 as oauth # httplib2 is required for this to work on AppEngine
import oauth2 as oauth # httplib2 is required for this to work on AppEngine


class Client(db.Model):
# oauth_key is the Model's key_name field
oauth_secret = db.StringProperty() # str(uuid.uuid4()) works well for this
oauth_secret = db.StringProperty() # str(uuid.uuid4()) works well for this
first_name = db.StringProperty()
last_name = db.StringProperty()
email_address = db.EmailProperty(required=True)
Expand All @@ -41,8 +42,8 @@ class Client(db.Model):
def secret(self):
return self.oauth_secret

class OAuthHandler(webapp.RequestHandler):

class OAuthHandler(webapp.RequestHandler):
def __init__(self):
self._server = oauth.Server()
self._server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
Expand All @@ -61,7 +62,8 @@ def get_oauth_request(self):
postdata = self.request.body

return oauth.Request.from_request(method, self.request.uri,
headers=self.request.headers, query_string=postdata)
headers=self.request.headers,
query_string=postdata)

def get_client(self, request=None):
"""Return the client from the OAuth parameters."""
Expand All @@ -70,8 +72,8 @@ def get_client(self, request=None):
request = self.get_oauth_request()
client_key = request.get_parameter('oauth_consumer_key')
if not client_key:
raise Exception('Missing "oauth_consumer_key" parameter in ' \
'OAuth "Authorization" header')
raise Exception('Missing "oauth_consumer_key" parameter in ' +
'OAuth "Authorization" header')

client = models.Client.get_by_key_name(client_key)
if not client:
Expand All @@ -91,6 +93,7 @@ def is_valid(self):

return client


class SampleHandler(OAuthHandler):
def get(self):
try:
Expand All @@ -99,10 +102,12 @@ def get(self):
self.error(500)
self.response.out.write(e)


def main():
application = webapp.WSGIApplication([(r'/sample', SampleHandler)],
debug=False)
debug=False)
util.run_wsgi_app(application)


if __name__ == '__main__':
main()
33 changes: 21 additions & 12 deletions example/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@
CONSUMER_KEY = 'key'
CONSUMER_SECRET = 'secret'


# example client using httplib with headers
class SimpleOAuthClient(oauth.OAuthClient):

def __init__(self, server, port=httplib.HTTP_PORT, request_token_url='',
access_token_url='', authorization_url=''):
self.server = server
Expand All @@ -57,44 +57,46 @@ def __init__(self, server, port=httplib.HTTP_PORT, request_token_url='',
self.access_token_url = access_token_url
self.authorization_url = authorization_url
self.connection = httplib.HTTPConnection(
"%s:%d" % (self.server, self.port))
"%s:%d" % (self.server, self.port))

def fetch_request_token(self, oauth_request):
# via headers
# -> OAuthToken
self.connection.request(oauth_request.http_method,
self.request_token_url, headers=oauth_request.to_header())
self.request_token_url,
headers=oauth_request.to_header())
response = self.connection.getresponse()
return oauth.OAuthToken.from_string(response.read())

def fetch_access_token(self, oauth_request):
# via headers
# -> OAuthToken
self.connection.request(oauth_request.http_method,
self.access_token_url, headers=oauth_request.to_header())
self.access_token_url,
headers=oauth_request.to_header())
response = self.connection.getresponse()
return oauth.OAuthToken.from_string(response.read())

def authorize_token(self, oauth_request):
# via url
# -> typically just some okay response
self.connection.request(oauth_request.http_method,
oauth_request.to_url())
oauth_request.to_url())
response = self.connection.getresponse()
return response.read()

def access_resource(self, oauth_request):
# via post body
# -> some protected resources
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
self.connection.request('POST', RESOURCE_URL,
body=oauth_request.to_postdata(),
headers=headers)
response = self.connection.getresponse()
return response.read()

def run_example():

def run_example():
# setup
print('** OAuth Python Library Example **')
client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
Expand Down Expand Up @@ -132,7 +134,8 @@ def run_example():
print('GOT')
print(response)
# sad way to get the verifier
import urlparse, cgi
import urlparse
import cgi
query = urlparse.urlparse(response)[4]
params = cgi.parse_qs(query, keep_blank_values=False)
verifier = params['oauth_verifier'][0]
Expand All @@ -159,10 +162,14 @@ def run_example():
print('* Access protected resources ...')
pause()
parameters = {'file': 'vacation.jpg',
'size': 'original'} # resource specific params
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
token=token, http_method='POST', http_url=RESOURCE_URL,
parameters=parameters)
'size': 'original'} # resource specific params
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer,
token=token,
http_method='POST',
http_url=RESOURCE_URL,
parameters=parameters
)
oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
print('REQUEST (via post body)')
print('parameters: %s' % str(oauth_request.parameters))
Expand All @@ -172,10 +179,12 @@ def run_example():
print('non-oauth parameters: %s' % params)
pause()


def pause():
print('')
time.sleep(1)


if __name__ == '__main__':
run_example()
print('Done.')
46 changes: 28 additions & 18 deletions example/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@
REALM = 'http://photos.example.net/'
VERIFIER = 'verifier'


# example store for one of each thing
class MockOAuthDataStore(oauth.OAuthDataStore):

def __init__(self):
self.consumer = oauth.OAuthConsumer('key', 'secret')
self.request_token = oauth.OAuthToken('requestkey', 'requestsecret')
Expand All @@ -54,17 +54,21 @@ def lookup_consumer(self, key):
def lookup_token(self, token_type, token):
token_attrib = getattr(self, '%s_token' % token_type)
if token == token_attrib.key:
## HACK
# HACK
token_attrib.set_callback(CALLBACK_URL)
return token_attrib
return None

def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
if (oauth_token and
oauth_consumer.key == self.consumer.key and
(oauth_token.key == self.request_token.key or
oauth_token.key == self.access_token.key) and
nonce == self.nonce):
if not oauth_token:
return None

consumer_key_set = oauth_consumer.key == self.consumer.key
access_token_equal = oauth_token.key == self.access_token.key
request_token_equal = oauth_token.key == self.request_token.key
token_set = access_token_equal or request_token_equal

if consumer_key_set and token_set and nonce == self.nonce:
return self.nonce
return None

Expand All @@ -78,9 +82,11 @@ def fetch_request_token(self, oauth_consumer, oauth_callback):
return None

def fetch_access_token(self, oauth_consumer, oauth_token, oauth_verifier):
if (oauth_consumer.key == self.consumer.key and
oauth_token.key == self.request_token.key and
oauth_verifier == self.verifier):
consumer_key_set = oauth_consumer.key == self.consumer.key
token_key_set = oauth_token.key == self.request_token.key
verifier_set = oauth_verifier == self.verifier

if consumer_key_set and token_key_set and verifier_set:
# want to check here if token is authorized
# for mock store, we assume it is
return self.access_token
Expand All @@ -93,14 +99,14 @@ def authorize_request_token(self, oauth_token, user):
return self.request_token
return None

class RequestHandler(BaseHTTPRequestHandler):

class RequestHandler(BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
self.oauth_server = oauth.OAuthServer(MockOAuthDataStore())
self.oauth_server.add_signature_method(
oauth.OAuthSignatureMethod_PLAINTEXT())
oauth.OAuthSignatureMethod_PLAINTEXT())
self.oauth_server.add_signature_method(
oauth.OAuthSignatureMethod_HMAC_SHA1())
oauth.OAuthSignatureMethod_HMAC_SHA1())
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)

# example way to send an oauth error
Expand All @@ -110,13 +116,13 @@ def send_oauth_error(self, err=None):
# return the authenticate header
header = oauth.build_authenticate_header(realm=REALM)
for k, v in header.iteritems():
self.send_header(k, v)
self.send_header(k, v)

def do_GET(self):

# debug info
#print self.command, self.path, self.headers
# print self.command, self.path, self.headers

# get the post data (if any)
postdata = None
if self.command == 'POST':
Expand All @@ -128,7 +134,9 @@ def do_GET(self):

# construct the oauth request from the request parameters
oauth_request = oauth.OAuthRequest.from_request(self.command,
self.path, headers=self.headers, query_string=postdata)
self.path,
headers=self.headers,
query_string=postdata)

# request token
if self.path.startswith(REQUEST_TOKEN_URL):
Expand Down Expand Up @@ -180,7 +188,7 @@ def do_GET(self):
try:
# verify the request has been oauth authorized
consumer, token, params = self.oauth_server.verify_request(
oauth_request)
oauth_request)
# send okay response
self.send_response(200, 'OK')
self.end_headers()
Expand All @@ -193,6 +201,7 @@ def do_GET(self):
def do_POST(self):
return self.do_GET()


def main():
try:
server = HTTPServer(('', 8080), RequestHandler)
Expand All @@ -201,5 +210,6 @@ def main():
except KeyboardInterrupt:
server.socket.close()


if __name__ == '__main__':
main()
Loading