Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / target / __init__.py @ 9d20fe23

History | View | Annotate | Download (9.6 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.contrib import messages
37
from django.utils.translation import ugettext as _
38
from django.http import HttpResponseRedirect
39
from django.core.urlresolvers import reverse
40
from django.db import transaction
41

    
42
from astakos.im.models import PendingThirdPartyUser, AstakosUser
43
from astakos.im.util import get_query, login_url
44
from astakos.im import messages as astakos_messages
45
from astakos.im import auth_providers as auth
46
from astakos.im.util import prepare_response, get_context
47
from astakos.im.views import requires_anonymous, render_response
48
import logging
49

    
50
logger = logging.getLogger(__name__)
51

    
52

    
53
def init_third_party_session(request):
54
    params = dict(request.GET.items())
55
    request.session['third_party_request_params'] = params
56

    
57

    
58
def get_third_party_session_params(request):
59
    if 'third_party_request_params' in request.session:
60
        params = request.session['third_party_request_params']
61
        del request.session['third_party_request_params']
62
        return params
63
    return {}
64

    
65

    
66
def add_pending_auth_provider(request, third_party_token, provider):
67
    if third_party_token:
68
        # use requests to assign the account he just authenticated with with
69
        # a third party provider account
70
        try:
71
            pending = PendingThirdPartyUser.objects.get(
72
                                token=third_party_token,
73
                                provider=provider.module)
74
            provider = pending.get_provider()
75
            provider.add_to_user()
76
            pending.delete()
77
        except PendingThirdPartyUser.DoesNotExist:
78
            messages.error(request, provider.get_add_failed_msg)
79

    
80

    
81
def get_pending_key(request):
82
    third_party_token = get_query(request).get('key', request.session.get('pending_key', False))
83
    if 'pending_key' in request.session:
84
        del request.session['pending_key']
85
    return third_party_token
86

    
87

    
88
def handle_third_party_signup(request, userid, provider_module,
89
                              third_party_key,
90
                              provider_info={},
91
                              pending_user_params={},
92
                              template="im/third_party_check_local.html",
93
                              extra_context={}):
94

    
95
    # build provider module object
96
    provider_data = {
97
        'affiliation': pending_user_params.get('affiliation', provider_module),
98
        'info_data': provider_info
99
    }
100
    provider = auth.get_provider(provider_module, request.user, userid,
101
                                 **provider_data)
102

    
103
    # user wants to add another third party login method
104
    if third_party_key:
105
        messages.error(request, provider.get_invalid_login_msg)
106
        return HttpResponseRedirect(reverse('login') + "?key=%s" %
107
                                    third_party_key)
108

    
109
    if not provider.get_create_policy:
110
                logger.info('%s signup is disabled.' % (provider.module,))
111
        messages.error(request, provider.get_disabled_for_create_msg)
112
        return HttpResponseRedirect(reverse('login'))
113

    
114
    # TODO: this could be stored in session
115
    # TODO: create a management command to clean old PendingThirdPartyUser
116
    user, created = PendingThirdPartyUser.objects.get_or_create(
117
        third_party_identifier=userid,
118
        provider=provider_module,
119
    )
120

    
121
    # update pending user
122
    for param, value in pending_user_params.iteritems():
123
        setattr(user, param, value)
124

    
125
    user.info = json.dumps(provider_info)
126
    user.generate_token()
127
    user.save()
128

    
129
    extra_context['provider'] = provider.module
130
    extra_context['provider_title'] = provider.get_title_msg
131
    extra_context['token'] = user.token
132
    extra_context['signup_url'] = reverse('signup') + \
133
        "?third_party_token=%s" % user.token
134
    extra_context['add_url'] = reverse('index') + \
135
        "?key=%s#other-login-methods" % user.token
136
    extra_context['can_create'] = provider.get_create_policy
137
    extra_context['can_add'] = provider.get_add_policy
138

    
139
    return HttpResponseRedirect(extra_context['signup_url'])
140

    
141

    
142
@transaction.commit_on_success
143
def handle_third_party_login(request, provider_module, identifier,
144
                             provider_info=None, affiliation=None,
145
                             third_party_key=None):
146

    
147
    if not provider_info:
148
        provider_info = {}
149

    
150
    if not affiliation:
151
        affiliation = provider_module.title()
152

    
153
    next_redirect = request.GET.get('next', request.session.get('next_url', None))
154
    if 'next_url' in request.session:
155
        del request.session['next_url']
156

    
157
    third_party_request_params = get_third_party_session_params(request)
158
    from_login = third_party_request_params.get('from_login', False)
159
    switch_from = third_party_request_params.get('switch_from', False)
160
    provider_data = {
161
        'affiliation': affiliation,
162
        'info': provider_info
163
    }
164
    provider = auth.get_provider(provider_module, request.user, identifier,
165
                                 **provider_data)
166

    
167
    # an existing user accessed the view
168
    if request.user.is_authenticated():
169
        if request.user.has_auth_provider(provider.module,
170
                                          identifier=identifier):
171
            return HttpResponseRedirect(reverse('edit_profile'))
172

    
173
        if provider.verified_exists():
174
            messages.error(request, provider.get_add_exists_msg)
175
            return HttpResponseRedirect(reverse('edit_profile'))
176

    
177
        # automatically add identifier provider to user
178
        if not switch_from and not provider.get_add_policy:
179
            # TODO: handle existing uuid message separately
180
            messages.error(request, provider.get_add_failed_msg)
181
            return HttpResponseRedirect(reverse('edit_profile'))
182

    
183
        user = request.user
184
        if switch_from:
185
            existing_provider = \
186
                request.user.auth_providers.active().get(
187
                    pk=int(switch_from), module=provider_module).settings
188

    
189
            # this is not a provider removal so we don't not use
190
            # provider.remove_from_user. Use low level access to the provider
191
            # db instance.
192
            if not provider.verified_exists():
193
                existing_provider._instance.delete()
194
                if provider.get_add_policy:
195
                    provider.add_to_user()
196
            else:
197
                messages.error(request, provider.get_add_exists_msg)
198
            messages.success(request, provider.get_switch_success_msg)
199
            return HttpResponseRedirect(reverse('edit_profile'))
200

    
201
        provider.add_to_user()
202
        provider = user.get_auth_provider(provider_module, identifier)
203
        messages.success(request, provider.get_added_msg)
204
        return HttpResponseRedirect(reverse('edit_profile'))
205

    
206
    # astakos user exists ?
207
    try:
208
        user = AstakosUser.objects.get_auth_provider_user(
209
            provider_module,
210
            identifier=identifier,
211
            user__email_verified=True,
212
        )
213
    except AstakosUser.DoesNotExist:
214
        # TODO: add a message ? redirec to login ?
215
        if astakos_messages.AUTH_PROVIDER_SIGNUP_FROM_LOGIN:
216
            messages.warning(request,
217
                             astakos_messages.AUTH_PROVIDER_SIGNUP_FROM_LOGIN)
218
        raise
219

    
220
    if not third_party_key:
221
        third_party_key = get_pending_key(request)
222

    
223
    provider = user.get_auth_provider(provider_module, identifier)
224
    if user.is_active:
225
        if not provider.get_login_policy:
226
            messages.error(request, provider.get_login_disabled_msg)
227
            return HttpResponseRedirect(reverse('login'))
228

    
229
        # authenticate user
230
        response = prepare_response(request, user, next_redirect,
231
                                    'renew' in request.GET)
232
        messages.error(request, provider.get_add_disabled_msg)
233
        return HttpResponseRedirect(reverse('edit_profile'))
234

    
235
        messages.success(request, provider.get_login_success_msg)
236
        add_pending_auth_provider(request, third_party_key, provider)
237
        response.set_cookie('astakos_last_login_method', provider_module)
238
        return response
239
    else:
240
        message = user.get_inactive_message(provider_module, identifier)
241
        messages.error(request, message)
242
        return HttpResponseRedirect(login_url(request))
243