root / snf-astakos-app / astakos / im / views / im.py @ 6e3bb9c8
History | View | Annotate | Download (36 kB)
1 |
# Copyright 2011, 2012, 2013 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 logging |
35 |
import inflect |
36 |
|
37 |
engine = inflect.engine() |
38 |
|
39 |
from urllib import quote |
40 |
|
41 |
from django.shortcuts import get_object_or_404 |
42 |
from django.contrib import messages |
43 |
from django.contrib.auth.models import User |
44 |
from django.core.urlresolvers import reverse |
45 |
from django.db import transaction |
46 |
from django.http import HttpResponse, HttpResponseRedirect, Http404 |
47 |
from django.shortcuts import redirect |
48 |
from django.utils.translation import ugettext as _ |
49 |
from django.core.exceptions import PermissionDenied |
50 |
from django.views.decorators.http import require_http_methods |
51 |
from django.utils import simplejson as json |
52 |
from django.template import RequestContext |
53 |
|
54 |
from synnefo_branding import utils as branding |
55 |
from synnefo_branding import settings as branding_settings |
56 |
|
57 |
import astakos.im.messages as astakos_messages |
58 |
|
59 |
from astakos.im import activation_backends |
60 |
from astakos.im.models import AstakosUser, ApprovalTerms, EmailChange, \ |
61 |
AstakosUserAuthProvider, PendingThirdPartyUser, Component |
62 |
from astakos.im.util import get_context, prepare_response, get_query, \ |
63 |
restrict_next
|
64 |
from astakos.im.forms import LoginForm, InvitationForm, FeedbackForm, \ |
65 |
SignApprovalTermsForm, EmailChangeForm |
66 |
from astakos.im.forms import ExtendedProfileForm as ProfileForm |
67 |
from synnefo.lib.services import get_public_endpoint |
68 |
from astakos.im.functions import send_feedback, logout as auth_logout, \ |
69 |
invite as invite_func |
70 |
from astakos.im import settings |
71 |
from astakos.im import presentation |
72 |
from astakos.im import auth_providers as auth |
73 |
from astakos.im import quotas |
74 |
from astakos.im.views.util import render_response, _resources_catalog |
75 |
from astakos.im.views.decorators import cookie_fix, signed_terms_required,\ |
76 |
required_auth_methods_assigned, valid_astakos_user_required, login_required |
77 |
|
78 |
logger = logging.getLogger(__name__) |
79 |
|
80 |
|
81 |
@require_http_methods(["GET", "POST"]) |
82 |
@cookie_fix
|
83 |
@signed_terms_required
|
84 |
def login(request, template_name='im/login.html', extra_context=None): |
85 |
"""
|
86 |
Renders login page.
|
87 |
|
88 |
**Arguments**
|
89 |
|
90 |
``template_name``
|
91 |
A custom login template to use. This is optional; if not specified,
|
92 |
this will default to ``im/login.html``.
|
93 |
|
94 |
``extra_context``
|
95 |
An dictionary of variables to add to the template context.
|
96 |
"""
|
97 |
|
98 |
extra_context = extra_context or {}
|
99 |
|
100 |
third_party_token = request.GET.get('key', False) |
101 |
if third_party_token:
|
102 |
messages.info(request, astakos_messages.AUTH_PROVIDER_LOGIN_TO_ADD) |
103 |
|
104 |
if request.user.is_authenticated():
|
105 |
return HttpResponseRedirect(reverse('landing')) |
106 |
|
107 |
return render_response(
|
108 |
template_name, |
109 |
login_form=LoginForm(request=request), |
110 |
context_instance=get_context(request, extra_context) |
111 |
) |
112 |
|
113 |
|
114 |
@require_http_methods(["GET", "POST"]) |
115 |
@cookie_fix
|
116 |
@signed_terms_required
|
117 |
def index(request, authenticated_redirect='landing', |
118 |
anonymous_redirect='login', extra_context=None): |
119 |
"""
|
120 |
If user is authenticated redirect to ``authenticated_redirect`` url.
|
121 |
Otherwise redirects to ``anonymous_redirect`` url.
|
122 |
|
123 |
"""
|
124 |
if request.user.is_authenticated():
|
125 |
return HttpResponseRedirect(reverse(authenticated_redirect))
|
126 |
return HttpResponseRedirect(reverse(anonymous_redirect))
|
127 |
|
128 |
|
129 |
@require_http_methods(["POST"]) |
130 |
@cookie_fix
|
131 |
@valid_astakos_user_required
|
132 |
@transaction.commit_on_success
|
133 |
def update_token(request): |
134 |
"""
|
135 |
Update api token view.
|
136 |
"""
|
137 |
user = AstakosUser.objects.select_for_update().get(id=request.user.id) |
138 |
user.renew_token() |
139 |
user.save() |
140 |
messages.success(request, astakos_messages.TOKEN_UPDATED) |
141 |
return HttpResponseRedirect(reverse('api_access')) |
142 |
|
143 |
|
144 |
@require_http_methods(["GET", "POST"]) |
145 |
@cookie_fix
|
146 |
@valid_astakos_user_required
|
147 |
@transaction.commit_on_success
|
148 |
def invite(request, template_name='im/invitations.html', extra_context=None): |
149 |
"""
|
150 |
Allows a user to invite somebody else.
|
151 |
|
152 |
In case of GET request renders a form for providing the invitee
|
153 |
information.
|
154 |
In case of POST checks whether the user has not run out of invitations and
|
155 |
then sends an invitation email to singup to the service.
|
156 |
|
157 |
The number of the user invitations is going to be updated only if the email
|
158 |
has been successfully sent.
|
159 |
|
160 |
If the user isn't logged in, redirects to settings.LOGIN_URL.
|
161 |
|
162 |
**Arguments**
|
163 |
|
164 |
``template_name``
|
165 |
A custom template to use. This is optional; if not specified,
|
166 |
this will default to ``im/invitations.html``.
|
167 |
|
168 |
``extra_context``
|
169 |
An dictionary of variables to add to the template context.
|
170 |
|
171 |
**Template:**
|
172 |
|
173 |
im/invitations.html or ``template_name`` keyword argument.
|
174 |
|
175 |
**Settings:**
|
176 |
|
177 |
The view expectes the following settings are defined:
|
178 |
|
179 |
* LOGIN_URL: login uri
|
180 |
"""
|
181 |
extra_context = extra_context or {}
|
182 |
status = None
|
183 |
message = None
|
184 |
form = InvitationForm() |
185 |
|
186 |
inviter = request.user |
187 |
if request.method == 'POST': |
188 |
form = InvitationForm(request.POST) |
189 |
if inviter.invitations > 0: |
190 |
if form.is_valid():
|
191 |
email = form.cleaned_data.get('username')
|
192 |
realname = form.cleaned_data.get('realname')
|
193 |
invite_func(inviter, email, realname) |
194 |
message = _(astakos_messages.INVITATION_SENT) % locals()
|
195 |
messages.success(request, message) |
196 |
else:
|
197 |
message = _(astakos_messages.MAX_INVITATION_NUMBER_REACHED) |
198 |
messages.error(request, message) |
199 |
|
200 |
sent = [{'email': inv.username,
|
201 |
'realname': inv.realname,
|
202 |
'is_consumed': inv.is_consumed}
|
203 |
for inv in request.user.invitations_sent.all()] |
204 |
kwargs = {'inviter': inviter,
|
205 |
'sent': sent}
|
206 |
context = get_context(request, extra_context, **kwargs) |
207 |
return render_response(template_name,
|
208 |
invitation_form=form, |
209 |
context_instance=context) |
210 |
|
211 |
|
212 |
@require_http_methods(["GET", "POST"]) |
213 |
@required_auth_methods_assigned()
|
214 |
@login_required
|
215 |
@cookie_fix
|
216 |
@signed_terms_required
|
217 |
def api_access_config(request, template_name='im/api_access_config.html', |
218 |
content_type='text/plain', extra_context=None, |
219 |
filename='.kamakirc'):
|
220 |
|
221 |
if settings.KAMAKI_CONFIG_CLOUD_NAME:
|
222 |
cloud_name = settings.KAMAKI_CONFIG_CLOUD_NAME |
223 |
else:
|
224 |
cloud_name = branding_settings.SERVICE_NAME.replace(' ', '_').lower() |
225 |
|
226 |
url = get_public_endpoint(settings.astakos_services, 'identity')
|
227 |
|
228 |
context = { |
229 |
'user': request.user,
|
230 |
'services': Component.catalog(),
|
231 |
'token_url': url,
|
232 |
'cloud_name': cloud_name
|
233 |
} |
234 |
|
235 |
extra_context = extra_context or {}
|
236 |
context.update(extra_context) |
237 |
content = branding.render_to_string(template_name, context, |
238 |
RequestContext(request)) |
239 |
response = HttpResponse(content_type=content_type) |
240 |
response.status_code = 200
|
241 |
response['Content-Disposition'] = 'attachment; filename="%s"' % filename |
242 |
response.content = content |
243 |
return response
|
244 |
|
245 |
|
246 |
@required_auth_methods_assigned()
|
247 |
@login_required
|
248 |
@cookie_fix
|
249 |
@signed_terms_required
|
250 |
def api_access(request, template_name='im/api_access.html', |
251 |
extra_context=None):
|
252 |
"""
|
253 |
API access view.
|
254 |
"""
|
255 |
context = {} |
256 |
|
257 |
url = get_public_endpoint(settings.astakos_services, 'identity')
|
258 |
context['services'] = Component.catalog()
|
259 |
context['token_url'] = url
|
260 |
context['user'] = request.user
|
261 |
context['client_url'] = settings.API_CLIENT_URL
|
262 |
|
263 |
if extra_context:
|
264 |
context.update(extra_context) |
265 |
context_instance = get_context(request, context) |
266 |
return render_response(template_name,
|
267 |
context_instance=context_instance) |
268 |
|
269 |
|
270 |
@require_http_methods(["GET", "POST"]) |
271 |
@required_auth_methods_assigned(allow_access=True) |
272 |
@login_required
|
273 |
@cookie_fix
|
274 |
@signed_terms_required
|
275 |
@transaction.commit_on_success
|
276 |
def edit_profile(request, template_name='im/profile.html', extra_context=None): |
277 |
"""
|
278 |
Allows a user to edit his/her profile.
|
279 |
|
280 |
In case of GET request renders a form for displaying the user information.
|
281 |
In case of POST updates the user informantion and redirects to ``next``
|
282 |
url parameter if exists.
|
283 |
|
284 |
If the user isn't logged in, redirects to settings.LOGIN_URL.
|
285 |
|
286 |
**Arguments**
|
287 |
|
288 |
``template_name``
|
289 |
A custom template to use. This is optional; if not specified,
|
290 |
this will default to ``im/profile.html``.
|
291 |
|
292 |
``extra_context``
|
293 |
An dictionary of variables to add to the template context.
|
294 |
|
295 |
**Template:**
|
296 |
|
297 |
im/profile.html or ``template_name`` keyword argument.
|
298 |
|
299 |
**Settings:**
|
300 |
|
301 |
The view expectes the following settings are defined:
|
302 |
|
303 |
* LOGIN_URL: login uri
|
304 |
"""
|
305 |
|
306 |
request.user = AstakosUser.objects.select_for_update().\ |
307 |
get(id=request.user.id) |
308 |
extra_context = extra_context or {}
|
309 |
form = ProfileForm( |
310 |
instance=request.user, |
311 |
session_key=request.session.session_key |
312 |
) |
313 |
|
314 |
extra_context['next'] = request.GET.get('next') |
315 |
if request.method == 'POST': |
316 |
form = ProfileForm( |
317 |
request.POST, |
318 |
instance=request.user, |
319 |
session_key=request.session.session_key |
320 |
) |
321 |
if form.is_valid():
|
322 |
try:
|
323 |
prev_token = request.user.auth_token |
324 |
user = form.save(request=request) |
325 |
next = restrict_next( |
326 |
request.POST.get('next'),
|
327 |
domain=settings.COOKIE_DOMAIN |
328 |
) |
329 |
msg = _(astakos_messages.PROFILE_UPDATED) |
330 |
messages.success(request, msg) |
331 |
|
332 |
if form.email_changed:
|
333 |
msg = _(astakos_messages.EMAIL_CHANGE_REGISTERED) |
334 |
messages.success(request, msg) |
335 |
if form.password_changed:
|
336 |
msg = _(astakos_messages.PASSWORD_CHANGED) |
337 |
messages.success(request, msg) |
338 |
|
339 |
if next: |
340 |
return redirect(next) |
341 |
else:
|
342 |
return redirect(reverse('edit_profile')) |
343 |
except ValueError, ve: |
344 |
messages.success(request, ve) |
345 |
elif request.method == "GET": |
346 |
request.user.is_verified = True
|
347 |
request.user.save() |
348 |
|
349 |
# existing providers
|
350 |
user_providers = request.user.get_enabled_auth_providers() |
351 |
user_disabled_providers = request.user.get_disabled_auth_providers() |
352 |
|
353 |
# providers that user can add
|
354 |
user_available_providers = request.user.get_available_auth_providers() |
355 |
|
356 |
extra_context['services'] = Component.catalog().values()
|
357 |
|
358 |
if request.method == "GET": |
359 |
if request.user.email_change_is_pending():
|
360 |
change_email = request.user.get_pending_email_change() |
361 |
msg = _(astakos_messages.PENDING_EMAIL_CHANGE_WARNING) % { |
362 |
'email': change_email.new_email_address,
|
363 |
'cancel_url': change_email.get_cancel_url()
|
364 |
} |
365 |
messages.warning(request, msg) |
366 |
|
367 |
return render_response(template_name,
|
368 |
profile_form=form, |
369 |
user_providers=user_providers, |
370 |
user_disabled_providers=user_disabled_providers, |
371 |
user_available_providers=user_available_providers, |
372 |
context_instance=get_context(request, |
373 |
extra_context)) |
374 |
|
375 |
|
376 |
@transaction.commit_on_success
|
377 |
@require_http_methods(["GET", "POST"]) |
378 |
@cookie_fix
|
379 |
def signup(request, template_name='im/signup.html', on_success='index', |
380 |
extra_context=None, activation_backend=None): |
381 |
"""
|
382 |
Allows a user to create a local account.
|
383 |
|
384 |
In case of GET request renders a form for entering the user information.
|
385 |
In case of POST handles the signup.
|
386 |
|
387 |
The user activation will be delegated to the backend specified by the
|
388 |
``activation_backend`` keyword argument if present, otherwise to the
|
389 |
``astakos.im.activation_backends.InvitationBackend`` if
|
390 |
settings.ASTAKOS_INVITATIONS_ENABLED is True or
|
391 |
``astakos.im.activation_backends.SimpleBackend`` if not (see
|
392 |
activation_backends);
|
393 |
|
394 |
Upon successful user creation, if ``next`` url parameter is present the
|
395 |
user is redirected there otherwise renders the same page with a success
|
396 |
message.
|
397 |
|
398 |
On unsuccessful creation, renders ``template_name`` with an error message.
|
399 |
|
400 |
**Arguments**
|
401 |
|
402 |
``template_name``
|
403 |
A custom template to render. This is optional;
|
404 |
if not specified, this will default to ``im/signup.html``.
|
405 |
|
406 |
``extra_context``
|
407 |
An dictionary of variables to add to the template context.
|
408 |
|
409 |
``on_success``
|
410 |
Resolvable view name to redirect on registration success.
|
411 |
|
412 |
**Template:**
|
413 |
|
414 |
im/signup.html or ``template_name`` keyword argument.
|
415 |
"""
|
416 |
extra_context = extra_context or {}
|
417 |
if request.user.is_authenticated():
|
418 |
logger.info("%s already signed in, redirect to index",
|
419 |
request.user.log_display) |
420 |
return HttpResponseRedirect(reverse('index')) |
421 |
|
422 |
provider = get_query(request).get('provider', 'local') |
423 |
if not auth.get_provider(provider).get_create_policy: |
424 |
logger.error("%s provider not available for signup", provider)
|
425 |
raise PermissionDenied
|
426 |
|
427 |
instance = None
|
428 |
|
429 |
# user registered using third party provider
|
430 |
third_party_token = request.REQUEST.get('third_party_token', None) |
431 |
unverified = None
|
432 |
pending = None
|
433 |
if third_party_token:
|
434 |
# retreive third party entry. This was created right after the initial
|
435 |
# third party provider handshake.
|
436 |
pending = get_object_or_404(PendingThirdPartyUser, |
437 |
token=third_party_token) |
438 |
|
439 |
provider = pending.provider |
440 |
|
441 |
# clone third party instance into the corresponding AstakosUser
|
442 |
instance = pending.get_user_instance() |
443 |
get_unverified = AstakosUserAuthProvider.objects.unverified |
444 |
|
445 |
# check existing unverified entries
|
446 |
unverified = get_unverified(pending.provider, |
447 |
identifier=pending.third_party_identifier) |
448 |
|
449 |
if unverified and request.method == 'GET': |
450 |
messages.warning(request, unverified.get_pending_registration_msg) |
451 |
if unverified.user.moderated:
|
452 |
messages.warning(request, |
453 |
unverified.get_pending_resend_activation_msg) |
454 |
else:
|
455 |
messages.warning(request, |
456 |
unverified.get_pending_moderation_msg) |
457 |
|
458 |
# prepare activation backend based on current request
|
459 |
if not activation_backend: |
460 |
activation_backend = activation_backends.get_backend() |
461 |
|
462 |
form_kwargs = {'instance': instance, 'request': request} |
463 |
if third_party_token:
|
464 |
form_kwargs['third_party_token'] = third_party_token
|
465 |
|
466 |
if pending:
|
467 |
form_kwargs['initial'] = {
|
468 |
'first_name': pending.first_name,
|
469 |
'last_name': pending.last_name,
|
470 |
'email': pending.email
|
471 |
} |
472 |
|
473 |
form = activation_backend.get_signup_form( |
474 |
provider, None, **form_kwargs)
|
475 |
|
476 |
|
477 |
if request.method == 'POST': |
478 |
form = activation_backend.get_signup_form( |
479 |
provider, |
480 |
request.POST, |
481 |
**form_kwargs) |
482 |
|
483 |
if form.is_valid():
|
484 |
user = form.create_user() |
485 |
result = activation_backend.handle_registration(user) |
486 |
if result.status == \
|
487 |
activation_backend.Result.PENDING_MODERATION: |
488 |
# user should be warned that his account is not active yet
|
489 |
status = messages.WARNING |
490 |
else:
|
491 |
status = messages.SUCCESS |
492 |
message = result.message |
493 |
activation_backend.send_result_notifications(result, user) |
494 |
|
495 |
# commit user entry
|
496 |
transaction.commit() |
497 |
|
498 |
if user and user.is_active: |
499 |
# activation backend directly activated the user
|
500 |
# log him in
|
501 |
next = request.POST.get('next', '') |
502 |
response = prepare_response(request, user, next=next)
|
503 |
return response
|
504 |
|
505 |
messages.add_message(request, status, message) |
506 |
return HttpResponseRedirect(reverse(on_success))
|
507 |
|
508 |
return render_response(
|
509 |
template_name, |
510 |
signup_form=form, |
511 |
third_party_token=third_party_token, |
512 |
provider=provider, |
513 |
context_instance=get_context(request, extra_context)) |
514 |
|
515 |
|
516 |
@require_http_methods(["GET", "POST"]) |
517 |
@required_auth_methods_assigned(allow_access=True) |
518 |
@login_required
|
519 |
@cookie_fix
|
520 |
@signed_terms_required
|
521 |
def feedback(request, template_name='im/feedback.html', |
522 |
email_template_name='im/feedback_mail.txt', extra_context=None): |
523 |
"""
|
524 |
Allows a user to send feedback.
|
525 |
|
526 |
In case of GET request renders a form for providing the feedback
|
527 |
information.
|
528 |
In case of POST sends an email to support team.
|
529 |
|
530 |
If the user isn't logged in, redirects to settings.LOGIN_URL.
|
531 |
|
532 |
**Arguments**
|
533 |
|
534 |
``template_name``
|
535 |
A custom template to use. This is optional; if not specified,
|
536 |
this will default to ``im/feedback.html``.
|
537 |
|
538 |
``extra_context``
|
539 |
An dictionary of variables to add to the template context.
|
540 |
|
541 |
**Template:**
|
542 |
|
543 |
im/signup.html or ``template_name`` keyword argument.
|
544 |
|
545 |
**Settings:**
|
546 |
|
547 |
* LOGIN_URL: login uri
|
548 |
"""
|
549 |
extra_context = extra_context or {}
|
550 |
if request.method == 'GET': |
551 |
form = FeedbackForm() |
552 |
if request.method == 'POST': |
553 |
if not request.user: |
554 |
return HttpResponse('Unauthorized', status=401) |
555 |
|
556 |
form = FeedbackForm(request.POST) |
557 |
if form.is_valid():
|
558 |
msg = form.cleaned_data['feedback_msg']
|
559 |
data = form.cleaned_data['feedback_data']
|
560 |
send_feedback(msg, data, request.user, email_template_name) |
561 |
message = _(astakos_messages.FEEDBACK_SENT) |
562 |
messages.success(request, message) |
563 |
return HttpResponseRedirect(reverse('feedback')) |
564 |
|
565 |
return render_response(template_name,
|
566 |
feedback_form=form, |
567 |
context_instance=get_context(request, |
568 |
extra_context)) |
569 |
|
570 |
|
571 |
@require_http_methods(["GET"]) |
572 |
@cookie_fix
|
573 |
def logout(request, template='registration/logged_out.html', |
574 |
extra_context=None):
|
575 |
"""
|
576 |
Wraps `django.contrib.auth.logout`.
|
577 |
"""
|
578 |
extra_context = extra_context or {}
|
579 |
response = HttpResponse() |
580 |
if request.user.is_authenticated():
|
581 |
email = request.user.email |
582 |
auth_logout(request) |
583 |
else:
|
584 |
response['Location'] = reverse('index') |
585 |
response.status_code = 301
|
586 |
return response
|
587 |
|
588 |
next = restrict_next( |
589 |
request.GET.get('next'),
|
590 |
domain=settings.COOKIE_DOMAIN |
591 |
) |
592 |
|
593 |
if next: |
594 |
response['Location'] = next |
595 |
response.status_code = 302
|
596 |
elif settings.LOGOUT_NEXT:
|
597 |
response['Location'] = settings.LOGOUT_NEXT
|
598 |
response.status_code = 301
|
599 |
else:
|
600 |
last_provider = request.COOKIES.get( |
601 |
'astakos_last_login_method', 'local') |
602 |
provider = auth.get_provider(last_provider) |
603 |
message = provider.get_logout_success_msg |
604 |
extra = provider.get_logout_success_extra_msg |
605 |
if extra:
|
606 |
message += "<br />" + extra
|
607 |
messages.success(request, message) |
608 |
response['Location'] = reverse('index') |
609 |
response.status_code = 301
|
610 |
return response
|
611 |
|
612 |
|
613 |
@require_http_methods(["GET", "POST"]) |
614 |
@cookie_fix
|
615 |
@transaction.commit_on_success
|
616 |
def activate(request, greeting_email_template_name='im/welcome_email.txt', |
617 |
helpdesk_email_template_name='im/helpdesk_notification.txt'):
|
618 |
"""
|
619 |
Activates the user identified by the ``auth`` request parameter, sends a
|
620 |
welcome email and renews the user token.
|
621 |
|
622 |
The user state will be updated only if the email will be send successfully.
|
623 |
"""
|
624 |
token = request.GET.get('auth', None) |
625 |
next = request.GET.get('next', None) |
626 |
|
627 |
if not token: |
628 |
raise PermissionDenied
|
629 |
|
630 |
if request.user.is_authenticated():
|
631 |
message = _(astakos_messages.LOGGED_IN_WARNING) |
632 |
messages.error(request, message) |
633 |
return HttpResponseRedirect(reverse('index')) |
634 |
|
635 |
try:
|
636 |
user = AstakosUser.objects.select_for_update().\ |
637 |
get(verification_code=token) |
638 |
except AstakosUser.DoesNotExist:
|
639 |
raise Http404
|
640 |
|
641 |
if user.email_verified:
|
642 |
message = _(astakos_messages.ACCOUNT_ALREADY_VERIFIED) |
643 |
messages.error(request, message) |
644 |
return HttpResponseRedirect(reverse('index')) |
645 |
|
646 |
backend = activation_backends.get_backend() |
647 |
result = backend.handle_verification(user, token) |
648 |
backend.send_result_notifications(result, user) |
649 |
next = settings.ACTIVATION_REDIRECT_URL or next or reverse('index') |
650 |
if user.is_active:
|
651 |
response = prepare_response(request, user, next, renew=True) |
652 |
messages.success(request, _(result.message)) |
653 |
else:
|
654 |
response = HttpResponseRedirect(reverse('index'))
|
655 |
messages.warning(request, _(result.message)) |
656 |
|
657 |
return response
|
658 |
|
659 |
|
660 |
@login_required
|
661 |
def _approval_terms_post(request, template_name, terms, extra_context): |
662 |
next = restrict_next( |
663 |
request.POST.get('next'),
|
664 |
domain=settings.COOKIE_DOMAIN |
665 |
) |
666 |
if not next: |
667 |
next = reverse('index')
|
668 |
form = SignApprovalTermsForm(request.POST, instance=request.user) |
669 |
if not form.is_valid(): |
670 |
return render_response(template_name,
|
671 |
terms=terms, |
672 |
approval_terms_form=form, |
673 |
context_instance=get_context(request, |
674 |
extra_context)) |
675 |
user = form.save() |
676 |
return HttpResponseRedirect(next) |
677 |
|
678 |
|
679 |
@require_http_methods(["GET", "POST"]) |
680 |
@cookie_fix
|
681 |
def approval_terms(request, term_id=None, |
682 |
template_name='im/approval_terms.html', extra_context=None): |
683 |
extra_context = extra_context or {}
|
684 |
terms_record = None
|
685 |
terms = None
|
686 |
if not term_id: |
687 |
try:
|
688 |
terms_record = ApprovalTerms.objects.order_by('-id')[0] |
689 |
except IndexError: |
690 |
pass
|
691 |
else:
|
692 |
try:
|
693 |
terms_record = ApprovalTerms.objects.get(id=term_id) |
694 |
except ApprovalTerms.DoesNotExist, e:
|
695 |
pass
|
696 |
|
697 |
if not terms_record: |
698 |
messages.error(request, _(astakos_messages.NO_APPROVAL_TERMS)) |
699 |
return HttpResponseRedirect(reverse('index')) |
700 |
try:
|
701 |
f = open(terms_record.location, 'r') |
702 |
except IOError: |
703 |
messages.error(request, _(astakos_messages.GENERIC_ERROR)) |
704 |
return render_response(
|
705 |
template_name, context_instance=get_context(request, |
706 |
extra_context)) |
707 |
|
708 |
terms = f.read() |
709 |
|
710 |
if request.method == 'POST': |
711 |
return _approval_terms_post(request, template_name, terms,
|
712 |
extra_context) |
713 |
else:
|
714 |
form = None
|
715 |
if request.user.is_authenticated() and not request.user.signed_terms: |
716 |
form = SignApprovalTermsForm(instance=request.user) |
717 |
return render_response(template_name,
|
718 |
terms=terms, |
719 |
approval_terms_form=form, |
720 |
context_instance=get_context(request, |
721 |
extra_context)) |
722 |
|
723 |
|
724 |
@require_http_methods(["GET"]) |
725 |
@required_auth_methods_assigned(allow_access=True) |
726 |
@login_required
|
727 |
@cookie_fix
|
728 |
@signed_terms_required
|
729 |
@transaction.commit_on_success
|
730 |
def change_email_cancel(request, cancel_key): |
731 |
email_change = get_object_or_404(EmailChange, cancel_key=cancel_key) |
732 |
email_change.delete() |
733 |
msg = _(astakos_messages.EMAIL_CHANGE_REQUEST_CANCELED) |
734 |
messages.success(request, msg) |
735 |
return HttpResponseRedirect(reverse('edit_profile')) |
736 |
|
737 |
|
738 |
|
739 |
@require_http_methods(["GET", "POST"]) |
740 |
@cookie_fix
|
741 |
@transaction.commit_on_success
|
742 |
def change_email(request, activation_key=None, |
743 |
email_template_name='registration/email_change_email.txt',
|
744 |
form_template_name='registration/email_change_form.html',
|
745 |
confirm_template_name='registration/email_change_done.html',
|
746 |
extra_context=None):
|
747 |
extra_context = extra_context or {}
|
748 |
|
749 |
if not settings.EMAILCHANGE_ENABLED: |
750 |
raise PermissionDenied
|
751 |
|
752 |
objects = EmailChange.objects |
753 |
if activation_key:
|
754 |
try:
|
755 |
try:
|
756 |
email_change = objects.get(activation_key=activation_key) |
757 |
except EmailChange.DoesNotExist:
|
758 |
messages.error(request, |
759 |
_(astakos_messages.INVALID_CHANGE_EMAIL_ACTIVATION_KEY)) |
760 |
logger.error("[change-email] Invalid change email activation "
|
761 |
"code, %s", activation_key)
|
762 |
return HttpResponseRedirect(reverse('index')) |
763 |
|
764 |
if (
|
765 |
request.user.is_authenticated() and
|
766 |
request.user == email_change.user or not |
767 |
request.user.is_authenticated() |
768 |
): |
769 |
user = EmailChange.objects.change_email(activation_key) |
770 |
msg = _(astakos_messages.EMAIL_CHANGED) |
771 |
messages.success(request, msg) |
772 |
return HttpResponseRedirect(reverse('edit_profile')) |
773 |
else:
|
774 |
logger.error("[change-email] Access from invalid user, %s %s",
|
775 |
email_change.user, request.user.log_display) |
776 |
raise PermissionDenied
|
777 |
except ValueError: |
778 |
# this means that new email which corresponds to this activation url
|
779 |
# is no longer available
|
780 |
|
781 |
# invalidate change email object
|
782 |
email_change.delete() |
783 |
logger.error("[change-email] Email change with code '%s' failed. "
|
784 |
"Email address '%s' no longer available",
|
785 |
activation_key, email_change.new_email_address) |
786 |
messages.error(request, astakos_messages.NEW_EMAIL_ADDR_RESERVED) |
787 |
return HttpResponseRedirect(reverse('edit_profile')) |
788 |
|
789 |
|
790 |
return render_response(confirm_template_name,
|
791 |
modified_user=user if 'user' in locals() |
792 |
else None, |
793 |
context_instance=get_context(request, |
794 |
extra_context)) |
795 |
|
796 |
# redirect to login
|
797 |
if not request.user.is_authenticated(): |
798 |
path = quote(request.get_full_path()) |
799 |
url = request.build_absolute_uri(reverse('index'))
|
800 |
return HttpResponseRedirect(url + '?next=' + path) |
801 |
|
802 |
# clean up expired email changes
|
803 |
if request.user.email_change_is_pending():
|
804 |
change = request.user.emailchanges.get() |
805 |
if change.activation_key_expired():
|
806 |
change.delete() |
807 |
return HttpResponseRedirect(reverse('email_change')) |
808 |
|
809 |
form = EmailChangeForm(request.POST or None) |
810 |
if request.method == 'POST' and form.is_valid(): |
811 |
ec = form.save(request, email_template_name, request) |
812 |
msg = _(astakos_messages.EMAIL_CHANGE_REGISTERED) |
813 |
messages.success(request, msg) |
814 |
return HttpResponseRedirect(reverse('edit_profile')) |
815 |
|
816 |
if request.user.email_change_is_pending():
|
817 |
messages.warning(request, |
818 |
astakos_messages.PENDING_EMAIL_CHANGE_REQUEST) |
819 |
|
820 |
return render_response(
|
821 |
form_template_name, |
822 |
form=form, |
823 |
context_instance=get_context(request, extra_context) |
824 |
) |
825 |
|
826 |
|
827 |
@cookie_fix
|
828 |
@transaction.commit_on_success
|
829 |
def send_activation(request, user_id, template_name='im/login.html', |
830 |
extra_context=None):
|
831 |
|
832 |
if request.user.is_authenticated():
|
833 |
return HttpResponseRedirect(reverse('index')) |
834 |
|
835 |
extra_context = extra_context or {}
|
836 |
try:
|
837 |
u = AstakosUser.objects.select_for_update().get(id=user_id) |
838 |
except AstakosUser.DoesNotExist:
|
839 |
messages.error(request, _(astakos_messages.ACCOUNT_UNKNOWN)) |
840 |
else:
|
841 |
if u.email_verified:
|
842 |
logger.warning("[resend activation] Account already verified: %s",
|
843 |
u.log_display) |
844 |
|
845 |
messages.error(request, |
846 |
_(astakos_messages.ACCOUNT_ALREADY_VERIFIED)) |
847 |
else:
|
848 |
activation_backend = activation_backends.get_backend() |
849 |
activation_backend.send_user_verification_email(u) |
850 |
messages.success(request, astakos_messages.ACTIVATION_SENT) |
851 |
|
852 |
return HttpResponseRedirect(reverse('index')) |
853 |
|
854 |
|
855 |
@require_http_methods(["GET"]) |
856 |
@cookie_fix
|
857 |
@valid_astakos_user_required
|
858 |
def resource_usage(request): |
859 |
|
860 |
resources_meta = presentation.RESOURCES |
861 |
|
862 |
current_usage = quotas.get_user_quotas(request.user) |
863 |
current_usage = json.dumps(current_usage['system'])
|
864 |
resource_catalog, resource_groups = _resources_catalog() |
865 |
if resource_catalog is False: |
866 |
# on fail resource_groups contains the result object
|
867 |
result = resource_groups |
868 |
messages.error(request, 'Unable to retrieve system resources: %s' %
|
869 |
result.reason) |
870 |
|
871 |
resource_catalog = json.dumps(resource_catalog) |
872 |
resource_groups = json.dumps(resource_groups) |
873 |
resources_order = json.dumps(resources_meta.get('resources_order'))
|
874 |
|
875 |
return render_response('im/resource_usage.html', |
876 |
context_instance=get_context(request), |
877 |
resource_catalog=resource_catalog, |
878 |
resource_groups=resource_groups, |
879 |
resources_order=resources_order, |
880 |
current_usage=current_usage, |
881 |
token_cookie_name=settings.COOKIE_NAME, |
882 |
usage_update_interval= |
883 |
settings.USAGE_UPDATE_INTERVAL) |
884 |
|
885 |
|
886 |
# TODO: action only on POST and user should confirm the removal
|
887 |
@require_http_methods(["POST"]) |
888 |
@cookie_fix
|
889 |
@valid_astakos_user_required
|
890 |
def remove_auth_provider(request, pk): |
891 |
try:
|
892 |
provider = request.user.auth_providers.get(pk=int(pk)).settings
|
893 |
except AstakosUserAuthProvider.DoesNotExist:
|
894 |
raise Http404
|
895 |
|
896 |
if provider.get_remove_policy:
|
897 |
messages.success(request, provider.get_removed_msg) |
898 |
provider.remove_from_user() |
899 |
return HttpResponseRedirect(reverse('edit_profile')) |
900 |
else:
|
901 |
raise PermissionDenied
|
902 |
|
903 |
|
904 |
@require_http_methods(["GET"]) |
905 |
@required_auth_methods_assigned(allow_access=True) |
906 |
@login_required
|
907 |
@cookie_fix
|
908 |
@signed_terms_required
|
909 |
def landing(request): |
910 |
context = {'services': Component.catalog(orderfor='dashboard')} |
911 |
return render_response(
|
912 |
'im/landing.html',
|
913 |
context_instance=get_context(request), **context) |
914 |
|
915 |
|
916 |
@cookie_fix
|
917 |
def get_menu(request, with_extra_links=False, with_signout=True): |
918 |
user = request.user |
919 |
index_url = reverse('index')
|
920 |
|
921 |
if isinstance(user, User) and user.is_authenticated(): |
922 |
l = [] |
923 |
append = l.append |
924 |
item = MenuItem |
925 |
item.current_path = request.build_absolute_uri(request.path) |
926 |
append(item(url=request.build_absolute_uri(reverse('index')),
|
927 |
name=user.email)) |
928 |
if with_extra_links:
|
929 |
append(item(url=request.build_absolute_uri(reverse('landing')),
|
930 |
name="Overview"))
|
931 |
if with_signout:
|
932 |
append(item(url=request.build_absolute_uri(reverse('landing')),
|
933 |
name="Dashboard"))
|
934 |
if with_extra_links:
|
935 |
append( |
936 |
item( |
937 |
url=request.build_absolute_uri(reverse('edit_profile')),
|
938 |
name="Profile"))
|
939 |
|
940 |
if with_extra_links:
|
941 |
if settings.INVITATIONS_ENABLED:
|
942 |
append(item(url=request.build_absolute_uri(reverse('invite')),
|
943 |
name="Invitations"))
|
944 |
|
945 |
append(item(url=request.build_absolute_uri(reverse('api_access')),
|
946 |
name="API access"))
|
947 |
|
948 |
append( |
949 |
item( |
950 |
url=request.build_absolute_uri(reverse('resource_usage')),
|
951 |
name="Usage"))
|
952 |
|
953 |
if settings.PROJECTS_VISIBLE:
|
954 |
append( |
955 |
item( |
956 |
url=request.build_absolute_uri( |
957 |
reverse('project_list')),
|
958 |
name="Projects"))
|
959 |
|
960 |
append(item(url=request.build_absolute_uri(reverse('feedback')),
|
961 |
name="Contact"))
|
962 |
if with_signout:
|
963 |
append(item(url=request.build_absolute_uri(reverse('logout')),
|
964 |
name="Sign out"))
|
965 |
else:
|
966 |
l = [{'url': request.build_absolute_uri(index_url),
|
967 |
'name': _("Sign in")}] |
968 |
|
969 |
callback = request.GET.get('callback', None) |
970 |
data = json.dumps(tuple(l))
|
971 |
mimetype = 'application/json'
|
972 |
|
973 |
if callback:
|
974 |
mimetype = 'application/javascript'
|
975 |
data = '%s(%s)' % (callback, data)
|
976 |
|
977 |
return HttpResponse(content=data, mimetype=mimetype)
|
978 |
|
979 |
|
980 |
class MenuItem(dict): |
981 |
current_path = ''
|
982 |
|
983 |
def __init__(self, *args, **kwargs): |
984 |
super(MenuItem, self).__init__(*args, **kwargs) |
985 |
if kwargs.get('url') or kwargs.get('submenu'): |
986 |
self.__set_is_active__()
|
987 |
|
988 |
def __setitem__(self, key, value): |
989 |
super(MenuItem, self).__setitem__(key, value) |
990 |
if key in ('url', 'submenu'): |
991 |
self.__set_is_active__()
|
992 |
|
993 |
def __set_is_active__(self): |
994 |
if self.get('is_active'): |
995 |
return
|
996 |
if self.current_path.startswith(self.get('url')): |
997 |
self.__setitem__('is_active', True) |
998 |
else:
|
999 |
submenu = self.get('submenu', ()) |
1000 |
current = (i for i in submenu if i.get('url') == self.current_path) |
1001 |
try:
|
1002 |
current_node = current.next() |
1003 |
if not current_node.get('is_active'): |
1004 |
current_node.__setitem__('is_active', True) |
1005 |
self.__setitem__('is_active', True) |
1006 |
except StopIteration: |
1007 |
return
|
1008 |
|
1009 |
def __setattribute__(self, name, value): |
1010 |
super(MenuItem, self).__setattribute__(name, value) |
1011 |
if name == 'current_path': |
1012 |
self.__set_is_active__()
|
1013 |
|
1014 |
|
1015 |
def get_services(request): |
1016 |
callback = request.GET.get('callback', None) |
1017 |
mimetype = 'application/json'
|
1018 |
data = json.dumps(Component.catalog().values()) |
1019 |
|
1020 |
if callback:
|
1021 |
# Consume session messages. When get_services is loaded from an astakos
|
1022 |
# page, messages should have already been consumed in the html
|
1023 |
# response. When get_services is loaded from another domain/service we
|
1024 |
# consume them here so that no stale messages to appear if user visits
|
1025 |
# an astakos view later on.
|
1026 |
# TODO: messages could be served to other services/sites in the dict
|
1027 |
# response of get_services and/or get_menu. Services could handle those
|
1028 |
# messages respectively.
|
1029 |
messages_list = list(messages.get_messages(request))
|
1030 |
mimetype = 'application/javascript'
|
1031 |
data = '%s(%s)' % (callback, data)
|
1032 |
|
1033 |
return HttpResponse(content=data, mimetype=mimetype)
|