root / snf-astakos-app / astakos / im / views.py @ 5550bcfb
History | View | Annotate | Download (48.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 |
import logging |
35 |
import calendar |
36 |
import inflect |
37 |
|
38 |
engine = inflect.engine() |
39 |
|
40 |
from urllib import quote |
41 |
from functools import wraps |
42 |
from datetime import datetime |
43 |
|
44 |
from django.shortcuts import get_object_or_404 |
45 |
from django.contrib import messages |
46 |
from django.contrib.auth.decorators import login_required |
47 |
from django.core.urlresolvers import reverse |
48 |
from django.db import transaction |
49 |
from django.db.utils import IntegrityError |
50 |
from django.http import ( |
51 |
HttpResponse, HttpResponseBadRequest, |
52 |
HttpResponseForbidden, HttpResponseRedirect, |
53 |
HttpResponseBadRequest, Http404) |
54 |
from django.shortcuts import redirect |
55 |
from django.template import RequestContext, loader as template_loader |
56 |
from django.utils.http import urlencode |
57 |
from django.utils.translation import ugettext as _ |
58 |
from django.views.generic.create_update import ( |
59 |
apply_extra_context, lookup_object, delete_object, get_model_and_form_class) |
60 |
from django.views.generic.list_detail import object_list, object_detail |
61 |
from django.core.xheaders import populate_xheaders |
62 |
from django.core.exceptions import ValidationError, PermissionDenied |
63 |
from django.template.loader import render_to_string |
64 |
from django.views.decorators.http import require_http_methods |
65 |
from django.db.models import Q |
66 |
from django.core.exceptions import PermissionDenied |
67 |
|
68 |
import astakos.im.messages as astakos_messages |
69 |
|
70 |
from astakos.im.activation_backends import get_backend, SimpleBackend |
71 |
from astakos.im import tables |
72 |
from astakos.im.models import ( |
73 |
AstakosUser, ApprovalTerms, |
74 |
EmailChange, GroupKind, |
75 |
RESOURCE_SEPARATOR, AstakosUserAuthProvider, |
76 |
PendingThirdPartyUser, |
77 |
ProjectApplication, ProjectMembership, Project) |
78 |
from astakos.im.util import ( |
79 |
get_context, prepare_response, get_query, restrict_next) |
80 |
from astakos.im.forms import ( |
81 |
LoginForm, InvitationForm, ProfileForm, |
82 |
FeedbackForm, SignApprovalTermsForm, |
83 |
EmailChangeForm, |
84 |
ProjectApplicationForm, ProjectSortForm, |
85 |
AddProjectMembersForm, ProjectSearchForm, |
86 |
ProjectMembersSortForm) |
87 |
from astakos.im.functions import ( |
88 |
send_feedback, SendMailError, |
89 |
logout as auth_logout,
|
90 |
activate as activate_func,
|
91 |
invite, |
92 |
send_activation as send_activation_func,
|
93 |
SendNotificationError, |
94 |
accept_membership, reject_membership, remove_membership, |
95 |
leave_project, join_project, enroll_member) |
96 |
# from astakos.im.endpoints.qh import timeline_charge
|
97 |
from astakos.im.settings import ( |
98 |
COOKIE_DOMAIN, LOGOUT_NEXT, |
99 |
LOGGING_LEVEL, PAGINATE_BY, |
100 |
RESOURCES_PRESENTATION_DATA, PAGINATE_BY_ALL, |
101 |
MODERATION_ENABLED) |
102 |
from astakos.im import settings as astakos_settings |
103 |
#from astakos.im.tasks import request_billing
|
104 |
from astakos.im.api.callpoint import AstakosCallpoint |
105 |
from astakos.im import auth_providers |
106 |
from astakos.im.templatetags.filters import ResourcePresentation |
107 |
|
108 |
logger = logging.getLogger(__name__) |
109 |
|
110 |
callpoint = AstakosCallpoint() |
111 |
|
112 |
def render_response(template, tab=None, status=200, context_instance=None, **kwargs): |
113 |
"""
|
114 |
Calls ``django.template.loader.render_to_string`` with an additional ``tab``
|
115 |
keyword argument and returns an ``django.http.HttpResponse`` with the
|
116 |
specified ``status``.
|
117 |
"""
|
118 |
if tab is None: |
119 |
tab = template.partition('_')[0].partition('.html')[0] |
120 |
kwargs.setdefault('tab', tab)
|
121 |
html = template_loader.render_to_string( |
122 |
template, kwargs, context_instance=context_instance) |
123 |
response = HttpResponse(html, status=status) |
124 |
return response
|
125 |
|
126 |
def requires_auth_provider(provider_id, **perms): |
127 |
"""
|
128 |
"""
|
129 |
def decorator(func, *args, **kwargs): |
130 |
@wraps(func)
|
131 |
def wrapper(request, *args, **kwargs): |
132 |
provider = auth_providers.get_provider(provider_id) |
133 |
|
134 |
if not provider or not provider.is_active(): |
135 |
raise PermissionDenied
|
136 |
|
137 |
if provider:
|
138 |
for pkey, value in perms.iteritems(): |
139 |
attr = 'is_available_for_%s' % pkey.lower()
|
140 |
if getattr(provider, attr)() != value: |
141 |
#TODO: add session message
|
142 |
return HttpResponseRedirect(reverse('login')) |
143 |
return func(request, *args)
|
144 |
return wrapper
|
145 |
return decorator
|
146 |
|
147 |
|
148 |
def requires_anonymous(func): |
149 |
"""
|
150 |
Decorator checkes whether the request.user is not Anonymous and in that case
|
151 |
redirects to `logout`.
|
152 |
"""
|
153 |
@wraps(func)
|
154 |
def wrapper(request, *args): |
155 |
if not request.user.is_anonymous(): |
156 |
next = urlencode({'next': request.build_absolute_uri()})
|
157 |
logout_uri = reverse(logout) + '?' + next |
158 |
return HttpResponseRedirect(logout_uri)
|
159 |
return func(request, *args)
|
160 |
return wrapper
|
161 |
|
162 |
|
163 |
def signed_terms_required(func): |
164 |
"""
|
165 |
Decorator checks whether the request.user is Anonymous and in that case
|
166 |
redirects to `logout`.
|
167 |
"""
|
168 |
@wraps(func)
|
169 |
def wrapper(request, *args, **kwargs): |
170 |
if request.user.is_authenticated() and not request.user.signed_terms: |
171 |
params = urlencode({'next': request.build_absolute_uri(),
|
172 |
'show_form': ''}) |
173 |
terms_uri = reverse('latest_terms') + '?' + params |
174 |
return HttpResponseRedirect(terms_uri)
|
175 |
return func(request, *args, **kwargs)
|
176 |
return wrapper
|
177 |
|
178 |
|
179 |
def required_auth_methods_assigned(only_warn=False): |
180 |
"""
|
181 |
Decorator that checks whether the request.user has all required auth providers
|
182 |
assigned.
|
183 |
"""
|
184 |
required_providers = auth_providers.REQUIRED_PROVIDERS.keys() |
185 |
|
186 |
def decorator(func): |
187 |
if not required_providers: |
188 |
return func
|
189 |
|
190 |
@wraps(func)
|
191 |
def wrapper(request, *args, **kwargs): |
192 |
if request.user.is_authenticated():
|
193 |
for required in required_providers: |
194 |
if not request.user.has_auth_provider(required): |
195 |
provider = auth_providers.get_provider(required) |
196 |
if only_warn:
|
197 |
messages.error(request, |
198 |
_(astakos_messages.AUTH_PROVIDER_REQUIRED % { |
199 |
'provider': provider.get_title_display}))
|
200 |
else:
|
201 |
return HttpResponseRedirect(reverse('edit_profile')) |
202 |
return func(request, *args, **kwargs)
|
203 |
return wrapper
|
204 |
return decorator
|
205 |
|
206 |
|
207 |
def valid_astakos_user_required(func): |
208 |
return signed_terms_required(required_auth_methods_assigned()(login_required(func)))
|
209 |
|
210 |
|
211 |
@require_http_methods(["GET", "POST"]) |
212 |
@signed_terms_required
|
213 |
def index(request, login_template_name='im/login.html', profile_template_name='im/profile.html', extra_context=None): |
214 |
"""
|
215 |
If there is logged on user renders the profile page otherwise renders login page.
|
216 |
|
217 |
**Arguments**
|
218 |
|
219 |
``login_template_name``
|
220 |
A custom login template to use. This is optional; if not specified,
|
221 |
this will default to ``im/login.html``.
|
222 |
|
223 |
``profile_template_name``
|
224 |
A custom profile template to use. This is optional; if not specified,
|
225 |
this will default to ``im/profile.html``.
|
226 |
|
227 |
``extra_context``
|
228 |
An dictionary of variables to add to the template context.
|
229 |
|
230 |
**Template:**
|
231 |
|
232 |
im/profile.html or im/login.html or ``template_name`` keyword argument.
|
233 |
|
234 |
"""
|
235 |
extra_context = extra_context or {}
|
236 |
template_name = login_template_name |
237 |
if request.user.is_authenticated():
|
238 |
return HttpResponseRedirect(reverse('astakos.im.views.edit_profile')) |
239 |
|
240 |
third_party_token = request.GET.get('key', False) |
241 |
if third_party_token:
|
242 |
messages.info(request, astakos_messages.AUTH_PROVIDER_LOGIN_TO_ADD) |
243 |
|
244 |
return render_response(
|
245 |
template_name, |
246 |
login_form = LoginForm(request=request), |
247 |
context_instance = get_context(request, extra_context) |
248 |
) |
249 |
|
250 |
|
251 |
@require_http_methods(["GET", "POST"]) |
252 |
@valid_astakos_user_required
|
253 |
@transaction.commit_manually
|
254 |
def invite(request, template_name='im/invitations.html', extra_context=None): |
255 |
"""
|
256 |
Allows a user to invite somebody else.
|
257 |
|
258 |
In case of GET request renders a form for providing the invitee information.
|
259 |
In case of POST checks whether the user has not run out of invitations and then
|
260 |
sends an invitation email to singup to the service.
|
261 |
|
262 |
The view uses commit_manually decorator in order to ensure the number of the
|
263 |
user invitations is going to be updated only if the email has been successfully sent.
|
264 |
|
265 |
If the user isn't logged in, redirects to settings.LOGIN_URL.
|
266 |
|
267 |
**Arguments**
|
268 |
|
269 |
``template_name``
|
270 |
A custom template to use. This is optional; if not specified,
|
271 |
this will default to ``im/invitations.html``.
|
272 |
|
273 |
``extra_context``
|
274 |
An dictionary of variables to add to the template context.
|
275 |
|
276 |
**Template:**
|
277 |
|
278 |
im/invitations.html or ``template_name`` keyword argument.
|
279 |
|
280 |
**Settings:**
|
281 |
|
282 |
The view expectes the following settings are defined:
|
283 |
|
284 |
* LOGIN_URL: login uri
|
285 |
"""
|
286 |
extra_context = extra_context or {}
|
287 |
status = None
|
288 |
message = None
|
289 |
form = InvitationForm() |
290 |
|
291 |
inviter = request.user |
292 |
if request.method == 'POST': |
293 |
form = InvitationForm(request.POST) |
294 |
if inviter.invitations > 0: |
295 |
if form.is_valid():
|
296 |
try:
|
297 |
email = form.cleaned_data.get('username')
|
298 |
realname = form.cleaned_data.get('realname')
|
299 |
invite(inviter, email, realname) |
300 |
message = _(astakos_messages.INVITATION_SENT) % locals()
|
301 |
messages.success(request, message) |
302 |
except SendMailError, e:
|
303 |
message = e.message |
304 |
messages.error(request, message) |
305 |
transaction.rollback() |
306 |
except BaseException, e: |
307 |
message = _(astakos_messages.GENERIC_ERROR) |
308 |
messages.error(request, message) |
309 |
logger.exception(e) |
310 |
transaction.rollback() |
311 |
else:
|
312 |
transaction.commit() |
313 |
else:
|
314 |
message = _(astakos_messages.MAX_INVITATION_NUMBER_REACHED) |
315 |
messages.error(request, message) |
316 |
|
317 |
sent = [{'email': inv.username,
|
318 |
'realname': inv.realname,
|
319 |
'is_consumed': inv.is_consumed}
|
320 |
for inv in request.user.invitations_sent.all()] |
321 |
kwargs = {'inviter': inviter,
|
322 |
'sent': sent}
|
323 |
context = get_context(request, extra_context, **kwargs) |
324 |
return render_response(template_name,
|
325 |
invitation_form=form, |
326 |
context_instance=context) |
327 |
|
328 |
|
329 |
@require_http_methods(["GET", "POST"]) |
330 |
@required_auth_methods_assigned(only_warn=True) |
331 |
@login_required
|
332 |
@signed_terms_required
|
333 |
def edit_profile(request, template_name='im/profile.html', extra_context=None): |
334 |
"""
|
335 |
Allows a user to edit his/her profile.
|
336 |
|
337 |
In case of GET request renders a form for displaying the user information.
|
338 |
In case of POST updates the user informantion and redirects to ``next``
|
339 |
url parameter if exists.
|
340 |
|
341 |
If the user isn't logged in, redirects to settings.LOGIN_URL.
|
342 |
|
343 |
**Arguments**
|
344 |
|
345 |
``template_name``
|
346 |
A custom template to use. This is optional; if not specified,
|
347 |
this will default to ``im/profile.html``.
|
348 |
|
349 |
``extra_context``
|
350 |
An dictionary of variables to add to the template context.
|
351 |
|
352 |
**Template:**
|
353 |
|
354 |
im/profile.html or ``template_name`` keyword argument.
|
355 |
|
356 |
**Settings:**
|
357 |
|
358 |
The view expectes the following settings are defined:
|
359 |
|
360 |
* LOGIN_URL: login uri
|
361 |
"""
|
362 |
extra_context = extra_context or {}
|
363 |
form = ProfileForm( |
364 |
instance=request.user, |
365 |
session_key=request.session.session_key |
366 |
) |
367 |
extra_context['next'] = request.GET.get('next') |
368 |
if request.method == 'POST': |
369 |
form = ProfileForm( |
370 |
request.POST, |
371 |
instance=request.user, |
372 |
session_key=request.session.session_key |
373 |
) |
374 |
if form.is_valid():
|
375 |
try:
|
376 |
prev_token = request.user.auth_token |
377 |
user = form.save() |
378 |
form = ProfileForm( |
379 |
instance=user, |
380 |
session_key=request.session.session_key |
381 |
) |
382 |
next = restrict_next( |
383 |
request.POST.get('next'),
|
384 |
domain=COOKIE_DOMAIN |
385 |
) |
386 |
if next: |
387 |
return redirect(next) |
388 |
msg = _(astakos_messages.PROFILE_UPDATED) |
389 |
messages.success(request, msg) |
390 |
except ValueError, ve: |
391 |
messages.success(request, ve) |
392 |
elif request.method == "GET": |
393 |
request.user.is_verified = True
|
394 |
request.user.save() |
395 |
|
396 |
# existing providers
|
397 |
user_providers = request.user.get_active_auth_providers() |
398 |
|
399 |
# providers that user can add
|
400 |
user_available_providers = request.user.get_available_auth_providers() |
401 |
|
402 |
return render_response(template_name,
|
403 |
profile_form = form, |
404 |
user_providers = user_providers, |
405 |
user_available_providers = user_available_providers, |
406 |
context_instance = get_context(request, |
407 |
extra_context)) |
408 |
|
409 |
|
410 |
@transaction.commit_manually
|
411 |
@require_http_methods(["GET", "POST"]) |
412 |
def signup(request, template_name='im/signup.html', on_success='im/signup_complete.html', extra_context=None, backend=None): |
413 |
"""
|
414 |
Allows a user to create a local account.
|
415 |
|
416 |
In case of GET request renders a form for entering the user information.
|
417 |
In case of POST handles the signup.
|
418 |
|
419 |
The user activation will be delegated to the backend specified by the ``backend`` keyword argument
|
420 |
if present, otherwise to the ``astakos.im.activation_backends.InvitationBackend``
|
421 |
if settings.ASTAKOS_INVITATIONS_ENABLED is True or ``astakos.im.activation_backends.SimpleBackend`` if not
|
422 |
(see activation_backends);
|
423 |
|
424 |
Upon successful user creation, if ``next`` url parameter is present the user is redirected there
|
425 |
otherwise renders the same page with a success message.
|
426 |
|
427 |
On unsuccessful creation, renders ``template_name`` with an error message.
|
428 |
|
429 |
**Arguments**
|
430 |
|
431 |
``template_name``
|
432 |
A custom template to render. This is optional;
|
433 |
if not specified, this will default to ``im/signup.html``.
|
434 |
|
435 |
``on_success``
|
436 |
A custom template to render in case of success. This is optional;
|
437 |
if not specified, this will default to ``im/signup_complete.html``.
|
438 |
|
439 |
``extra_context``
|
440 |
An dictionary of variables to add to the template context.
|
441 |
|
442 |
**Template:**
|
443 |
|
444 |
im/signup.html or ``template_name`` keyword argument.
|
445 |
im/signup_complete.html or ``on_success`` keyword argument.
|
446 |
"""
|
447 |
extra_context = extra_context or {}
|
448 |
if request.user.is_authenticated():
|
449 |
return HttpResponseRedirect(reverse('edit_profile')) |
450 |
|
451 |
provider = get_query(request).get('provider', 'local') |
452 |
if not auth_providers.get_provider(provider).is_available_for_create(): |
453 |
raise PermissionDenied
|
454 |
|
455 |
id = get_query(request).get('id')
|
456 |
try:
|
457 |
instance = AstakosUser.objects.get(id=id) if id else None |
458 |
except AstakosUser.DoesNotExist:
|
459 |
instance = None
|
460 |
|
461 |
third_party_token = request.REQUEST.get('third_party_token', None) |
462 |
if third_party_token:
|
463 |
pending = get_object_or_404(PendingThirdPartyUser, |
464 |
token=third_party_token) |
465 |
provider = pending.provider |
466 |
instance = pending.get_user_instance() |
467 |
|
468 |
try:
|
469 |
if not backend: |
470 |
backend = get_backend(request) |
471 |
form = backend.get_signup_form(provider, instance) |
472 |
except Exception, e: |
473 |
form = SimpleBackend(request).get_signup_form(provider) |
474 |
messages.error(request, e) |
475 |
if request.method == 'POST': |
476 |
if form.is_valid():
|
477 |
user = form.save(commit=False)
|
478 |
try:
|
479 |
result = backend.handle_activation(user) |
480 |
status = messages.SUCCESS |
481 |
message = result.message |
482 |
|
483 |
form.store_user(user, request) |
484 |
|
485 |
if 'additional_email' in form.cleaned_data: |
486 |
additional_email = form.cleaned_data['additional_email']
|
487 |
if additional_email != user.email:
|
488 |
user.additionalmail_set.create(email=additional_email) |
489 |
msg = 'Additional email: %s saved for user %s.' % (
|
490 |
additional_email, |
491 |
user.email |
492 |
) |
493 |
logger._log(LOGGING_LEVEL, msg, []) |
494 |
if user and user.is_active: |
495 |
next = request.POST.get('next', '') |
496 |
response = prepare_response(request, user, next=next)
|
497 |
transaction.commit() |
498 |
return response
|
499 |
messages.add_message(request, status, message) |
500 |
transaction.commit() |
501 |
return render_response(
|
502 |
on_success, |
503 |
context_instance=get_context( |
504 |
request, |
505 |
extra_context |
506 |
) |
507 |
) |
508 |
except SendMailError, e:
|
509 |
logger.exception(e) |
510 |
status = messages.ERROR |
511 |
message = e.message |
512 |
messages.error(request, message) |
513 |
transaction.rollback() |
514 |
except BaseException, e: |
515 |
logger.exception(e) |
516 |
message = _(astakos_messages.GENERIC_ERROR) |
517 |
messages.error(request, message) |
518 |
logger.exception(e) |
519 |
transaction.rollback() |
520 |
return render_response(template_name,
|
521 |
signup_form=form, |
522 |
third_party_token=third_party_token, |
523 |
provider=provider, |
524 |
context_instance=get_context(request, extra_context)) |
525 |
|
526 |
|
527 |
@require_http_methods(["GET", "POST"]) |
528 |
@required_auth_methods_assigned(only_warn=True) |
529 |
@login_required
|
530 |
@signed_terms_required
|
531 |
def feedback(request, template_name='im/feedback.html', email_template_name='im/feedback_mail.txt', extra_context=None): |
532 |
"""
|
533 |
Allows a user to send feedback.
|
534 |
|
535 |
In case of GET request renders a form for providing the feedback information.
|
536 |
In case of POST sends an email to support team.
|
537 |
|
538 |
If the user isn't logged in, redirects to settings.LOGIN_URL.
|
539 |
|
540 |
**Arguments**
|
541 |
|
542 |
``template_name``
|
543 |
A custom template to use. This is optional; if not specified,
|
544 |
this will default to ``im/feedback.html``.
|
545 |
|
546 |
``extra_context``
|
547 |
An dictionary of variables to add to the template context.
|
548 |
|
549 |
**Template:**
|
550 |
|
551 |
im/signup.html or ``template_name`` keyword argument.
|
552 |
|
553 |
**Settings:**
|
554 |
|
555 |
* LOGIN_URL: login uri
|
556 |
"""
|
557 |
extra_context = extra_context or {}
|
558 |
if request.method == 'GET': |
559 |
form = FeedbackForm() |
560 |
if request.method == 'POST': |
561 |
if not request.user: |
562 |
return HttpResponse('Unauthorized', status=401) |
563 |
|
564 |
form = FeedbackForm(request.POST) |
565 |
if form.is_valid():
|
566 |
msg = form.cleaned_data['feedback_msg']
|
567 |
data = form.cleaned_data['feedback_data']
|
568 |
try:
|
569 |
send_feedback(msg, data, request.user, email_template_name) |
570 |
except SendMailError, e:
|
571 |
messages.error(request, message) |
572 |
else:
|
573 |
message = _(astakos_messages.FEEDBACK_SENT) |
574 |
messages.success(request, message) |
575 |
return render_response(template_name,
|
576 |
feedback_form=form, |
577 |
context_instance=get_context(request, extra_context)) |
578 |
|
579 |
|
580 |
@require_http_methods(["GET"]) |
581 |
@signed_terms_required
|
582 |
def logout(request, template='registration/logged_out.html', extra_context=None): |
583 |
"""
|
584 |
Wraps `django.contrib.auth.logout`.
|
585 |
"""
|
586 |
extra_context = extra_context or {}
|
587 |
response = HttpResponse() |
588 |
if request.user.is_authenticated():
|
589 |
email = request.user.email |
590 |
auth_logout(request) |
591 |
else:
|
592 |
response['Location'] = reverse('index') |
593 |
response.status_code = 301
|
594 |
return response
|
595 |
|
596 |
next = restrict_next( |
597 |
request.GET.get('next'),
|
598 |
domain=COOKIE_DOMAIN |
599 |
) |
600 |
|
601 |
if next: |
602 |
response['Location'] = next |
603 |
response.status_code = 302
|
604 |
elif LOGOUT_NEXT:
|
605 |
response['Location'] = LOGOUT_NEXT
|
606 |
response.status_code = 301
|
607 |
else:
|
608 |
messages.add_message(request, messages.SUCCESS, _(astakos_messages.LOGOUT_SUCCESS)) |
609 |
response['Location'] = reverse('index') |
610 |
response.status_code = 301
|
611 |
return response
|
612 |
|
613 |
|
614 |
@require_http_methods(["GET", "POST"]) |
615 |
@transaction.commit_manually
|
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 welcome email
|
620 |
and renews the user token.
|
621 |
|
622 |
The view uses commit_manually decorator in order to ensure the user state will be updated
|
623 |
only if the email will be send successfully.
|
624 |
"""
|
625 |
token = request.GET.get('auth')
|
626 |
next = request.GET.get('next')
|
627 |
try:
|
628 |
user = AstakosUser.objects.get(auth_token=token) |
629 |
except AstakosUser.DoesNotExist:
|
630 |
return HttpResponseBadRequest(_(astakos_messages.ACCOUNT_UNKNOWN))
|
631 |
|
632 |
if user.is_active:
|
633 |
message = _(astakos_messages.ACCOUNT_ALREADY_ACTIVE) |
634 |
messages.error(request, message) |
635 |
return index(request)
|
636 |
|
637 |
try:
|
638 |
activate_func(user, greeting_email_template_name, helpdesk_email_template_name, verify_email=True)
|
639 |
response = prepare_response(request, user, next, renew=True) |
640 |
transaction.commit() |
641 |
return response
|
642 |
except SendMailError, e:
|
643 |
message = e.message |
644 |
messages.add_message(request, messages.ERROR, message) |
645 |
transaction.rollback() |
646 |
return index(request)
|
647 |
except BaseException, e: |
648 |
status = messages.ERROR |
649 |
message = _(astakos_messages.GENERIC_ERROR) |
650 |
messages.add_message(request, messages.ERROR, message) |
651 |
logger.exception(e) |
652 |
transaction.rollback() |
653 |
return index(request)
|
654 |
|
655 |
|
656 |
@require_http_methods(["GET", "POST"]) |
657 |
def approval_terms(request, term_id=None, template_name='im/approval_terms.html', extra_context=None): |
658 |
extra_context = extra_context or {}
|
659 |
term = None
|
660 |
terms = None
|
661 |
if not term_id: |
662 |
try:
|
663 |
term = ApprovalTerms.objects.order_by('-id')[0] |
664 |
except IndexError: |
665 |
pass
|
666 |
else:
|
667 |
try:
|
668 |
term = ApprovalTerms.objects.get(id=term_id) |
669 |
except ApprovalTerms.DoesNotExist, e:
|
670 |
pass
|
671 |
|
672 |
if not term: |
673 |
messages.error(request, _(astakos_messages.NO_APPROVAL_TERMS)) |
674 |
return HttpResponseRedirect(reverse('index')) |
675 |
f = open(term.location, 'r') |
676 |
terms = f.read() |
677 |
|
678 |
if request.method == 'POST': |
679 |
next = restrict_next( |
680 |
request.POST.get('next'),
|
681 |
domain=COOKIE_DOMAIN |
682 |
) |
683 |
if not next: |
684 |
next = reverse('index')
|
685 |
form = SignApprovalTermsForm(request.POST, instance=request.user) |
686 |
if not form.is_valid(): |
687 |
return render_response(template_name,
|
688 |
terms=terms, |
689 |
approval_terms_form=form, |
690 |
context_instance=get_context(request, extra_context)) |
691 |
user = form.save() |
692 |
return HttpResponseRedirect(next) |
693 |
else:
|
694 |
form = None
|
695 |
if request.user.is_authenticated() and not request.user.signed_terms: |
696 |
form = SignApprovalTermsForm(instance=request.user) |
697 |
return render_response(template_name,
|
698 |
terms=terms, |
699 |
approval_terms_form=form, |
700 |
context_instance=get_context(request, extra_context)) |
701 |
|
702 |
|
703 |
@require_http_methods(["GET", "POST"]) |
704 |
@valid_astakos_user_required
|
705 |
@transaction.commit_manually
|
706 |
def change_email(request, activation_key=None, |
707 |
email_template_name='registration/email_change_email.txt',
|
708 |
form_template_name='registration/email_change_form.html',
|
709 |
confirm_template_name='registration/email_change_done.html',
|
710 |
extra_context=None):
|
711 |
extra_context = extra_context or {}
|
712 |
|
713 |
|
714 |
if activation_key:
|
715 |
try:
|
716 |
user = EmailChange.objects.change_email(activation_key) |
717 |
if request.user.is_authenticated() and request.user == user: |
718 |
msg = _(astakos_messages.EMAIL_CHANGED) |
719 |
messages.success(request, msg) |
720 |
auth_logout(request) |
721 |
response = prepare_response(request, user) |
722 |
transaction.commit() |
723 |
return HttpResponseRedirect(reverse('edit_profile')) |
724 |
except ValueError, e: |
725 |
messages.error(request, e) |
726 |
transaction.rollback() |
727 |
return HttpResponseRedirect(reverse('index')) |
728 |
|
729 |
return render_response(confirm_template_name,
|
730 |
modified_user=user if 'user' in locals() \ |
731 |
else None, context_instance=get_context(request, |
732 |
extra_context)) |
733 |
|
734 |
if not request.user.is_authenticated(): |
735 |
path = quote(request.get_full_path()) |
736 |
url = request.build_absolute_uri(reverse('index'))
|
737 |
return HttpResponseRedirect(url + '?next=' + path) |
738 |
|
739 |
# clean up expired email changes
|
740 |
if request.user.email_change_is_pending():
|
741 |
change = request.user.emailchanges.get() |
742 |
if change.activation_key_expired():
|
743 |
change.delete() |
744 |
transaction.commit() |
745 |
return HttpResponseRedirect(reverse('email_change')) |
746 |
|
747 |
form = EmailChangeForm(request.POST or None) |
748 |
if request.method == 'POST' and form.is_valid(): |
749 |
try:
|
750 |
# delete pending email changes
|
751 |
request.user.emailchanges.all().delete() |
752 |
ec = form.save(email_template_name, request) |
753 |
except SendMailError, e:
|
754 |
msg = e |
755 |
messages.error(request, msg) |
756 |
transaction.rollback() |
757 |
return HttpResponseRedirect(reverse('edit_profile')) |
758 |
else:
|
759 |
msg = _(astakos_messages.EMAIL_CHANGE_REGISTERED) |
760 |
messages.success(request, msg) |
761 |
transaction.commit() |
762 |
return HttpResponseRedirect(reverse('edit_profile')) |
763 |
|
764 |
if request.user.email_change_is_pending():
|
765 |
messages.warning(request, astakos_messages.PENDING_EMAIL_CHANGE_REQUEST) |
766 |
|
767 |
return render_response(
|
768 |
form_template_name, |
769 |
form=form, |
770 |
context_instance=get_context(request, extra_context) |
771 |
) |
772 |
|
773 |
|
774 |
def send_activation(request, user_id, template_name='im/login.html', extra_context=None): |
775 |
|
776 |
if request.user.is_authenticated():
|
777 |
messages.error(request, _(astakos_messages.ALREADY_LOGGED_IN)) |
778 |
return HttpResponseRedirect(reverse('edit_profile')) |
779 |
|
780 |
if astakos_settings.MODERATION_ENABLED:
|
781 |
raise PermissionDenied
|
782 |
|
783 |
extra_context = extra_context or {}
|
784 |
try:
|
785 |
u = AstakosUser.objects.get(id=user_id) |
786 |
except AstakosUser.DoesNotExist:
|
787 |
messages.error(request, _(astakos_messages.ACCOUNT_UNKNOWN)) |
788 |
else:
|
789 |
try:
|
790 |
send_activation_func(u) |
791 |
msg = _(astakos_messages.ACTIVATION_SENT) |
792 |
messages.success(request, msg) |
793 |
except SendMailError, e:
|
794 |
messages.error(request, e) |
795 |
return render_response(
|
796 |
template_name, |
797 |
login_form = LoginForm(request=request), |
798 |
context_instance = get_context( |
799 |
request, |
800 |
extra_context |
801 |
) |
802 |
) |
803 |
|
804 |
|
805 |
@require_http_methods(["GET"]) |
806 |
@valid_astakos_user_required
|
807 |
def resource_usage(request): |
808 |
|
809 |
def with_class(entry): |
810 |
entry['load_class'] = 'red' |
811 |
max_value = float(entry['maxValue']) |
812 |
curr_value = float(entry['currValue']) |
813 |
entry['ratio_limited']= 0 |
814 |
if max_value > 0 : |
815 |
entry['ratio'] = (curr_value / max_value) * 100 |
816 |
else:
|
817 |
entry['ratio'] = 0 |
818 |
if entry['ratio'] < 66: |
819 |
entry['load_class'] = 'yellow' |
820 |
if entry['ratio'] < 33: |
821 |
entry['load_class'] = 'green' |
822 |
if entry['ratio']<0: |
823 |
entry['ratio'] = 0 |
824 |
if entry['ratio']>100: |
825 |
entry['ratio_limited'] = 100 |
826 |
else:
|
827 |
entry['ratio_limited'] = entry['ratio'] |
828 |
return entry
|
829 |
|
830 |
def pluralize(entry): |
831 |
entry['plural'] = engine.plural(entry.get('name')) |
832 |
return entry
|
833 |
|
834 |
resource_usage = None
|
835 |
result = callpoint.get_user_usage(request.user.id) |
836 |
if result.is_success:
|
837 |
resource_usage = result.data |
838 |
backenddata = map(with_class, result.data)
|
839 |
backenddata = map(with_class, backenddata)
|
840 |
|
841 |
else:
|
842 |
messages.error(request, result.reason) |
843 |
return render_response('im/resource_usage.html', |
844 |
context_instance=get_context(request), |
845 |
resource_usage=backenddata, |
846 |
result=result) |
847 |
|
848 |
|
849 |
##@require_http_methods(["GET"])
|
850 |
#@require_http_methods(["POST", "GET"])
|
851 |
#@signed_terms_required
|
852 |
#@login_required
|
853 |
#def billing(request):
|
854 |
#
|
855 |
# today = datetime.today()
|
856 |
# month_last_day = calendar.monthrange(today.year, today.month)[1]
|
857 |
# start = request.POST.get('datefrom', None)
|
858 |
# if start:
|
859 |
# today = datetime.fromtimestamp(int(start))
|
860 |
# month_last_day = calendar.monthrange(today.year, today.month)[1]
|
861 |
#
|
862 |
# start = datetime(today.year, today.month, 1).strftime("%s")
|
863 |
# end = datetime(today.year, today.month, month_last_day).strftime("%s")
|
864 |
# r = request_billing.apply(args=('pgerakios@grnet.gr',
|
865 |
# int(start) * 1000,
|
866 |
# int(end) * 1000))
|
867 |
# data = {}
|
868 |
#
|
869 |
# try:
|
870 |
# status, data = r.result
|
871 |
# data = _clear_billing_data(data)
|
872 |
# if status != 200:
|
873 |
# messages.error(request, _(astakos_messages.BILLING_ERROR) % status)
|
874 |
# except:
|
875 |
# messages.error(request, r.result)
|
876 |
#
|
877 |
# return render_response(
|
878 |
# template='im/billing.html',
|
879 |
# context_instance=get_context(request),
|
880 |
# data=data,
|
881 |
# zerodate=datetime(month=1, year=1970, day=1),
|
882 |
# today=today,
|
883 |
# start=int(start),
|
884 |
# month_last_day=month_last_day)
|
885 |
|
886 |
|
887 |
#def _clear_billing_data(data):
|
888 |
#
|
889 |
# # remove addcredits entries
|
890 |
# def isnotcredit(e):
|
891 |
# return e['serviceName'] != "addcredits"
|
892 |
#
|
893 |
# # separate services
|
894 |
# def servicefilter(service_name):
|
895 |
# service = service_name
|
896 |
#
|
897 |
# def fltr(e):
|
898 |
# return e['serviceName'] == service
|
899 |
# return fltr
|
900 |
#
|
901 |
# data['bill_nocredits'] = filter(isnotcredit, data['bill'])
|
902 |
# data['bill_vmtime'] = filter(servicefilter('vmtime'), data['bill'])
|
903 |
# data['bill_diskspace'] = filter(servicefilter('diskspace'), data['bill'])
|
904 |
# data['bill_addcredits'] = filter(servicefilter('addcredits'), data['bill'])
|
905 |
#
|
906 |
# return data
|
907 |
|
908 |
|
909 |
# #@require_http_methods(["GET"])
|
910 |
# @require_http_methods(["POST", "GET"])
|
911 |
# @signed_terms_required
|
912 |
# @login_required
|
913 |
# def timeline(request):
|
914 |
# # data = {'entity':request.user.email}
|
915 |
# timeline_body = ()
|
916 |
# timeline_header = ()
|
917 |
# # form = TimelineForm(data)
|
918 |
# form = TimelineForm()
|
919 |
# if request.method == 'POST':
|
920 |
# data = request.POST
|
921 |
# form = TimelineForm(data)
|
922 |
# if form.is_valid():
|
923 |
# data = form.cleaned_data
|
924 |
# timeline_header = ('entity', 'resource',
|
925 |
# 'event name', 'event date',
|
926 |
# 'incremental cost', 'total cost')
|
927 |
# timeline_body = timeline_charge(
|
928 |
# data['entity'], data['resource'],
|
929 |
# data['start_date'], data['end_date'],
|
930 |
# data['details'], data['operation'])
|
931 |
#
|
932 |
# return render_response(template='im/timeline.html',
|
933 |
# context_instance=get_context(request),
|
934 |
# form=form,
|
935 |
# timeline_header=timeline_header,
|
936 |
# timeline_body=timeline_body)
|
937 |
# return data
|
938 |
|
939 |
|
940 |
# TODO: action only on POST and user should confirm the removal
|
941 |
@require_http_methods(["GET", "POST"]) |
942 |
@login_required
|
943 |
@signed_terms_required
|
944 |
def remove_auth_provider(request, pk): |
945 |
try:
|
946 |
provider = request.user.auth_providers.get(pk=pk) |
947 |
except AstakosUserAuthProvider.DoesNotExist:
|
948 |
raise Http404
|
949 |
|
950 |
if provider.can_remove():
|
951 |
provider.delete() |
952 |
return HttpResponseRedirect(reverse('edit_profile')) |
953 |
else:
|
954 |
raise PermissionDenied
|
955 |
|
956 |
|
957 |
def how_it_works(request): |
958 |
return render_response(
|
959 |
'im/how_it_works.html',
|
960 |
context_instance=get_context(request)) |
961 |
|
962 |
@transaction.commit_manually
|
963 |
def _create_object(request, model=None, template_name=None, |
964 |
template_loader=template_loader, extra_context=None, post_save_redirect=None, |
965 |
login_required=False, context_processors=None, form_class=None): |
966 |
"""
|
967 |
Based of django.views.generic.create_update.create_object which displays a
|
968 |
summary page before creating the object.
|
969 |
"""
|
970 |
rollback = False
|
971 |
response = None
|
972 |
|
973 |
if extra_context is None: extra_context = {} |
974 |
if login_required and not request.user.is_authenticated(): |
975 |
return redirect_to_login(request.path)
|
976 |
try:
|
977 |
|
978 |
model, form_class = get_model_and_form_class(model, form_class) |
979 |
extra_context['edit'] = 0 |
980 |
if request.method == 'POST': |
981 |
form = form_class(request.POST, request.FILES) |
982 |
if form.is_valid():
|
983 |
verify = request.GET.get('verify')
|
984 |
edit = request.GET.get('edit')
|
985 |
if verify == '1': |
986 |
extra_context['show_form'] = False |
987 |
extra_context['form_data'] = form.cleaned_data
|
988 |
elif edit == '1': |
989 |
extra_context['show_form'] = True |
990 |
else:
|
991 |
new_object = form.save() |
992 |
|
993 |
msg = _("The %(verbose_name)s was created successfully.") %\
|
994 |
{"verbose_name": model._meta.verbose_name}
|
995 |
messages.success(request, msg, fail_silently=True)
|
996 |
response = redirect(post_save_redirect, new_object) |
997 |
else:
|
998 |
form = form_class() |
999 |
except BaseException, e: |
1000 |
logger.exception(e) |
1001 |
messages.error(request, _(astakos_messages.GENERIC_ERROR)) |
1002 |
rollback = True
|
1003 |
finally:
|
1004 |
if rollback:
|
1005 |
transaction.rollback() |
1006 |
else:
|
1007 |
transaction.commit() |
1008 |
|
1009 |
if response == None: |
1010 |
# Create the template, context, response
|
1011 |
if not template_name: |
1012 |
template_name = "%s/%s_form.html" %\
|
1013 |
(model._meta.app_label, model._meta.object_name.lower()) |
1014 |
t = template_loader.get_template(template_name) |
1015 |
c = RequestContext(request, { |
1016 |
'form': form
|
1017 |
}, context_processors) |
1018 |
apply_extra_context(extra_context, c) |
1019 |
response = HttpResponse(t.render(c)) |
1020 |
return response
|
1021 |
|
1022 |
@transaction.commit_manually
|
1023 |
def _update_object(request, model=None, object_id=None, slug=None, |
1024 |
slug_field='slug', template_name=None, template_loader=template_loader, |
1025 |
extra_context=None, post_save_redirect=None, login_required=False, |
1026 |
context_processors=None, template_object_name='object', |
1027 |
form_class=None):
|
1028 |
"""
|
1029 |
Based of django.views.generic.create_update.update_object which displays a
|
1030 |
summary page before updating the object.
|
1031 |
"""
|
1032 |
rollback = False
|
1033 |
response = None
|
1034 |
|
1035 |
if extra_context is None: extra_context = {} |
1036 |
if login_required and not request.user.is_authenticated(): |
1037 |
return redirect_to_login(request.path)
|
1038 |
|
1039 |
try:
|
1040 |
model, form_class = get_model_and_form_class(model, form_class) |
1041 |
obj = lookup_object(model, object_id, slug, slug_field) |
1042 |
|
1043 |
if request.method == 'POST': |
1044 |
form = form_class(request.POST, request.FILES, instance=obj) |
1045 |
if form.is_valid():
|
1046 |
verify = request.GET.get('verify')
|
1047 |
edit = request.GET.get('edit')
|
1048 |
if verify == '1': |
1049 |
extra_context['show_form'] = False |
1050 |
extra_context['form_data'] = form.cleaned_data
|
1051 |
elif edit == '1': |
1052 |
extra_context['show_form'] = True |
1053 |
else:
|
1054 |
obj = form.save() |
1055 |
msg = _("The %(verbose_name)s was updated successfully.") %\
|
1056 |
{"verbose_name": model._meta.verbose_name}
|
1057 |
messages.success(request, msg, fail_silently=True)
|
1058 |
response = redirect(post_save_redirect, obj) |
1059 |
else:
|
1060 |
form = form_class(instance=obj) |
1061 |
except BaseException, e: |
1062 |
logger.exception(e) |
1063 |
messages.error(request, _(astakos_messages.GENERIC_ERROR)) |
1064 |
rollback = True
|
1065 |
finally:
|
1066 |
if rollback:
|
1067 |
transaction.rollback() |
1068 |
else:
|
1069 |
transaction.commit() |
1070 |
if response == None: |
1071 |
if not template_name: |
1072 |
template_name = "%s/%s_form.html" %\
|
1073 |
(model._meta.app_label, model._meta.object_name.lower()) |
1074 |
t = template_loader.get_template(template_name) |
1075 |
c = RequestContext(request, { |
1076 |
'form': form,
|
1077 |
template_object_name: obj, |
1078 |
}, context_processors) |
1079 |
apply_extra_context(extra_context, c) |
1080 |
response = HttpResponse(t.render(c)) |
1081 |
populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.attname))
|
1082 |
return response
|
1083 |
|
1084 |
@require_http_methods(["GET", "POST"]) |
1085 |
@signed_terms_required
|
1086 |
@login_required
|
1087 |
def project_add(request): |
1088 |
result = callpoint.list_resources() |
1089 |
if not result.is_success: |
1090 |
messages.error( |
1091 |
request, |
1092 |
'Unable to retrieve system resources: %s' % result.reason
|
1093 |
) |
1094 |
else:
|
1095 |
resource_catalog = result.data |
1096 |
extra_context = {'resource_catalog':resource_catalog, 'show_form':True} |
1097 |
return _create_object(request, template_name='im/projects/projectapplication_form.html', |
1098 |
extra_context=extra_context, post_save_redirect='/im/project/list/',
|
1099 |
form_class=ProjectApplicationForm) |
1100 |
|
1101 |
|
1102 |
@require_http_methods(["GET"]) |
1103 |
@signed_terms_required
|
1104 |
@login_required
|
1105 |
def project_list(request): |
1106 |
projects = ProjectApplication.objects.user_projects(request.user).select_related() |
1107 |
table = tables.UserProjectApplicationsTable(projects, user=request.user, prefix="my_projects")
|
1108 |
table.paginate(page=request.GET.get('my_projectspage', 1), per_page=PAGINATE_BY) |
1109 |
|
1110 |
return object_list(
|
1111 |
request, |
1112 |
projects, |
1113 |
template_name='im/projects/project_list.html',
|
1114 |
extra_context={ |
1115 |
'is_search':False, |
1116 |
'table': table,
|
1117 |
} |
1118 |
) |
1119 |
|
1120 |
@require_http_methods(["GET", "POST"]) |
1121 |
@signed_terms_required
|
1122 |
@login_required
|
1123 |
def project_update(request, application_id): |
1124 |
result = callpoint.list_resources() |
1125 |
if not result.is_success: |
1126 |
messages.error( |
1127 |
request, |
1128 |
'Unable to retrieve system resources: %s' % result.reason
|
1129 |
) |
1130 |
else:
|
1131 |
resource_catalog = result.data |
1132 |
extra_context = {'resource_catalog':resource_catalog, 'show_form':True} |
1133 |
return _update_object(
|
1134 |
request, |
1135 |
object_id=application_id, |
1136 |
template_name='im/projects/projectapplication_form.html',
|
1137 |
extra_context=extra_context, post_save_redirect='/im/project/list/',
|
1138 |
form_class=ProjectApplicationForm) |
1139 |
|
1140 |
|
1141 |
@require_http_methods(["GET", "POST"]) |
1142 |
@signed_terms_required
|
1143 |
@login_required
|
1144 |
@transaction.commit_manually
|
1145 |
def project_detail(request, application_id): |
1146 |
resource_catalog = None
|
1147 |
result = callpoint.list_resources() |
1148 |
if not result.is_success: |
1149 |
messages.error( |
1150 |
request, |
1151 |
'Unable to retrieve system resources: %s' % result.reason
|
1152 |
) |
1153 |
else:
|
1154 |
resource_catalog = result.data |
1155 |
|
1156 |
addmembers_form = AddProjectMembersForm() |
1157 |
if request.method == 'POST': |
1158 |
addmembers_form = AddProjectMembersForm(request.POST) |
1159 |
if addmembers_form.is_valid():
|
1160 |
try:
|
1161 |
rollback = False
|
1162 |
application_id = int(application_id)
|
1163 |
map(lambda u: enroll_member( |
1164 |
application_id, |
1165 |
u, |
1166 |
request_user=request.user), |
1167 |
addmembers_form.valid_users) |
1168 |
except (IOError, PermissionDenied), e: |
1169 |
messages.error(request, e) |
1170 |
except BaseException, e: |
1171 |
rollback = True
|
1172 |
messages.error(request, e) |
1173 |
finally:
|
1174 |
if rollback == True: |
1175 |
transaction.rollback() |
1176 |
else:
|
1177 |
transaction.commit() |
1178 |
addmembers_form = AddProjectMembersForm() |
1179 |
|
1180 |
# validate sorting
|
1181 |
sorting = 'person__email'
|
1182 |
form = ProjectMembersSortForm(request.GET or request.POST)
|
1183 |
if form.is_valid():
|
1184 |
sorting = form.cleaned_data.get('sorting')
|
1185 |
|
1186 |
rollback = False
|
1187 |
try:
|
1188 |
return object_detail(
|
1189 |
request, |
1190 |
queryset=ProjectApplication.objects.select_related(), |
1191 |
object_id=application_id, |
1192 |
template_name='im/projects/project_detail.html',
|
1193 |
extra_context={ |
1194 |
'resource_catalog':resource_catalog,
|
1195 |
'sorting':sorting,
|
1196 |
'addmembers_form':addmembers_form
|
1197 |
} |
1198 |
) |
1199 |
except:
|
1200 |
rollback = True
|
1201 |
finally:
|
1202 |
if rollback == True: |
1203 |
transaction.rollback() |
1204 |
else:
|
1205 |
transaction.commit() |
1206 |
|
1207 |
|
1208 |
@require_http_methods(["GET", "POST"]) |
1209 |
@signed_terms_required
|
1210 |
@login_required
|
1211 |
def project_search(request): |
1212 |
q = request.GET.get('q', '') |
1213 |
queryset = ProjectApplication.objects.filter() |
1214 |
|
1215 |
if request.method == 'GET': |
1216 |
form = ProjectSearchForm() |
1217 |
q = q.strip() |
1218 |
queryset = queryset.filter(~Q(project__last_approval_date__isnull=True))
|
1219 |
queryset = queryset.filter(name__contains=q) |
1220 |
else:
|
1221 |
form = ProjectSearchForm(request.POST) |
1222 |
|
1223 |
if form.is_valid():
|
1224 |
q = form.cleaned_data['q'].strip()
|
1225 |
queryset = queryset.filter(~Q(project__last_approval_date__isnull=True))
|
1226 |
queryset = queryset.filter(name__contains=q) |
1227 |
else:
|
1228 |
queryset = queryset.none() |
1229 |
|
1230 |
sorting = 'name'
|
1231 |
# validate sorting
|
1232 |
sort_form = ProjectSortForm(request.GET) |
1233 |
if sort_form.is_valid():
|
1234 |
sorting = sort_form.cleaned_data.get('sorting')
|
1235 |
queryset = queryset.order_by(sorting) |
1236 |
|
1237 |
return object_list(
|
1238 |
request, |
1239 |
queryset, |
1240 |
paginate_by=PAGINATE_BY_ALL, |
1241 |
page=request.GET.get('page') or 1, |
1242 |
template_name='im/projects/project_list.html',
|
1243 |
extra_context=dict(
|
1244 |
form=form, |
1245 |
is_search=True,
|
1246 |
sorting=sorting, |
1247 |
q=q, |
1248 |
) |
1249 |
) |
1250 |
|
1251 |
@require_http_methods(["POST"]) |
1252 |
@signed_terms_required
|
1253 |
@login_required
|
1254 |
@transaction.commit_manually
|
1255 |
def project_join(request, application_id): |
1256 |
next = request.GET.get('next')
|
1257 |
if not next: |
1258 |
return HttpResponseBadRequest(
|
1259 |
_(astakos_messages.MISSING_NEXT_PARAMETER)) |
1260 |
|
1261 |
rollback = False
|
1262 |
try:
|
1263 |
application_id = int(application_id)
|
1264 |
join_project(application_id, request.user) |
1265 |
except (IOError, PermissionDenied), e: |
1266 |
messages.error(request, e) |
1267 |
except BaseException, e: |
1268 |
logger.exception(e) |
1269 |
messages.error(request, _(astakos_messages.GENERIC_ERROR)) |
1270 |
rollback = True
|
1271 |
finally:
|
1272 |
if rollback:
|
1273 |
transaction.rollback() |
1274 |
else:
|
1275 |
transaction.commit() |
1276 |
next = restrict_next(next, domain=COOKIE_DOMAIN)
|
1277 |
return redirect(next) |
1278 |
|
1279 |
@require_http_methods(["POST"]) |
1280 |
@signed_terms_required
|
1281 |
@login_required
|
1282 |
@transaction.commit_manually
|
1283 |
def project_leave(request, application_id): |
1284 |
next = request.GET.get('next')
|
1285 |
if not next: |
1286 |
return HttpResponseBadRequest(
|
1287 |
_(astakos_messages.MISSING_NEXT_PARAMETER)) |
1288 |
|
1289 |
rollback = False
|
1290 |
try:
|
1291 |
application_id = int(application_id)
|
1292 |
leave_project(application_id, request.user) |
1293 |
except (IOError, PermissionDenied), e: |
1294 |
messages.error(request, e) |
1295 |
except BaseException, e: |
1296 |
logger.exception(e) |
1297 |
messages.error(request, _(astakos_messages.GENERIC_ERROR)) |
1298 |
rollback = True
|
1299 |
finally:
|
1300 |
if rollback:
|
1301 |
transaction.rollback() |
1302 |
else:
|
1303 |
transaction.commit() |
1304 |
|
1305 |
next = restrict_next(next, domain=COOKIE_DOMAIN)
|
1306 |
return redirect(next) |
1307 |
|
1308 |
@require_http_methods(["GET"]) |
1309 |
@signed_terms_required
|
1310 |
@login_required
|
1311 |
@transaction.commit_manually
|
1312 |
def project_accept_member(request, application_id, user_id): |
1313 |
rollback = False
|
1314 |
try:
|
1315 |
application_id = int(application_id)
|
1316 |
user_id = int(user_id)
|
1317 |
m = accept_membership(application_id, user_id, request.user) |
1318 |
except (IOError, PermissionDenied), e: |
1319 |
messages.error(request, e) |
1320 |
except BaseException, e: |
1321 |
logger.exception(e) |
1322 |
messages.error(request, _(astakos_messages.GENERIC_ERROR)) |
1323 |
rollback = True
|
1324 |
else:
|
1325 |
realname = m.person.realname |
1326 |
msg = _(astakos_messages.USER_JOINED_PROJECT) % locals()
|
1327 |
messages.success(request, msg) |
1328 |
finally:
|
1329 |
if rollback:
|
1330 |
transaction.rollback() |
1331 |
else:
|
1332 |
transaction.commit() |
1333 |
return redirect(reverse('project_detail', args=(application_id,))) |
1334 |
|
1335 |
@require_http_methods(["GET"]) |
1336 |
@signed_terms_required
|
1337 |
@login_required
|
1338 |
@transaction.commit_manually
|
1339 |
def project_remove_member(request, application_id, user_id): |
1340 |
rollback = False
|
1341 |
try:
|
1342 |
application_id = int(application_id)
|
1343 |
user_id = int(user_id)
|
1344 |
m = remove_membership(application_id, user_id, request.user) |
1345 |
except (IOError, PermissionDenied), e: |
1346 |
messages.error(request, e) |
1347 |
except BaseException, e: |
1348 |
logger.exception(e) |
1349 |
messages.error(request, _(astakos_messages.GENERIC_ERROR)) |
1350 |
rollback = True
|
1351 |
else:
|
1352 |
realname = m.person.realname |
1353 |
msg = _(astakos_messages.USER_LEFT_PROJECT) % locals()
|
1354 |
messages.success(request, msg) |
1355 |
finally:
|
1356 |
if rollback:
|
1357 |
transaction.rollback() |
1358 |
else:
|
1359 |
transaction.commit() |
1360 |
return redirect(reverse('project_detail', args=(application_id,))) |
1361 |
|
1362 |
@require_http_methods(["GET"]) |
1363 |
@signed_terms_required
|
1364 |
@login_required
|
1365 |
@transaction.commit_manually
|
1366 |
def project_reject_member(request, application_id, user_id): |
1367 |
rollback = False
|
1368 |
try:
|
1369 |
application_id = int(application_id)
|
1370 |
user_id = int(user_id)
|
1371 |
m = reject_membership(application_id, user_id, request.user) |
1372 |
except (IOError, PermissionDenied), e: |
1373 |
messages.error(request, e) |
1374 |
except BaseException, e: |
1375 |
logger.exception(e) |
1376 |
messages.error(request, _(astakos_messages.GENERIC_ERROR)) |
1377 |
rollback = True
|
1378 |
else:
|
1379 |
realname = m.person.realname |
1380 |
msg = _(astakos_messages.USER_LEFT_PROJECT) % locals()
|
1381 |
messages.success(request, msg) |
1382 |
finally:
|
1383 |
if rollback:
|
1384 |
transaction.rollback() |
1385 |
else:
|
1386 |
transaction.commit() |
1387 |
return redirect(reverse('project_detail', args=(application_id,))) |
1388 |
|
1389 |
|