Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / views / target / google.py @ 70e11eaa

History | View | Annotate | Download (6.7 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
import json
35

    
36
from django.http import HttpResponseBadRequest
37
from django.utils.translation import ugettext as _
38
from django.contrib import messages
39
from django.template import RequestContext
40
from django.views.decorators.http import require_http_methods
41
from django.http import HttpResponseRedirect
42
from django.core.urlresolvers import reverse
43
from django.core.exceptions import ImproperlyConfigured
44
from django.shortcuts import get_object_or_404
45

    
46
from urlparse import urlunsplit, urlsplit
47

    
48
from astakos.im.util import prepare_response, get_context, login_url
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
from astakos.im import auth_providers
55
from astakos.im.views.target import add_pending_auth_provider, get_pending_key, \
56
    handle_third_party_signup, handle_third_party_login, init_third_party_session
57
from astakos.im.views.util import render_response
58
from astakos.im.views.decorators import cookie_fix, requires_anonymous, \
59
    requires_auth_provider
60

    
61
import logging
62
import time
63
import astakos.im.messages as astakos_messages
64
import urlparse
65
import urllib
66

    
67
logger = logging.getLogger(__name__)
68

    
69
import oauth2 as oauth
70
import cgi
71

    
72
signature_method = oauth.SignatureMethod_HMAC_SHA1()
73

    
74
OAUTH_CONSUMER_KEY = settings.GOOGLE_CLIENT_ID
75
OAUTH_CONSUMER_SECRET = settings.GOOGLE_SECRET
76

    
77
token_scope = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email'
78
authenticate_url = 'https://accounts.google.com/o/oauth2/auth'
79
access_token_url = 'https://www.googleapis.com/oauth2/v1/tokeninfo'
80
request_token_url = 'https://accounts.google.com/o/oauth2/token'
81

    
82

    
83
def get_redirect_uri():
84
    return "%s%s" % (settings.BASEURL,
85
                     reverse('astakos.im.views.target.google.authenticated'))
86

    
87

    
88
@requires_auth_provider('google')
89
@require_http_methods(["GET", "POST"])
90
def login(request):
91
    init_third_party_session(request)
92
    params = {
93
        'scope': token_scope,
94
        'response_type': 'code',
95
        'redirect_uri': get_redirect_uri(),
96
        'client_id': settings.GOOGLE_CLIENT_ID
97
    }
98
    force_login = request.GET.get('force_login', request.GET.get('from_login',
99
                                                                 True))
100
    if force_login:
101
        params['approval_prompt'] = 'force'
102

    
103
    if request.GET.get('key', None):
104
        request.session['pending_key'] = request.GET.get('key')
105

    
106
    if request.GET.get('next', None):
107
        request.session['next_url'] = request.GET.get('next')
108

    
109
    url = "%s?%s" % (authenticate_url, urllib.urlencode(params))
110
    return HttpResponseRedirect(url)
111

    
112

    
113
@requires_auth_provider('google')
114
@require_http_methods(["GET", "POST"])
115
@cookie_fix
116
def authenticated(
117
    request,
118
    template='im/third_party_check_local.html',
119
    extra_context=None
120
):
121

    
122
    if extra_context is None:
123
        extra_context = {}
124

    
125
    if request.GET.get('error', None):
126
        return HttpResponseRedirect(reverse('edit_profile'))
127

    
128
    # TODO: Handle errors, e.g. error=access_denied
129
    try:
130
        consumer = oauth.Consumer(key=OAUTH_CONSUMER_KEY,
131
                                  secret=OAUTH_CONSUMER_SECRET)
132
        client = oauth.Client(consumer)
133

    
134
        code = request.GET.get('code', None)
135
        params = {
136
            'code': code,
137
            'client_id': settings.GOOGLE_CLIENT_ID,
138
            'client_secret': settings.GOOGLE_SECRET,
139
            'redirect_uri': get_redirect_uri(),
140
            'grant_type': 'authorization_code'
141
        }
142
        get_token_url = "%s" % (request_token_url,)
143
        resp, content = client.request(get_token_url, "POST",
144
                                       body=urllib.urlencode(params))
145
        token = json.loads(content).get('access_token', None)
146

    
147
        resp, content = client.request("%s?access_token=%s" %
148
                                       (access_token_url, token), "GET")
149
        access_token_data = json.loads(content)
150
    except Exception:
151
        messages.error(request, _('Invalid Google response. Please '
152
                                  'contact support'))
153
        return HttpResponseRedirect(reverse('edit_profile'))
154

    
155
    if not access_token_data.get('user_id', None):
156
        messages.error(request, _('Invalid Google response. Please contact '
157
                                  ' support'))
158
        return HttpResponseRedirect(reverse('edit_profile'))
159

    
160
    userid = access_token_data['user_id']
161
    provider_info = access_token_data
162
    affiliation = 'Google.com'
163

    
164
    try:
165
        return handle_third_party_login(request, 'google', userid,
166
                                        provider_info, affiliation)
167
    except AstakosUser.DoesNotExist:
168
        third_party_key = get_pending_key(request)
169
        user_info = {'affiliation': affiliation}
170
        return handle_third_party_signup(request, userid, 'google',
171
                                         third_party_key,
172
                                         provider_info,
173
                                         user_info,
174
                                         template,
175
                                         extra_context)