Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / target / twitter.py @ 73fbaec4

History | View | Annotate | Download (7.9 kB)

1
# Copyright 2011-2012 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
from django.http import HttpResponseBadRequest
35
from django.utils.translation import ugettext as _
36
from django.contrib import messages
37
from django.template import RequestContext
38
from django.views.decorators.http import require_http_methods
39
from django.http import HttpResponseRedirect
40
from django.core.urlresolvers import reverse
41
from django.core.exceptions import ImproperlyConfigured
42
from django.shortcuts import get_object_or_404
43

    
44
from urlparse import urlunsplit, urlsplit
45

    
46
from astakos.im.util import prepare_response, get_context
47
from astakos.im.views import (
48
    requires_anonymous, render_response, requires_auth_provider)
49
from astakos.im.settings import ENABLE_LOCAL_ACCOUNT_MIGRATION, BASEURL
50
from astakos.im.models import AstakosUser, PendingThirdPartyUser
51
from astakos.im.forms import LoginForm
52
from astakos.im.activation_backends import get_backend, SimpleBackend
53
from astakos.im import settings
54

    
55
import astakos.im.messages as astakos_messages
56

    
57
import logging
58

    
59
logger = logging.getLogger(__name__)
60

    
61
import oauth2 as oauth
62
import cgi
63

    
64
consumer = oauth.Consumer(settings.TWITTER_TOKEN, settings.TWITTER_SECRET)
65
client = oauth.Client(consumer)
66

    
67
request_token_url = 'http://twitter.com/oauth/request_token'
68
access_token_url = 'http://twitter.com/oauth/access_token'
69
authenticate_url = 'http://twitter.com/oauth/authenticate'
70

    
71

    
72
@requires_auth_provider('twitter', login=True)
73
@require_http_methods(["GET", "POST"])
74
def login(request):
75
    resp, content = client.request(request_token_url, "GET")
76
    if resp['status'] != '200':
77
        messages.error(request, 'Invalid Twitter response')
78
        return HttpResponseRedirect(reverse('edit_profile'))
79

    
80
    request.session['request_token'] = dict(cgi.parse_qsl(content))
81
    url = "%s?oauth_token=%s" % (authenticate_url,
82
        request.session['request_token']['oauth_token'])
83

    
84
    return HttpResponseRedirect(url)
85

    
86

    
87
@requires_auth_provider('twitter', login=True)
88
@require_http_methods(["GET", "POST"])
89
def authenticated(
90
    request,
91
    template='im/third_party_check_local.html',
92
    extra_context={}):
93

    
94
    if not 'request_token' in request.session:
95
        messages.error(request, 'Twitter handshake failed')
96
        return HttpResponseRedirect(reverse('edit_profile'))
97

    
98
    token = oauth.Token(request.session['request_token']['oauth_token'],
99
        request.session['request_token']['oauth_token_secret'])
100
    client = oauth.Client(consumer, token)
101

    
102
    # Step 2. Request the authorized access token from Twitter.
103
    resp, content = client.request(access_token_url, "GET")
104
    if resp['status'] != '200':
105
        try:
106
          del request.session['request_token']
107
        except:
108
          pass
109
        messages.error(request, 'Invalid Twitter response')
110
        return HttpResponseRedirect(reverse('edit_profile'))
111

    
112
    access_token = dict(cgi.parse_qsl(content))
113
    userid = access_token['user_id']
114

    
115
    # an existing user accessed the view
116
    if request.user.is_authenticated():
117
        if request.user.has_auth_provider('twitter', identifier=userid):
118
            return HttpResponseRedirect(reverse('edit_profile'))
119

    
120
        # automatically add eppn provider to user
121
        user = request.user
122
        if not request.user.can_add_auth_provider('twitter',
123
                                                  identifier=userid):
124
            messages.error(request, 'Account already exists.')
125
            return HttpResponseRedirect(reverse('edit_profile'))
126

    
127
        user.add_auth_provider('twitter', identifier=userid)
128
        return HttpResponseRedirect(reverse('edit_profile'))
129

    
130
    try:
131
        # astakos user exists ?
132
        user = AstakosUser.objects.get_auth_provider_user(
133
            'twitter',
134
            identifier=userid
135
        )
136
        if user.is_active:
137
            # authenticate user
138
            return prepare_response(request,
139
                                    user,
140
                                    request.GET.get('next'),
141
                                    'renew' in request.GET)
142
        elif not user.activation_sent:
143
            message = _('Your request is pending activation')
144
                        #TODO: use astakos_messages
145
            if not settings.MODERATION_ENABLED:
146
                url = user.get_resend_activation_url()
147
                msg_extra = _('<a href="%s">Resend activation email?</a>') % url
148
                message = message + u' ' + msg_extra
149

    
150
            messages.error(request, message)
151
            return HttpResponseRedirect(reverse('login'))
152

    
153
        else:
154
                        #TODO: use astakos_messages
155
            message = _(u'Account disabled. Please contact support')
156
            messages.error(request, message)
157
            return HttpResponseRedirect(reverse('login'))
158

    
159
    except AstakosUser.DoesNotExist, e:
160
                #TODO: use astakos_messages
161
        # eppn not stored in astakos models, create pending profile
162
        user, created = PendingThirdPartyUser.objects.get_or_create(
163
            third_party_identifier=userid,
164
            provider='twitter',
165
        )
166
        # update pending user
167
        user.affiliation = 'Twitter'
168
        user.generate_token()
169
        user.save()
170

    
171
        extra_context['provider'] = 'twitter'
172
        extra_context['token'] = user.token
173
        extra_context['signup_url'] = reverse('twitter_signup', args=(user.token,))
174

    
175
        return render_response(
176
            template,
177
            context_instance=get_context(request, extra_context)
178
        )
179

    
180

    
181
@requires_auth_provider('twitter', login=True, create=True)
182
@require_http_methods(["GET"])
183
@requires_anonymous
184
def signup(
185
    request,
186
    token,
187
    backend=None,
188
    on_creation_template='im/third_party_registration.html',
189
    extra_context={}):
190

    
191
    extra_context = extra_context or {}
192
    if not token:
193
                #TODO: use astakos_messages
194
        return HttpResponseBadRequest(_('Missing key parameter.'))
195

    
196
    pending = get_object_or_404(PendingThirdPartyUser, token=token)
197
    d = pending.__dict__
198
    d.pop('_state', None)
199
    d.pop('id', None)
200
    d.pop('token', None)
201
    d.pop('created', None)
202
    user = AstakosUser(**d)
203

    
204
    try:
205
        backend = backend or get_backend(request)
206
    except ImproperlyConfigured, e:
207
        messages.error(request, e)
208
    else:
209
        extra_context['form'] = backend.get_signup_form(
210
            provider='twitter',
211
            instance=user
212
        )
213

    
214
    extra_context['provider'] = 'twitter'
215
    extra_context['third_party_token'] = token
216
    return render_response(
217
            on_creation_template,
218
            context_instance=get_context(request, extra_context)
219
    )
220