Skip to content

Commit ef42e4b

Browse files
author
Daniel J Holmes (jaitaiwan)
committed
Update for py3k release
1 parent 1ff5e1d commit ef42e4b

File tree

4 files changed

+13
-374
lines changed

4 files changed

+13
-374
lines changed

.travis.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,7 @@ language: python
22
python:
33
- "2.6"
44
- "2.7"
5+
- "3.3"
6+
- "3.4"
57
install: "pip install -r requirements.txt"
68
script: py.test

README.md

Lines changed: 2 additions & 358 deletions
Original file line numberDiff line numberDiff line change
@@ -19,362 +19,6 @@ You can install `oauth2` via [the PIP package](https://pypi.python.org/pypi/oaut
1919

2020
We recommend using [virtualenv](https://virtualenv.pypa.io/en/latest/).
2121

22-
# Signing a Request
23-
24-
```python
25-
import oauth2 as oauth
26-
import time
27-
28-
# Set the API endpoint
29-
url = "http://example.com/photos"
30-
31-
# Set the base oauth_* parameters along with any other parameters required
32-
# for the API call.
33-
params = {
34-
'oauth_version': "1.0",
35-
'oauth_nonce': oauth.generate_nonce(),
36-
'oauth_timestamp': int(time.time()),
37-
'user': 'joestump',
38-
'photoid': 555555555555
39-
}
40-
41-
# Set up instances of our Token and Consumer. The Consumer.key and
42-
# Consumer.secret are given to you by the API provider. The Token.key and
43-
# Token.secret is given to you after a three-legged authentication.
44-
token = oauth.Token(key="tok-test-key", secret="tok-test-secret")
45-
consumer = oauth.Consumer(key="con-test-key", secret="con-test-secret")
46-
47-
# Set our token/key parameters
48-
params['oauth_token'] = token.key
49-
params['oauth_consumer_key'] = consumer.key
50-
51-
# Create our request. Change method, etc. accordingly.
52-
req = oauth.Request(method="GET", url=url, parameters=params)
53-
54-
# Sign the request.
55-
signature_method = oauth.SignatureMethod_HMAC_SHA1()
56-
req.sign_request(signature_method, consumer, token)
57-
```
58-
59-
# Using the Client
60-
61-
The <code>oauth2.Client</code> is based on <code>httplib2</code> and works just as you'd expect it to. The only difference is the first two arguments to the constructor are an instance of <code>oauth2.Consumer</code> and <code>oauth2.Token</code> (<code>oauth2.Token</code> is only needed for three-legged requests).
62-
63-
```python
64-
import oauth2 as oauth
65-
66-
# Create your consumer with the proper key/secret.
67-
consumer = oauth.Consumer(key="your-twitter-consumer-key",
68-
secret="your-twitter-consumer-secret")
69-
70-
# Request token URL for Twitter.
71-
request_token_url = "https://api.twitter.com/oauth/request_token"
72-
73-
# Create our client.
74-
client = oauth.Client(consumer)
75-
76-
# The OAuth Client request works just like httplib2 for the most part.
77-
resp, content = client.request(request_token_url, "GET")
78-
print resp
79-
print content
80-
```
81-
82-
# Twitter Three-legged OAuth Example
83-
84-
Below is an example of how one would go through a three-legged OAuth flow to
85-
gain access to protected resources on Twitter. This is a simple CLI script, but
86-
can be easily translated to a web application.
87-
88-
```python
89-
import urlparse
90-
import oauth2 as oauth
91-
92-
consumer_key = 'my_key_from_twitter'
93-
consumer_secret = 'my_secret_from_twitter'
94-
95-
request_token_url = 'https://api.twitter.com/oauth/request_token'
96-
access_token_url = 'https://api.twitter.com/oauth/access_token'
97-
authorize_url = 'https://api.twitter.com/oauth/authorize'
98-
99-
consumer = oauth.Consumer(consumer_key, consumer_secret)
100-
client = oauth.Client(consumer)
101-
102-
# Step 1: Get a request token. This is a temporary token that is used for
103-
# having the user authorize an access token and to sign the request to obtain
104-
# said access token.
105-
106-
resp, content = client.request(request_token_url, "GET")
107-
if resp['status'] != '200':
108-
raise Exception("Invalid response %s." % resp['status'])
109-
110-
request_token = dict(urlparse.parse_qsl(content))
111-
112-
print "Request Token:"
113-
print " - oauth_token = %s" % request_token['oauth_token']
114-
print " - oauth_token_secret = %s" % request_token['oauth_token_secret']
115-
print
116-
117-
# Step 2: Redirect to the provider. Since this is a CLI script we do not
118-
# redirect. In a web application you would redirect the user to the URL
119-
# below.
120-
121-
print "Go to the following link in your browser:"
122-
print "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token'])
123-
print
124-
125-
# After the user has granted access to you, the consumer, the provider will
126-
# redirect you to whatever URL you have told them to redirect to. You can
127-
# usually define this in the oauth_callback argument as well.
128-
accepted = 'n'
129-
while accepted.lower() == 'n':
130-
accepted = raw_input('Have you authorized me? (y/n) ')
131-
oauth_verifier = raw_input('What is the PIN? ')
132-
133-
# Step 3: Once the consumer has redirected the user back to the oauth_callback
134-
# URL you can request the access token the user has approved. You use the
135-
# request token to sign this request. After this is done you throw away the
136-
# request token and use the access token returned. You should store this
137-
# access token somewhere safe, like a database, for future use.
138-
token = oauth.Token(request_token['oauth_token'],
139-
request_token['oauth_token_secret'])
140-
token.set_verifier(oauth_verifier)
141-
client = oauth.Client(consumer, token)
142-
143-
resp, content = client.request(access_token_url, "POST")
144-
access_token = dict(urlparse.parse_qsl(content))
145-
146-
print "Access Token:"
147-
print " - oauth_token = %s" % access_token['oauth_token']
148-
print " - oauth_token_secret = %s" % access_token['oauth_token_secret']
149-
print
150-
print "You may now access protected resources using the access tokens above."
151-
print
152-
```
153-
154-
# Logging into Django w/ Twitter
155-
156-
Twitter also has the ability to authenticate a user [via an OAuth flow](https://dev.twitter.com/docs/auth/sign-twitter). This
157-
flow is exactly like the three-legged OAuth flow, except you send them to a
158-
slightly different URL to authorize them.
159-
160-
In this example we'll look at how you can implement this login flow using
161-
Django and python-oauth2.
162-
163-
## Set up a Profile model
164-
165-
You'll need a place to store all of your Twitter OAuth credentials after the
166-
user has logged in. In your app's `models.py` file you should add something
167-
that resembles the following model.
168-
169-
```python
170-
class Profile(models.Model):
171-
user = models.ForeignKey(User)
172-
oauth_token = models.CharField(max_length=200)
173-
oauth_secret = models.CharField(max_length=200)
174-
```
175-
176-
## Set up your Django views
177-
178-
### `urls.py`
179-
180-
Your `urls.py` should look something like the following. Basically, you need to
181-
have a login URL, a callback URL that Twitter will redirect your users back to,
182-
and a logout URL.
183-
184-
In this example `^login/` and `twitter_login` will send the user to Twitter to
185-
be logged in, `^login/authenticated/` and `twitter_authenticated` will confirm
186-
the login, create the account if necessary, and log the user into the
187-
application, and `^logout`/ logs the user out in the `twitter_logout` view.
188-
189-
```python
190-
from django.conf.urls.defaults import *
191-
from django.contrib import admin
192-
from mytwitterapp.views import twitter_login, twitter_logout, \
193-
twitter_authenticated
194-
195-
admin.autodiscover()
196-
197-
urlpatterns = patterns('',
198-
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
199-
url(r'^admin/', include(admin.site.urls)),
200-
url(r'^login/?$', twitter_login),
201-
url(r'^logout/?$', twitter_logout),
202-
url(r'^login/authenticated/?$', twitter_authenticated),
203-
)
204-
```
205-
206-
### `views.py`
207-
208-
*NOTE:* The following code was coded for Python 2.4 so some of the libraries
209-
and code here might need to be updated if you are using Python 2.6+.
210-
211-
```python
212-
# Python
213-
import oauth2 as oauth
214-
import cgi
215-
216-
# Django
217-
from django.shortcuts import render_to_response
218-
from django.http import HttpResponseRedirect
219-
from django.conf import settings
220-
from django.contrib.auth import authenticate, login, logout
221-
from django.contrib.auth.models import User
222-
from django.contrib.auth.decorators import login_required
223-
224-
# Project
225-
from mytwitterapp.models import Profile
226-
227-
# It's probably a good idea to put your consumer's OAuth token and
228-
# OAuth secret into your project's settings.
229-
consumer = oauth.Consumer(settings.TWITTER_TOKEN, settings.TWITTER_SECRET)
230-
client = oauth.Client(consumer)
231-
232-
request_token_url = 'https://api.twitter.com/oauth/request_token'
233-
access_token_url = 'https://api.twitter.com/oauth/access_token'
234-
235-
# This is the slightly different URL used to authenticate/authorize.
236-
authenticate_url = 'https://api.twitter.com/oauth/authenticate'
237-
238-
def twitter_login(request):
239-
# Step 1. Get a request token from Twitter.
240-
resp, content = client.request(request_token_url, "GET")
241-
if resp['status'] != '200':
242-
raise Exception("Invalid response from Twitter.")
243-
244-
# Step 2. Store the request token in a session for later use.
245-
request.session['request_token'] = dict(cgi.parse_qsl(content))
246-
247-
# Step 3. Redirect the user to the authentication URL.
248-
url = "%s?oauth_token=%s" % (authenticate_url,
249-
request.session['request_token']['oauth_token'])
250-
251-
return HttpResponseRedirect(url)
252-
253-
254-
@login_required
255-
def twitter_logout(request):
256-
# Log a user out using Django's logout function and redirect them
257-
# back to the homepage.
258-
logout(request)
259-
return HttpResponseRedirect('/')
260-
261-
def twitter_authenticated(request):
262-
# Step 1. Use the request token in the session to build a new client.
263-
token = oauth.Token(request.session['request_token']['oauth_token'],
264-
request.session['request_token']['oauth_token_secret'])
265-
token.set_verifier(request.GET['oauth_verifier'])
266-
client = oauth.Client(consumer, token)
267-
268-
# Step 2. Request the authorized access token from Twitter.
269-
resp, content = client.request(access_token_url, "GET")
270-
if resp['status'] != '200':
271-
print content
272-
raise Exception("Invalid response from Twitter.")
273-
274-
"""
275-
This is what you'll get back from Twitter. Note that it includes the
276-
user's user_id and screen_name.
277-
{
278-
'oauth_token_secret': 'IcJXPiJh8be3BjDWW50uCY31chyhsMHEhqJVsphC3M',
279-
'user_id': '120889797',
280-
'oauth_token': '120889797-H5zNnM3qE0iFoTTpNEHIz3noL9FKzXiOxwtnyVOD',
281-
'screen_name': 'heyismysiteup'
282-
}
283-
"""
284-
access_token = dict(cgi.parse_qsl(content))
285-
286-
# Step 3. Lookup the user or create them if they don't exist.
287-
try:
288-
user = User.objects.get(username=access_token['screen_name'])
289-
except User.DoesNotExist:
290-
# When creating the user I just use their screen_name@twitter.com
291-
# for their email and the oauth_token_secret for their password.
292-
# These two things will likely never be used. Alternatively, you
293-
# can prompt them for their email here. Either way, the password
294-
# should never be used.
295-
user = User.objects.create_user(access_token['screen_name'],
296-
'%s@twitter.com' % access_token['screen_name'],
297-
access_token['oauth_token_secret'])
298-
299-
# Save our permanent token and secret for later.
300-
profile = Profile()
301-
profile.user = user
302-
profile.oauth_token = access_token['oauth_token']
303-
profile.oauth_secret = access_token['oauth_token_secret']
304-
profile.save()
305-
306-
# Authenticate the user and log them in using Django's pre-built
307-
# functions for these things.
308-
user = authenticate(username=access_token['screen_name'],
309-
password=access_token['oauth_token_secret'])
310-
login(request, user)
311-
312-
return HttpResponseRedirect('/')
313-
```
314-
315-
### `settings.py`
316-
317-
* You'll likely want to set `LOGIN_URL` to `/login/` so that users are properly redirected to your Twitter login handler when you use `@login_required` in other parts of your Django app.
318-
* You can also set `AUTH_PROFILE_MODULE = 'mytwitterapp.Profile'` so that you can easily access the Twitter OAuth token/secret for that user using the `User.get_profile()` method in Django.
319-
320-
# XOAUTH for IMAP and SMTP
321-
322-
Gmail supports OAuth over IMAP and SMTP via a standard they call XOAUTH. This allows you to authenticate against Gmail's IMAP and SMTP servers using an OAuth token and secret. It also has the added benefit of allowing you to use vanilla SMTP and IMAP libraries. The `python-oauth2` package provides both IMAP and SMTP libraries that implement XOAUTH and wrap `imaplib.IMAP4_SSL` and `smtplib.SMTP`. This allows you to connect to Gmail with OAuth credentials using standard Python libraries.
323-
324-
## IMAP
325-
326-
```python
327-
import oauth2 as oauth
328-
import oauth2.clients.imap as imaplib
329-
330-
# Set up your Consumer and Token as per usual. Just like any other
331-
# three-legged OAuth request.
332-
consumer = oauth.Consumer('your_consumer_key', 'your_consumer_secret')
333-
token = oauth.Token('your_users_3_legged_token',
334-
'your_users_3_legged_token_secret')
335-
336-
# Setup the URL according to Google's XOAUTH implementation. Be sure
337-
# to replace the email here with the appropriate email address that
338-
# you wish to access.
339-
url = "https://mail.google.com/mail/b/your_users_email@gmail.com/imap/"
340-
341-
conn = imaplib.IMAP4_SSL('imap.googlemail.com')
342-
conn.debug = 4
343-
344-
# This is the only thing in the API for impaplib.IMAP4_SSL that has
345-
# changed. You now authenticate with the URL, consumer, and token.
346-
conn.authenticate(url, consumer, token)
347-
348-
# Once authenticated everything from the impalib.IMAP4_SSL class will
349-
# work as per usual without any modification to your code.
350-
conn.select('INBOX')
351-
print conn.list()
352-
```
353-
354-
## SMTP
355-
356-
```python
357-
import oauth2 as oauth
358-
import oauth2.clients.smtp as smtplib
359-
360-
# Set up your Consumer and Token as per usual. Just like any other
361-
# three-legged OAuth request.
362-
consumer = oauth.Consumer('your_consumer_key', 'your_consumer_secret')
363-
token = oauth.Token('your_users_3_legged_token',
364-
'your_users_3_legged_token_secret')
365-
366-
# Setup the URL according to Google's XOAUTH implementation. Be sure
367-
# to replace the email here with the appropriate email address that
368-
# you wish to access.
369-
url = "https://mail.google.com/mail/b/your_users_email@gmail.com/smtp/"
370-
371-
conn = smtplib.SMTP('smtp.googlemail.com', 587)
372-
conn.set_debuglevel(True)
373-
conn.ehlo('test')
374-
conn.starttls()
375-
376-
# Again the only thing modified from smtplib.SMTP is the authenticate
377-
# method, which works identically to the imaplib.IMAP4_SSL method.
378-
conn.authenticate(url, consumer, token)
379-
```
22+
# Examples
38023

24+
Examples can be found in the [wiki](./wiki/)

0 commit comments

Comments
 (0)