Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / views / target / google.py @ 3e0a032d

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

    
36
from django.utils.translation import ugettext as _
37
from django.contrib import messages
38
from django.views.decorators.http import require_http_methods
39
from django.http import HttpResponseRedirect
40
from django.core.urlresolvers import reverse
41

    
42
from astakos.im.models import AstakosUser
43
from astakos.im import settings
44
from astakos.im.views.target import get_pending_key, \
45
    handle_third_party_signup, handle_third_party_login, init_third_party_session
46
from astakos.im.views.decorators import cookie_fix, requires_auth_provider
47

    
48
import logging
49
import urllib
50

    
51
logger = logging.getLogger(__name__)
52

    
53
import oauth2 as oauth
54

    
55
signature_method = oauth.SignatureMethod_HMAC_SHA1()
56

    
57
OAUTH_CONSUMER_KEY = settings.GOOGLE_CLIENT_ID
58
OAUTH_CONSUMER_SECRET = settings.GOOGLE_SECRET
59

    
60
token_scope = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email'
61
authenticate_url = 'https://accounts.google.com/o/oauth2/auth'
62
access_token_url = 'https://www.googleapis.com/oauth2/v1/tokeninfo'
63
request_token_url = 'https://accounts.google.com/o/oauth2/token'
64

    
65

    
66
def get_redirect_uri():
67
    return "%s%s" % (settings.BASEURL,
68
                     reverse('astakos.im.views.target.google.authenticated'))
69

    
70

    
71
@requires_auth_provider('google')
72
@require_http_methods(["GET", "POST"])
73
def login(request):
74
    init_third_party_session(request)
75
    params = {
76
        'scope': token_scope,
77
        'response_type': 'code',
78
        'redirect_uri': get_redirect_uri(),
79
        'client_id': settings.GOOGLE_CLIENT_ID
80
    }
81
    force_login = request.GET.get('force_login', request.GET.get('from_login',
82
                                                                 True))
83
    if force_login:
84
        params['approval_prompt'] = 'force'
85

    
86
    if request.GET.get('key', None):
87
        request.session['pending_key'] = request.GET.get('key')
88

    
89
    if request.GET.get('next', None):
90
        request.session['next_url'] = request.GET.get('next')
91

    
92
    url = "%s?%s" % (authenticate_url, urllib.urlencode(params))
93
    return HttpResponseRedirect(url)
94

    
95

    
96
@requires_auth_provider('google')
97
@require_http_methods(["GET", "POST"])
98
@cookie_fix
99
def authenticated(
100
    request,
101
    template='im/third_party_check_local.html',
102
    extra_context=None
103
):
104

    
105
    if extra_context is None:
106
        extra_context = {}
107

    
108
    if request.GET.get('error', None):
109
        return HttpResponseRedirect(reverse('edit_profile'))
110

    
111
    # TODO: Handle errors, e.g. error=access_denied
112
    try:
113
        consumer = oauth.Consumer(key=OAUTH_CONSUMER_KEY,
114
                                  secret=OAUTH_CONSUMER_SECRET)
115
        client = oauth.Client(consumer)
116

    
117
        code = request.GET.get('code', None)
118
        params = {
119
            'code': code,
120
            'client_id': settings.GOOGLE_CLIENT_ID,
121
            'client_secret': settings.GOOGLE_SECRET,
122
            'redirect_uri': get_redirect_uri(),
123
            'grant_type': 'authorization_code'
124
        }
125
        get_token_url = "%s" % (request_token_url,)
126
        resp, content = client.request(get_token_url, "POST",
127
                                       body=urllib.urlencode(params))
128
        token = json.loads(content).get('access_token', None)
129

    
130
        resp, content = client.request("%s?access_token=%s" %
131
                                       (access_token_url, token), "GET")
132
        access_token_data = json.loads(content)
133
    except Exception:
134
        messages.error(request, _('Invalid Google response. Please '
135
                                  'contact support'))
136
        return HttpResponseRedirect(reverse('edit_profile'))
137

    
138
    if not access_token_data.get('user_id', None):
139
        messages.error(request, _('Invalid Google response. Please contact '
140
                                  ' support'))
141
        return HttpResponseRedirect(reverse('edit_profile'))
142

    
143
    userid = access_token_data['user_id']
144
    provider_info = access_token_data
145
    affiliation = 'Google.com'
146

    
147
    try:
148
        return handle_third_party_login(request, 'google', userid,
149
                                        provider_info, affiliation)
150
    except AstakosUser.DoesNotExist:
151
        third_party_key = get_pending_key(request)
152
        user_info = {'affiliation': affiliation}
153
        return handle_third_party_signup(request, userid, 'google',
154
                                         third_party_key,
155
                                         provider_info,
156
                                         user_info,
157
                                         template,
158
                                         extra_context)