Skip to content

Commit 6abf870

Browse files
committed
Moved OAuth 2.0 samples up to the top level.
1 parent 6f3014a commit 6abf870

File tree

10 files changed

+239
-466
lines changed

10 files changed

+239
-466
lines changed

.hgignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
syntax: glob
22

33
*.pyc
4+
*.pyc-2.4
45
*.dat
56
.*.swp
67
*/.git/*

samples/appengine/main.py

Lines changed: 31 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,13 @@
2121
import httplib2
2222
import logging
2323
import os
24+
import pickle
2425

2526
from apiclient.discovery import build
26-
from apiclient.ext.appengine import FlowThreeLeggedProperty
27-
from apiclient.ext.appengine import OAuthCredentialsProperty
28-
from apiclient.oauth import FlowThreeLegged
27+
from oauth2client.appengine import CredentialsProperty
28+
from oauth2client.appengine import StorageByKeyName
29+
from oauth2client.client import OAuth2WebServerFlow
30+
from google.appengine.api import memcache
2931
from google.appengine.api import users
3032
from google.appengine.ext import db
3133
from google.appengine.ext import webapp
@@ -34,65 +36,60 @@
3436
from google.appengine.ext.webapp.util import login_required
3537

3638

37-
class Flow(db.Model):
38-
# FlowThreeLegged could also be stored in memcache.
39-
flow = FlowThreeLeggedProperty()
40-
41-
4239
class Credentials(db.Model):
43-
credentials = OAuthCredentialsProperty()
40+
credentials = CredentialsProperty()
4441

4542

4643
class MainHandler(webapp.RequestHandler):
4744

4845
@login_required
4946
def get(self):
5047
user = users.get_current_user()
51-
c = Credentials.get_by_key_name(user.user_id())
48+
credentials = StorageByKeyName(
49+
Credentials, user.user_id(), 'credentials').get()
50+
51+
if credentials is None or credentials.invalid == True:
52+
flow = OAuth2WebServerFlow(
53+
# Visit https://code.google.com/apis/console to
54+
# generate your client_id, client_secret and to
55+
# register your redirect_uri.
56+
client_id='<YOUR CLIENT ID HERE>',
57+
client_secret='<YOUR CLIENT SECRET HERE>',
58+
scope='https://www.googleapis.com/auth/buzz',
59+
user_agent='buzz-cmdline-sample/1.0',
60+
domain='anonymous',
61+
xoauth_displayname='Google App Engine Example App')
5262

53-
if c:
63+
callback = self.request.relative_url('/auth_return')
64+
authorize_url = flow.step1_get_authorize_url(callback)
65+
memcache.set(user.user_id(), pickle.dumps(flow))
66+
self.redirect(authorize_url)
67+
else:
5468
http = httplib2.Http()
55-
http = c.credentials.authorize(http)
69+
http = credentials.authorize(http)
5670
service = build("buzz", "v1", http=http)
5771
activities = service.activities()
5872
activitylist = activities.list(scope='@consumption',
5973
userId='@me').execute()
60-
logging.info(activitylist)
6174
path = os.path.join(os.path.dirname(__file__), 'welcome.html')
6275
logout = users.create_logout_url('/')
6376
self.response.out.write(
6477
template.render(
6578
path, {'activitylist': activitylist,
6679
'logout': logout
6780
}))
68-
else:
69-
p = build("buzz", "v1")
70-
flow = FlowThreeLegged(p.auth_discovery(),
71-
consumer_key='anonymous',
72-
consumer_secret='anonymous',
73-
user_agent='google-api-client-python-buzz-webapp/1.0',
74-
domain='anonymous',
75-
scope='https://www.googleapis.com/auth/buzz',
76-
xoauth_displayname='Example Web App')
77-
78-
callback = self.request.relative_url('/auth_return')
79-
authorize_url = flow.step1_get_authorize_url(callback)
80-
f = Flow(key_name=user.user_id(), flow=flow)
81-
f.put()
82-
self.redirect(authorize_url)
8381

8482

8583
class OAuthHandler(webapp.RequestHandler):
8684

8785
@login_required
8886
def get(self):
8987
user = users.get_current_user()
90-
f = Flow.get_by_key_name(user.user_id())
91-
if f:
92-
credentials = f.flow.step2_exchange(self.request.params)
93-
c = Credentials(key_name=user.user_id(), credentials=credentials)
94-
c.put()
95-
f.delete()
88+
flow = pickle.loads(memcache.get(user.user_id()))
89+
if flow:
90+
credentials = flow.step2_exchange(self.request.params)
91+
StorageByKeyName(
92+
Credentials, user.user_id(), 'credentials').put(credentials)
9693
self.redirect("/")
9794
else:
9895
pass

samples/buzz/buzz.py

Lines changed: 65 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -11,85 +11,85 @@
1111

1212
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
1313

14-
from apiclient.discovery import build
15-
from apiclient.oauth import FlowThreeLegged
16-
from apiclient.ext.authtools import run
17-
from apiclient.ext.file import Storage
18-
from apiclient.oauth import CredentialsInvalidError
19-
14+
import gflags
2015
import httplib2
16+
import logging
2117
import pprint
18+
import sys
19+
20+
from apiclient.discovery import build
21+
from oauth2client.file import Storage
22+
from oauth2client.client import OAuth2WebServerFlow
23+
from oauth2client.tools import run
24+
25+
FLAGS = gflags.FLAGS
26+
FLOW = OAuth2WebServerFlow(
27+
client_id='433807057907.apps.googleusercontent.com',
28+
client_secret='jigtZpMApkRxncxikFpR+SFg',
29+
scope='https://www.googleapis.com/auth/buzz',
30+
user_agent='buzz-cmdline-sample/1.0')
2231

23-
# Uncomment the next line to get very detailed logging
24-
#httplib2.debuglevel = 4
32+
gflags.DEFINE_enum('logging_level', 'ERROR',
33+
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
34+
'Set the level of logging detail.')
2535

2636

27-
def main():
37+
def main(argv):
38+
try:
39+
argv = FLAGS(argv)
40+
except gflags.FlagsError, e:
41+
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
42+
sys.exit(1)
43+
44+
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
45+
2846
storage = Storage('buzz.dat')
2947
credentials = storage.get()
3048
if credentials is None or credentials.invalid == True:
31-
buzz_discovery = build("buzz", "v1").auth_discovery()
32-
33-
flow = FlowThreeLegged(buzz_discovery,
34-
consumer_key='anonymous',
35-
consumer_secret='anonymous',
36-
user_agent='python-buzz-sample/1.0',
37-
domain='anonymous',
38-
scope='https://www.googleapis.com/auth/buzz',
39-
xoauth_displayname='Google API Client Example App')
40-
41-
credentials = run(flow, storage)
49+
credentials = run(FLOW, storage)
4250

4351
http = httplib2.Http()
4452
http = credentials.authorize(http)
4553

54+
# Build the Buzz service
4655
service = build("buzz", "v1", http=http,
47-
developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0")
56+
developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0")
4857
activities = service.activities()
4958

50-
try:
51-
# Retrieve the first two activities
52-
activitylist = activities.list(
53-
max_results='2', scope='@self', userId='@me').execute()
54-
print "Retrieved the first two activities"
55-
56-
# Retrieve the next two activities
57-
if activitylist:
58-
activitylist = activities.list_next(activitylist).execute()
59-
print "Retrieved the next two activities"
60-
61-
# Add a new activity
62-
new_activity_body = {
63-
"data": {
64-
'title': 'Testing insert',
65-
'object': {
66-
'content':
67-
u'Just a short note to show that insert is working. ☄',
68-
'type': 'note'}
69-
}
70-
}
71-
activity = activities.insert(
72-
userId='@me', body=new_activity_body).execute()
73-
print "Added a new activity"
74-
75-
activitylist = activities.list(
76-
max_results='2', scope='@self', userId='@me').execute()
77-
78-
# Add a comment to that activity
79-
comment_body = {
80-
"data": {
81-
"content": "This is a comment"
82-
}
83-
}
84-
item = activitylist['items'][0]
85-
comment = service.comments().insert(
86-
userId=item['actor']['id'], postId=item['id'], body=comment_body
87-
).execute()
88-
print 'Added a comment to the new activity'
89-
pprint.pprint(comment)
90-
except CredentialsInvalidError:
91-
print 'Your credentials are no longer valid.'
92-
print 'Please re-run this application to re-authorize.'
59+
# Retrieve the first two activities
60+
activitylist = activities.list(
61+
max_results='2', scope='@self', userId='@me').execute()
62+
print "Retrieved the first two activities"
63+
64+
# Retrieve the next two activities
65+
if activitylist:
66+
activitylist = activities.list_next(activitylist).execute()
67+
print "Retrieved the next two activities"
68+
69+
# Add a new activity
70+
new_activity_body = {
71+
'title': 'Testing insert',
72+
'object': {
73+
'content':
74+
u'Just a short note to show that insert is working. ☄',
75+
'type': 'note'}
76+
}
77+
activity = activities.insert(userId='@me', body=new_activity_body).execute()
78+
print "Added a new activity"
79+
80+
activitylist = activities.list(
81+
max_results='2', scope='@self', userId='@me').execute()
82+
83+
# Add a comment to that activity
84+
comment_body = {
85+
"content": "This is a comment"
86+
}
87+
item = activitylist['items'][0]
88+
comment = service.comments().insert(
89+
userId=item['actor']['id'], postId=item['id'], body=comment_body
90+
).execute()
91+
print 'Added a comment to the new activity'
92+
pprint.pprint(comment)
9393

9494
if __name__ == '__main__':
95-
main()
95+
main(sys.argv)

samples/django_sample/buzz/models.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,29 +5,29 @@
55
from django.contrib.auth.models import User
66
from django.db import models
77

8-
from apiclient.ext.django_orm import FlowThreeLeggedField
9-
from apiclient.ext.django_orm import OAuthCredentialsField
8+
from oauth2client.django_orm import FlowField
9+
from oauth2client.django_orm import CredentialsField
1010

1111
# The Flow could also be stored in memcache since it is short lived.
1212

1313

14-
class Flow(models.Model):
14+
class FlowModel(models.Model):
1515
id = models.ForeignKey(User, primary_key=True)
16-
flow = FlowThreeLeggedField()
16+
flow = FlowField()
1717

1818

19-
class Credential(models.Model):
19+
class CredentialsModel(models.Model):
2020
id = models.ForeignKey(User, primary_key=True)
21-
credential = OAuthCredentialsField()
21+
credential = CredentialsField()
2222

2323

24-
class CredentialAdmin(admin.ModelAdmin):
24+
class CredentialsAdmin(admin.ModelAdmin):
2525
pass
2626

2727

2828
class FlowAdmin(admin.ModelAdmin):
2929
pass
3030

3131

32-
admin.site.register(Credential, CredentialAdmin)
33-
admin.site.register(Flow, FlowAdmin)
32+
admin.site.register(CredentialsModel, CredentialsAdmin)
33+
admin.site.register(FlowModel, FlowAdmin)

samples/django_sample/buzz/views.py

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,13 @@
55
from django.http import HttpResponse
66
from django.core.urlresolvers import reverse
77
from django.contrib.auth.decorators import login_required
8-
from django_sample.buzz.models import Credential, Flow
8+
9+
from oauth2client.django_orm import Storage
10+
from oauth2client.client import OAuth2WebServerFlow
11+
from django_sample.buzz.models import CredentialsModel
12+
from django_sample.buzz.models import FlowModel
913
from apiclient.discovery import build
10-
from apiclient.oauth import FlowThreeLegged
14+
1115
from django.http import HttpResponseRedirect
1216
from django.shortcuts import render_to_response
1317

@@ -16,10 +20,23 @@
1620

1721
@login_required
1822
def index(request):
19-
try:
20-
c = Credential.objects.get(id=request.user)
23+
storage = Storage(CredentialsModel, 'id', request.user, 'credential')
24+
credential = storage.get()
25+
if credential is None or credential.invalid == True:
26+
flow = OAuth2WebServerFlow(
27+
client_id='837647042410.apps.googleusercontent.com',
28+
client_secret='+SWwMCL9d8gWtzPRa1lXw5R8',
29+
scope='https://www.googleapis.com/auth/buzz',
30+
user_agent='buzz-django-sample/1.0',
31+
)
32+
33+
authorize_url = flow.step1_get_authorize_url(STEP2_URI)
34+
f = FlowModel(id=request.user, flow=flow)
35+
f.save()
36+
return HttpResponseRedirect(authorize_url)
37+
else:
2138
http = httplib2.Http()
22-
http = c.credential.authorize(http)
39+
http = credential.authorize(http)
2340
service = build("buzz", "v1", http=http)
2441
activities = service.activities()
2542
activitylist = activities.list(scope='@consumption',
@@ -30,30 +47,15 @@ def index(request):
3047
'activitylist': activitylist,
3148
})
3249

33-
except Credential.DoesNotExist:
34-
service = build("buzz", "v1")
35-
flow = FlowThreeLegged(service.auth_discovery(),
36-
consumer_key='anonymous',
37-
consumer_secret='anonymous',
38-
user_agent='google-api-client-python-buzz-django/1.0',
39-
domain='anonymous',
40-
scope='https://www.googleapis.com/auth/buzz',
41-
xoauth_displayname='Django Example Web App')
42-
43-
authorize_url = flow.step1_get_authorize_url(STEP2_URI)
44-
f = Flow(id=request.user, flow=flow)
45-
f.save()
46-
return HttpResponseRedirect(authorize_url)
47-
4850

4951
@login_required
5052
def auth_return(request):
5153
try:
52-
f = Flow.objects.get(id=request.user)
54+
f = FlowModel.objects.get(id=request.user)
5355
credential = f.flow.step2_exchange(request.REQUEST)
54-
c = Credential(id=request.user, credential=credential)
55-
c.save()
56+
storage = Storage(CredentialsModel, 'id', request.user, 'credential')
57+
storage.put(credential)
5658
f.delete()
5759
return HttpResponseRedirect("/")
58-
except Flow.DoesNotExist:
60+
except FlowModel.DoesNotExist:
5961
pass

0 commit comments

Comments
 (0)