Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / views / target / local.py @ 70e11eaa

History | View | Annotate | Download (8.2 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
from django.http import HttpResponseRedirect
35
from django.shortcuts import render_to_response
36
from django.template import RequestContext
37
from django.contrib import messages
38
from django.utils.translation import ugettext as _
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
import django.contrib.auth.views as django_auth_views
45

    
46
from astakos.im.util import prepare_response, get_query
47
from astakos.im.views.decorators import requires_anonymous, \
48
    signed_terms_required, requires_auth_provider
49
from astakos.im.models import PendingThirdPartyUser
50
from astakos.im.forms import LoginForm, ExtendedPasswordChangeForm, \
51
                             ExtendedSetPasswordForm
52
from astakos.im.settings import (RATELIMIT_RETRIES_ALLOWED,
53
                                ENABLE_LOCAL_ACCOUNT_MIGRATION)
54
import astakos.im.messages as astakos_messages
55
from astakos.im import settings
56
from astakos.im import auth_providers as auth
57
from astakos.im.views.decorators import cookie_fix, signed_terms_required
58

    
59
from ratelimit.decorators import ratelimit
60

    
61
retries = RATELIMIT_RETRIES_ALLOWED - 1
62
rate = str(retries) + '/m'
63

    
64

    
65
@requires_auth_provider('local')
66
@require_http_methods(["GET", "POST"])
67
@csrf_exempt
68
@requires_anonymous
69
@cookie_fix
70
@ratelimit(field='username', method='POST', rate=rate)
71
def login(request, on_failure='im/login.html'):
72
    """
73
    on_failure: the template name to render on login failure
74
    """
75
    was_limited = getattr(request, 'limited', False)
76
    form = LoginForm(data=request.POST,
77
                     was_limited=was_limited,
78
                     request=request)
79
    next = get_query(request).get('next', '')
80
    third_party_token = get_query(request).get('key', False)
81
    provider = auth.get_provider('local')
82

    
83
    if not form.is_valid():
84
        if third_party_token:
85
            messages.info(request, astakos_messages.get_login_to_add_msg)
86

    
87
        return render_to_response(
88
            on_failure,
89
            {'login_form':form,
90
             'next':next,
91
             'key': third_party_token},
92
            context_instance=RequestContext(request))
93

    
94
    # get the user from the cache
95
    user = form.user_cache
96
    provider = auth.get_provider('local', user)
97

    
98
    if not provider.get_login_policy:
99
        message = provider.get_login_disabled_msg
100
        messages.error(request, message)
101
        return HttpResponseRedirect(reverse('login'))
102

    
103
    message = None
104
    if not user:
105
        message = provider.get_authentication_failed_msg
106
    elif not user.is_active:
107
        message = user.get_inactive_message('local')
108

    
109
    elif not user.has_auth_provider('local'):
110
        # valid user logged in with no auth providers set, add local provider
111
        # and let him log in
112
        if not user.get_available_auth_providers():
113
            user.add_auth_provider('local')
114
        else:
115
            message = _(astakos_messages.NO_LOCAL_AUTH)
116

    
117
    if message:
118
        messages.error(request, message)
119
        return render_to_response(on_failure,
120
                                  {'login_form': form},
121
                                  context_instance=RequestContext(request))
122

    
123
    response = prepare_response(request, user, next)
124
    if third_party_token:
125
        # use requests to assign the account he just authenticated with with
126
        # a third party provider account
127
        try:
128
            request.user.add_pending_auth_provider(third_party_token)
129
        except PendingThirdPartyUser.DoesNotExist:
130
            provider = auth.get_provider('local', request.user)
131
            messages.error(request, provider.get_add_failed_msg)
132

    
133
    provider = user.get_auth_provider('local')
134
    messages.success(request, provider.get_login_success_msg)
135
    response.set_cookie('astakos_last_login_method', 'local')
136
    return response
137

    
138

    
139
@require_http_methods(["GET"])
140
@cookie_fix
141
def password_reset_done(request, *args, **kwargs):
142
    messages.success(request, _(astakos_messages.PASSWORD_RESET_DONE))
143
    return HttpResponseRedirect(reverse('index'))
144

    
145

    
146
@require_http_methods(["GET"])
147
@cookie_fix
148
def password_reset_confirm_done(request, *args, **kwargs):
149
    messages.success(request, _(astakos_messages.PASSWORD_RESET_CONFIRM_DONE))
150
    return HttpResponseRedirect(reverse('index'))
151

    
152

    
153
@cookie_fix
154
def password_reset(request, *args, **kwargs):
155
    kwargs['post_reset_redirect'] = reverse(
156
            'astakos.im.views.target.local.password_reset_done')
157
    return django_auth_views.password_reset(request, *args, **kwargs)
158

    
159

    
160
@cookie_fix
161
def password_reset_confirm(request, *args, **kwargs):
162
    kwargs['post_reset_redirect'] = reverse(
163
            'astakos.im.views.target.local.password_reset_complete')
164
    return django_auth_views.password_reset_confirm(request, *args, **kwargs)
165

    
166

    
167
@cookie_fix
168
def password_reset_complete(request, *args, **kwargs):
169
    return django_auth_views.password_reset_complete(request, *args, **kwargs)
170

    
171

    
172
@require_http_methods(["GET", "POST"])
173
@signed_terms_required
174
@login_required
175
@cookie_fix
176
@requires_auth_provider('local', login=True)
177
def password_change(request, template_name='registration/password_change_form.html',
178
                    post_change_redirect=None, password_change_form=ExtendedPasswordChangeForm):
179

    
180
    create_password = False
181

    
182
    provider = auth.get_provider('local', request.user)
183

    
184
    # no local backend user wants to create a password
185
    if not request.user.has_auth_provider('local'):
186
        if not provider.get_add_policy:
187
            messages.error(request, provider.get_add_disabled_msg)
188
            return HttpResponseRedirect(reverse('edit_profile'))
189

    
190
        create_password = True
191
        password_change_form = ExtendedSetPasswordForm
192

    
193
    if post_change_redirect is None:
194
        post_change_redirect = reverse('edit_profile')
195

    
196
    if request.method == "POST":
197
        form_kwargs = dict(
198
            user=request.user,
199
            data=request.POST,
200
        )
201
        if not create_password:
202
            form_kwargs['session_key'] = session_key=request.session.session_key
203

    
204
        form = password_change_form(**form_kwargs)
205
        if form.is_valid():
206
            form.save()
207
            if create_password:
208
                provider = auth.get_provider('local', request.user)
209
                messages.success(request, provider.get_added_msg)
210
            else:
211
                messages.success(request,
212
                                 astakos_messages.PASSWORD_RESET_CONFIRM_DONE)
213
            return HttpResponseRedirect(post_change_redirect)
214
    else:
215
        form = password_change_form(user=request.user)
216
    return render_to_response(template_name, {
217
        'form': form,
218
    }, context_instance=RequestContext(request, {'create_password':
219
                                                 create_password}))
220