Statistics
| Branch: | Tag: | Revision:

root / pithos / im / twitter.py @ 1a7c659b

History | View | Annotate | Download (4.8 kB)

1
# Copyright 2011 GRNET S.A. All rights reserved.
2
# 
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
# 
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
# 
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
# 
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
# 
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
# This is based on the docs at: https://github.com/simplegeo/python-oauth2
35

    
36
import oauth2 as oauth
37
import urlparse
38

    
39
from django.conf import settings
40
from django.http import HttpResponse, HttpResponseRedirect
41

    
42
from models import User
43

    
44
# It's probably a good idea to put your consumer's OAuth token and
45
# OAuth secret into your project's settings. 
46
consumer = oauth.Consumer(settings.TWITTER_KEY, settings.TWITTER_SECRET)
47
client = oauth.Client(consumer)
48

    
49
request_token_url = 'http://twitter.com/oauth/request_token'
50
access_token_url = 'http://twitter.com/oauth/access_token'
51

    
52
# This is the slightly different URL used to authenticate/authorize.
53
authenticate_url = 'http://twitter.com/oauth/authenticate'
54

    
55
def login(request):
56
    # Step 1. Get a request token from Twitter.
57
    resp, content = client.request(request_token_url, "GET")
58
    if resp['status'] != '200':
59
        raise Exception("Invalid response from Twitter.")
60
    
61
    # Step 2. Store the request token in a session for later use.
62
    response = HttpResponse()
63
    response.set_cookie('Twitter-Request-Token', value=content, max_age=300)
64
    
65
    # Step 3. Redirect the user to the authentication URL.
66
    request_token = dict(urlparse.parse_qsl(content))
67
    url = "%s?oauth_token=%s" % (authenticate_url,
68
        request_token['oauth_token'])
69
    response['Location'] = url
70
    response.status_code = 302
71
    
72
    return response
73

    
74
def authenticated(request):
75
    # Step 1. Use the request token in the session to build a new client.
76
    content = request.COOKIES.get('Twitter-Request-Token', None)
77
    if not content:
78
        raise Exception("Request token cookie not found.")
79
    request_token = dict(urlparse.parse_qsl(content))
80
    token = oauth.Token(request_token['oauth_token'],
81
        request_token['oauth_token_secret'])
82
    client = oauth.Client(consumer, token)
83
    
84
    # Step 2. Request the authorized access token from Twitter.
85
    resp, content = client.request(access_token_url, "GET")
86
    if resp['status'] != '200':
87
        raise Exception("Invalid response from Twitter.")
88
    
89
    """
90
    This is what you'll get back from Twitter. Note that it includes the
91
    user's user_id and screen_name.
92
    {
93
        'oauth_token_secret': 'IcJXPiJh8be3BjDWW50uCY31chyhsMHEhqJVsphC3M',
94
        'user_id': '120889797', 
95
        'oauth_token': '120889797-H5zNnM3qE0iFoTTpNEHIz3noL9FKzXiOxwtnyVOD',
96
        'screen_name': 'heyismysiteup'
97
    }
98
    """
99
    access_token = dict(urlparse.parse_qsl(content))
100
    
101
    # Step 3. Lookup the user or create them if they don't exist.
102
    try:
103
        user = User.objects.get(uniq=access_token['screen_name'])
104
    except User.DoesNotExist:
105
        # When creating the user I just use their screen_name@twitter.com
106
        # for their email and the oauth_token_secret for their password.
107
        # These two things will likely never be used. Alternatively, you 
108
        # can prompt them for their email here. Either way, the password 
109
        # should never be used.
110
        user = User()
111
        user.uniq = '%s@twitter.com' % access_token['screen_name']
112
        user.realname = access_token['oauth_token']
113
        user.affiliation = 'Twitter'
114
        user.renew_token()
115
        user.auth_token = access_token['oauth_token_secret']
116
        user.save()
117
    
118
    response = HttpResponse()
119
    response.content = user.uniq + '\n' + user.auth_token + '\n'
120
    response.status_code = 200
121
    return response