Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7 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
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
from astakos.im.forms import LoginForm, ExtendedPasswordChangeForm, \
48
                             ExtendedSetPasswordForm
49
from astakos.im.settings import (RATELIMIT_RETRIES_ALLOWED,
50
                                ENABLE_LOCAL_ACCOUNT_MIGRATION)
51
import astakos.im.messages as astakos_messages
52
from astakos.im.views import requires_auth_provider
53
from astakos.im import settings
54
from astakos.im import auth_providers as auth
55

    
56
from ratelimit.decorators import ratelimit
57

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

    
61

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

    
79
    if not form.is_valid():
80
        if third_party_token:
81
            messages.info(request, astakos_messages.get_login_to_add_msg)
82

    
83
        return render_to_response(
84
            on_failure,
85
            {'login_form':form,
86
             'next':next,
87
             'key': third_party_token},
88
            context_instance=RequestContext(request))
89

    
90
    # get the user from the cache
91
    user = form.user_cache
92
    provider = auth.get_provider('local', user)
93

    
94
    message = None
95
    if not user:
96
        message = provider.get_authentication_failed_msg
97
    elif not user.is_active:
98
        message = user.get_inactive_message('local')
99

    
100
    elif not user.has_auth_provider('local'):
101
        # valid user logged in with no auth providers set, add local provider
102
        # and let him log in
103
        if not user.get_available_auth_providers():
104
            user.add_auth_provider('local')
105
        else:
106
            message = _(astakos_messages.NO_LOCAL_AUTH)
107

    
108
    if message:
109
        messages.error(request, message)
110
        return render_to_response(on_failure,
111
                                  {'login_form': form},
112
                                  context_instance=RequestContext(request))
113

    
114
    response = prepare_response(request, user, next)
115
    if third_party_token:
116
        # use requests to assign the account he just authenticated with with
117
        # a third party provider account
118
        try:
119
            request.user.add_pending_auth_provider(third_party_token)
120
        except PendingThirdPartyUser.DoesNotExist:
121
            provider = auth.get_provider('local', request.user)
122
            messages.error(request, provider.get_add_failed_msg)
123

    
124
    provider = user.get_auth_provider('local')
125
    messages.success(request, provider.get_login_success_msg)
126
    response.set_cookie('astakos_last_login_method', 'local')
127
    return response
128

    
129

    
130
@require_http_methods(["GET"])
131
def password_reset_done(request, *args, **kwargs):
132
    messages.success(request, _(astakos_messages.PASSWORD_RESET_DONE))
133
    return HttpResponseRedirect(reverse('index'))
134

    
135

    
136
@require_http_methods(["GET"])
137
def password_reset_confirm_done(request, *args, **kwargs):
138
    messages.success(request, _(astakos_messages.PASSWORD_RESET_CONFIRM_DONE))
139
    return HttpResponseRedirect(reverse('index'))
140

    
141

    
142
@require_http_methods(["GET", "POST"])
143
@signed_terms_required
144
@login_required
145
@requires_auth_provider('local', login=True)
146
def password_change(request, template_name='registration/password_change_form.html',
147
                    post_change_redirect=None, password_change_form=ExtendedPasswordChangeForm):
148

    
149
    create_password = False
150

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

    
156
    if post_change_redirect is None:
157
        post_change_redirect = reverse('edit_profile')
158

    
159
    if request.method == "POST":
160
        form_kwargs = dict(
161
            user=request.user,
162
            data=request.POST,
163
        )
164
        if not create_password:
165
            form_kwargs['session_key'] = session_key=request.session.session_key
166

    
167
        form = password_change_form(**form_kwargs)
168
        if form.is_valid():
169
            form.save()
170
            if create_password:
171
                provider = auth.get_provider('local', request.user)
172
                messages.success(request, provider.get_added_msg)
173
            else:
174
                messages.success(request,
175
                                 astakos_messages.PASSWORD_RESET_CONFIRM_DONE)
176
            return HttpResponseRedirect(post_change_redirect)
177
    else:
178
        form = password_change_form(user=request.user)
179
    return render_to_response(template_name, {
180
        'form': form,
181
    }, context_instance=RequestContext(request, {'create_password':
182
                                                 create_password}))
183