root / snf-astakos-app / astakos / im / target / google.py @ 74796dd8
History | View | Annotate | Download (7.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 |
49 |
from astakos.im.views import requires_anonymous, render_response, \ |
50 |
requires_auth_provider
|
51 |
from astakos.im.settings import ENABLE_LOCAL_ACCOUNT_MIGRATION, BASEURL |
52 |
from astakos.im.models import AstakosUser, PendingThirdPartyUser |
53 |
from astakos.im.forms import LoginForm |
54 |
from astakos.im.activation_backends import get_backend, SimpleBackend |
55 |
from astakos.im import settings |
56 |
from astakos.im import auth_providers |
57 |
|
58 |
import logging |
59 |
import time |
60 |
import astakos.im.messages as astakos_messages |
61 |
import urlparse |
62 |
import urllib |
63 |
|
64 |
logger = logging.getLogger(__name__) |
65 |
|
66 |
import oauth2 as oauth |
67 |
import cgi |
68 |
|
69 |
signature_method = oauth.SignatureMethod_HMAC_SHA1() |
70 |
|
71 |
OAUTH_CONSUMER_KEY = settings.GOOGLE_CLIENT_ID |
72 |
OAUTH_CONSUMER_SECRET = settings.GOOGLE_SECRET |
73 |
|
74 |
consumer = oauth.Consumer(key=OAUTH_CONSUMER_KEY, secret=OAUTH_CONSUMER_SECRET) |
75 |
client = oauth.Client(consumer) |
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.target.google.authenticated'))
|
86 |
|
87 |
@requires_auth_provider('google', login=True) |
88 |
@require_http_methods(["GET", "POST"]) |
89 |
def login(request): |
90 |
params = { |
91 |
'scope': token_scope,
|
92 |
'response_type': 'code', |
93 |
'redirect_uri': get_redirect_uri(),
|
94 |
'client_id': settings.GOOGLE_CLIENT_ID
|
95 |
} |
96 |
url = "%s?%s" % (authenticate_url, urllib.urlencode(params))
|
97 |
return HttpResponseRedirect(url)
|
98 |
|
99 |
|
100 |
@requires_auth_provider('google', login=True) |
101 |
@require_http_methods(["GET", "POST"]) |
102 |
def authenticated( |
103 |
request, |
104 |
template='im/third_party_check_local.html',
|
105 |
extra_context={} |
106 |
): |
107 |
|
108 |
# TODO: Handle errors, e.g. error=access_denied
|
109 |
try:
|
110 |
code = request.GET.get('code', None) |
111 |
params = { |
112 |
'code': code,
|
113 |
'client_id': settings.GOOGLE_CLIENT_ID,
|
114 |
'client_secret': settings.GOOGLE_SECRET,
|
115 |
'redirect_uri': get_redirect_uri(),
|
116 |
'grant_type': 'authorization_code' |
117 |
} |
118 |
get_token_url = "%s" % (request_token_url,)
|
119 |
resp, content = client.request(get_token_url, "POST",
|
120 |
body=urllib.urlencode(params)) |
121 |
token = json.loads(content).get('access_token', None) |
122 |
|
123 |
resp, content = client.request("%s?access_token=%s" % (access_token_url,
|
124 |
token) , "GET")
|
125 |
access_token_data = json.loads(content) |
126 |
except Exception, e: |
127 |
messages.error(request, 'Invalid Google response. Please contact support')
|
128 |
return HttpResponseRedirect(reverse('edit_profile')) |
129 |
|
130 |
userid = access_token_data['user_id']
|
131 |
username = access_token_data.get('email', None) |
132 |
provider_info = access_token_data |
133 |
affiliation = 'Google.com'
|
134 |
|
135 |
# an existing user accessed the view
|
136 |
if request.user.is_authenticated():
|
137 |
if request.user.has_auth_provider('google', identifier=userid): |
138 |
return HttpResponseRedirect(reverse('edit_profile')) |
139 |
|
140 |
# automatically add eppn provider to user
|
141 |
user = request.user |
142 |
if not request.user.can_add_auth_provider('google', |
143 |
identifier=userid): |
144 |
messages.error(request, _(astakos_messages.AUTH_PROVIDER_ADD_FAILED) + |
145 |
u' ' + _(astakos_messages.AUTH_PROVIDER_ADD_EXISTS))
|
146 |
return HttpResponseRedirect(reverse('edit_profile')) |
147 |
|
148 |
user.add_auth_provider('google', identifier=userid,
|
149 |
affiliation=affiliation, |
150 |
provider_info=provider_info) |
151 |
messages.success(request, astakos_messages.AUTH_PROVIDER_ADDED) |
152 |
return HttpResponseRedirect(reverse('edit_profile')) |
153 |
|
154 |
try:
|
155 |
# astakos user exists ?
|
156 |
user = AstakosUser.objects.get_auth_provider_user( |
157 |
'google',
|
158 |
identifier=userid |
159 |
) |
160 |
if user.is_active:
|
161 |
# authenticate user
|
162 |
response = prepare_response(request, |
163 |
user, |
164 |
request.GET.get('next'),
|
165 |
'renew' in request.GET) |
166 |
response.set_cookie('astakos_last_login_method', 'google') |
167 |
return response
|
168 |
else:
|
169 |
message = user.get_inactive_message() |
170 |
messages.error(request, message) |
171 |
return HttpResponseRedirect(reverse('login')) |
172 |
|
173 |
except AstakosUser.DoesNotExist, e:
|
174 |
provider = auth_providers.get_provider('google')
|
175 |
if not provider.is_available_for_create(): |
176 |
messages.error(request, |
177 |
_(astakos_messages.AUTH_PROVIDER_NOT_ACTIVE) % provider.get_title_display) |
178 |
return HttpResponseRedirect(reverse('login')) |
179 |
|
180 |
# eppn not stored in astakos models, create pending profile
|
181 |
user, created = PendingThirdPartyUser.objects.get_or_create( |
182 |
third_party_identifier=userid, |
183 |
provider='google',
|
184 |
) |
185 |
# update pending user
|
186 |
user.affiliation = affiliation |
187 |
user.info = json.dumps(provider_info) |
188 |
user.generate_token() |
189 |
user.save() |
190 |
|
191 |
extra_context['provider'] = 'google' |
192 |
extra_context['provider_title'] = 'google' |
193 |
extra_context['token'] = user.token
|
194 |
extra_context['signup_url'] = reverse('signup') + \ |
195 |
"?third_party_token=%s" % user.token
|
196 |
|
197 |
return render_response(
|
198 |
template, |
199 |
context_instance=get_context(request, extra_context) |
200 |
) |
201 |
|
202 |
|