Allow multiple login methods per account
[astakos] / snf-astakos-app / astakos / im / target / local.py
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, HttpResponseRedirect
35 from django.shortcuts import render_to_response
36 from django.template import RequestContext
37 from django.contrib.auth import authenticate
38 from django.contrib import messages
39 from django.utils.translation import ugettext as _
40 from django.views.decorators.csrf import csrf_exempt
41 from django.views.decorators.http import require_http_methods
42 from django.core.urlresolvers import reverse
43 from django.contrib.auth.decorators import login_required
44
45 from astakos.im.util import prepare_response, get_query
46 from astakos.im.views import requires_anonymous, signed_terms_required, \
47         requires_auth_provider
48 from astakos.im.models import AstakosUser, PendingThirdPartyUser
49 from astakos.im.forms import LoginForm, ExtendedPasswordChangeForm, \
50         ExtendedSetPasswordForm
51 from astakos.im.settings import (RATELIMIT_RETRIES_ALLOWED,
52                                 ENABLE_LOCAL_ACCOUNT_MIGRATION)
53 from astakos.im import settings
54
55 from ratelimit.decorators import ratelimit
56
57 retries = RATELIMIT_RETRIES_ALLOWED-1
58 rate = str(retries)+'/m'
59
60 @requires_auth_provider('local', login=True)
61 @require_http_methods(["GET", "POST"])
62 @csrf_exempt
63 @requires_anonymous
64 @ratelimit(field='username', method='POST', rate=rate)
65 def login(request, on_failure='im/login.html'):
66     """
67     on_failure: the template name to render on login failure
68     """
69     was_limited = getattr(request, 'limited', False)
70     form = LoginForm(data=request.POST, was_limited=was_limited, request=request)
71     next = get_query(request).get('next', '')
72     third_party_token = get_query(request).get('key', False)
73
74     if not form.is_valid():
75         return render_to_response(
76             on_failure,
77             {'login_form':form,
78              'next':next,
79              'key': third_party_token},
80             context_instance=RequestContext(request)
81         )
82     # get the user from the cash
83     user = form.user_cache
84     
85     message = None
86     if not user:
87         message = _('Cannot authenticate account')
88     elif not user.is_active:
89         if not user.activation_sent:
90             message = _('Your request is pending activation')
91         else:
92             url = reverse('send_activation', kwargs={'user_id':user.id})
93             msg = _('You have not followed the activation link.')
94             if settings.MODERATION_ENABLED:
95                 msg_extra = ' ' + _('Please contact support.')
96             else:
97                 msg_extra = _('<a href="%s">Resend activation email?</a>') % url
98
99             message = msg + msg_extra
100     elif not user.can_login_with_auth_provider('local'):
101         message = _(
102             'Local login is not the current authentication method for this account.'
103         )
104
105     if message:
106         messages.error(request, message)
107         return render_to_response(on_failure,
108                                   {'login_form': form},
109                                   context_instance=RequestContext(request))
110
111     response = prepare_response(request, user, next)
112     if third_party_token:
113         # use requests to assign the account he just authenticated with with
114         # a third party provider account
115         try:
116           request.user.add_pending_auth_provider(third_party_token)
117           messages.success(request, _('Your new login method has been added'))
118         except PendingThirdPartyUser.DoesNotExist:
119           messages.error(request, _('Account method assignment failed'))
120
121     return response
122
123 @require_http_methods(["GET", "POST"])
124 @signed_terms_required
125 @login_required
126 @requires_auth_provider('local', login=True)
127 def password_change(request, template_name='registration/password_change_form.html',
128                     post_change_redirect=None, password_change_form=ExtendedPasswordChangeForm):
129
130     create_password = False
131
132     # no local backend user wants to create a password
133     if not request.user.has_auth_provider('local'):
134         create_password = True
135         password_change_form = ExtendedSetPasswordForm
136
137     if post_change_redirect is None:
138         post_change_redirect = reverse('edit_profile')
139
140     if request.method == "POST":
141         form_kwargs = dict(
142             user=request.user,
143             data=request.POST,
144         )
145         if not create_password:
146             form_kwargs['session_key'] = session_key=request.session.session_key
147
148         form = password_change_form(**form_kwargs)
149         if form.is_valid():
150             form.save()
151             return HttpResponseRedirect(post_change_redirect)
152     else:
153         form = password_change_form(user=request.user)
154     return render_to_response(template_name, {
155         'form': form,
156     }, context_instance=RequestContext(request))