Statistics
| Branch: | Tag: | Revision:

root / astakos / im / target / twitter.py @ 64cd4730

History | View | Annotate | Download (4.9 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
41
from django.utils import simplejson as json
42

    
43
from astakos.im.target.util import get_or_create_user, prepare_response
44

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

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

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

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

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