local.py 6.38 KB
Newer Older
Antony Chazapis's avatar
Antony Chazapis committed
1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

34
from django.http import HttpResponseRedirect
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
35
36
from django.shortcuts import render_to_response
from django.template import RequestContext
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
37
from django.contrib import messages
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
38
from django.utils.translation import ugettext as _
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
39
from django.views.decorators.csrf import csrf_exempt
40
from django.views.decorators.http import require_http_methods
41
from django.core.urlresolvers import reverse
42
from django.contrib.auth.decorators import login_required
43

44
from astakos.im.util import prepare_response, get_query
45
from astakos.im.views import requires_anonymous, signed_terms_required
46
from astakos.im.models import PendingThirdPartyUser
47
48
from astakos.im.forms import LoginForm, ExtendedPasswordChangeForm, \
                             ExtendedSetPasswordForm
49
50
from astakos.im.settings import (RATELIMIT_RETRIES_ALLOWED,
                                ENABLE_LOCAL_ACCOUNT_MIGRATION)
Olga Brani's avatar
Olga Brani committed
51
import astakos.im.messages as astakos_messages
52
from astakos.im.views import requires_auth_provider
53
from astakos.im import settings
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
54
55
56

from ratelimit.decorators import ratelimit

57
58
59
retries = RATELIMIT_RETRIES_ALLOWED - 1
rate = str(retries) + '/m'

60

61
@requires_auth_provider('local', login=True)
62
@require_http_methods(["GET", "POST"])
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
63
@csrf_exempt
64
@requires_anonymous
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
65
@ratelimit(field='username', method='POST', rate=rate)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
66
def login(request, on_failure='im/login.html'):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
67
    """
68
    on_failure: the template name to render on login failure
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
69
    """
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
70
    was_limited = getattr(request, 'limited', False)
71
    form = LoginForm(data=request.POST,
72
                     was_limited=was_limited,
Olga Brani's avatar
Olga Brani committed
73
                     request=request)
74
    next = get_query(request).get('next', '')
75
76
    third_party_token = get_query(request).get('key', False)

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
77
    if not form.is_valid():
78
79
80
81
        return render_to_response(
            on_failure,
            {'login_form':form,
             'next':next,
82
             'key': third_party_token},
83
84
            context_instance=RequestContext(request)
        )
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
85
86
    # get the user from the cash
    user = form.user_cache
87

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
88
    message = None
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
89
    if not user:
Olga Brani's avatar
Olga Brani committed
90
        message = _(astakos_messages.ACCOUNT_AUTHENTICATION_FAILED)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
91
    elif not user.is_active:
92
        if not user.activation_sent:
93
            message = _(astakos_messages.ACCOUNT_PENDING_ACTIVATION)
94
        else:
95
			# TODO: USE astakos_messages
96
            url = reverse('send_activation', kwargs={'user_id':user.id})
97
98
99
100
101
102
103
104
            msg = _('You have not followed the activation link.')
            if settings.MODERATION_ENABLED:
                msg_extra = ' ' + _('Please contact support.')
            else:
                msg_extra = _('<a href="%s">Resend activation email?</a>') % url

            message = msg + msg_extra
    elif not user.can_login_with_auth_provider('local'):
105
106
107
108
109
110
        # valid user logged in with no auth providers set, add local provider
        # and let him log in
        if user.auth_providers.count() == 0:
            user.add_auth_provider('local')
        else:
            message = _(astakos_messages.NO_LOCAL_AUTH)
111

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
112
    if message:
113
        messages.error(request, message)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
114
        return render_to_response(on_failure,
115
                                  {'login_form': form},
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
116
                                  context_instance=RequestContext(request))
117
118
119
120
121

    response = prepare_response(request, user, next)
    if third_party_token:
        # use requests to assign the account he just authenticated with with
        # a third party provider account
122
        # TODO: USE astakos_messages
123
        try:
124
125
126
127
128
129
          request.user.add_pending_auth_provider(third_party_token)
          messages.success(request, _('Your new login method has been added'))
        except PendingThirdPartyUser.DoesNotExist:
          messages.error(request, _('Account method assignment failed'))

    return response
130
131
132
133

@require_http_methods(["GET", "POST"])
@signed_terms_required
@login_required
134
@requires_auth_provider('local', login=True)
135
136
def password_change(request, template_name='registration/password_change_form.html',
                    post_change_redirect=None, password_change_form=ExtendedPasswordChangeForm):
137
138
139
140
141
142
143
144

    create_password = False

    # no local backend user wants to create a password
    if not request.user.has_auth_provider('local'):
        create_password = True
        password_change_form = ExtendedSetPasswordForm

145
    if post_change_redirect is None:
146
147
        post_change_redirect = reverse('edit_profile')

148
    if request.method == "POST":
149
        form_kwargs = dict(
150
151
152
            user=request.user,
            data=request.POST,
        )
153
154
155
156
        if not create_password:
            form_kwargs['session_key'] = session_key=request.session.session_key

        form = password_change_form(**form_kwargs)
157
158
159
160
161
162
163
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(post_change_redirect)
    else:
        form = password_change_form(user=request.user)
    return render_to_response(template_name, {
        'form': form,
164
    }, context_instance=RequestContext(request))
165