root / snf-astakos-app / astakos / im / functions.py @ e1723ca1
History | View | Annotate | Download (30 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 |
from datetime import datetime |
36 |
|
37 |
from django.utils.translation import ugettext as _ |
38 |
from django.core.mail import send_mail, get_connection |
39 |
from django.core.urlresolvers import reverse |
40 |
from django.contrib.auth import login as auth_login, logout as auth_logout |
41 |
from django.core.exceptions import PermissionDenied |
42 |
from django.db.models import Q |
43 |
|
44 |
from synnefo_branding.utils import render_to_string |
45 |
|
46 |
from synnefo.lib import join_urls |
47 |
from astakos.im.models import AstakosUser, Invitation, ProjectMembership, \ |
48 |
ProjectApplication, Project, new_chain, Resource |
49 |
from astakos.im.quotas import qh_sync_user, get_pending_app_quota, \ |
50 |
register_pending_apps, qh_sync_project, qh_sync_locked_users, \ |
51 |
get_users_for_update, members_to_sync |
52 |
from astakos.im.project_notif import membership_change_notify, \ |
53 |
membership_enroll_notify, membership_request_notify, \ |
54 |
membership_leave_request_notify, application_submit_notify, \ |
55 |
application_approve_notify, application_deny_notify, \ |
56 |
project_termination_notify, project_suspension_notify |
57 |
from astakos.im import settings |
58 |
|
59 |
import astakos.im.messages as astakos_messages |
60 |
|
61 |
logger = logging.getLogger(__name__) |
62 |
|
63 |
|
64 |
def login(request, user): |
65 |
auth_login(request, user) |
66 |
from astakos.im.models import SessionCatalog |
67 |
SessionCatalog( |
68 |
session_key=request.session.session_key, |
69 |
user=user |
70 |
).save() |
71 |
logger.info('%s logged in.', user.log_display)
|
72 |
|
73 |
|
74 |
def logout(request, *args, **kwargs): |
75 |
user = request.user |
76 |
auth_logout(request, *args, **kwargs) |
77 |
logger.info('%s logged out.', user.log_display)
|
78 |
|
79 |
|
80 |
def send_verification(user, template_name='im/activation_email.txt'): |
81 |
"""
|
82 |
Send email to user to verify his/her email and activate his/her account.
|
83 |
"""
|
84 |
url = join_urls(settings.BASE_HOST, |
85 |
user.get_activation_url(nxt=reverse('index')))
|
86 |
message = render_to_string(template_name, { |
87 |
'user': user,
|
88 |
'url': url,
|
89 |
'baseurl': settings.BASE_URL,
|
90 |
'site_name': settings.SITENAME,
|
91 |
'support': settings.CONTACT_EMAIL})
|
92 |
sender = settings.SERVER_EMAIL |
93 |
send_mail(_(astakos_messages.VERIFICATION_EMAIL_SUBJECT), message, sender, |
94 |
[user.email], |
95 |
connection=get_connection()) |
96 |
logger.info("Sent user verirfication email: %s", user.log_display)
|
97 |
|
98 |
|
99 |
def _send_admin_notification(template_name, |
100 |
context=None,
|
101 |
user=None,
|
102 |
msg="",
|
103 |
subject='alpha2 testing notification',):
|
104 |
"""
|
105 |
Send notification email to settings.HELPDESK + settings.MANAGERS +
|
106 |
settings.ADMINS.
|
107 |
"""
|
108 |
if context is None: |
109 |
context = {} |
110 |
if not 'user' in context: |
111 |
context['user'] = user
|
112 |
|
113 |
message = render_to_string(template_name, context) |
114 |
sender = settings.SERVER_EMAIL |
115 |
recipient_list = [e[1] for e in settings.HELPDESK + |
116 |
settings.MANAGERS + settings.ADMINS] |
117 |
send_mail(subject, message, sender, recipient_list, |
118 |
connection=get_connection()) |
119 |
if user:
|
120 |
msg = 'Sent admin notification (%s) for user %s' % (msg,
|
121 |
user.log_display) |
122 |
else:
|
123 |
msg = 'Sent admin notification (%s)' % msg
|
124 |
|
125 |
logger.log(settings.LOGGING_LEVEL, msg) |
126 |
|
127 |
|
128 |
def send_account_pending_moderation_notification( |
129 |
user, |
130 |
template_name='im/account_pending_moderation_notification.txt'):
|
131 |
"""
|
132 |
Notify admins that a new user has verified his email address and moderation
|
133 |
step is required to activate his account.
|
134 |
"""
|
135 |
subject = (_(astakos_messages.ACCOUNT_CREATION_SUBJECT) % |
136 |
{'user': user.email})
|
137 |
return _send_admin_notification(template_name, {}, subject=subject,
|
138 |
user=user, msg="account creation")
|
139 |
|
140 |
|
141 |
def send_account_activated_notification( |
142 |
user, |
143 |
template_name='im/account_activated_notification.txt'):
|
144 |
"""
|
145 |
Send email to settings.HELPDESK + settings.MANAGERES + settings.ADMINS
|
146 |
lists to notify that a new account has been accepted and activated.
|
147 |
"""
|
148 |
message = render_to_string( |
149 |
template_name, |
150 |
{'user': user}
|
151 |
) |
152 |
sender = settings.SERVER_EMAIL |
153 |
recipient_list = [e[1] for e in settings.HELPDESK + |
154 |
settings.MANAGERS + settings.ADMINS] |
155 |
send_mail(_(astakos_messages.HELPDESK_NOTIFICATION_EMAIL_SUBJECT) % |
156 |
{'user': user.email},
|
157 |
message, sender, recipient_list, connection=get_connection()) |
158 |
msg = 'Sent helpdesk admin notification for %s' % user.email
|
159 |
logger.log(settings.LOGGING_LEVEL, msg) |
160 |
|
161 |
|
162 |
def send_invitation(invitation, template_name='im/invitation.txt'): |
163 |
"""
|
164 |
Send invitation email.
|
165 |
"""
|
166 |
subject = _(astakos_messages.INVITATION_EMAIL_SUBJECT) |
167 |
url = '%s?code=%d' % (join_urls(settings.BASE_HOST,
|
168 |
reverse('index')), invitation.code)
|
169 |
message = render_to_string(template_name, { |
170 |
'invitation': invitation,
|
171 |
'url': url,
|
172 |
'baseurl': settings.BASE_URL,
|
173 |
'site_name': settings.SITENAME,
|
174 |
'support': settings.CONTACT_EMAIL})
|
175 |
sender = settings.SERVER_EMAIL |
176 |
send_mail(subject, message, sender, [invitation.username], |
177 |
connection=get_connection()) |
178 |
msg = 'Sent invitation %s' % invitation
|
179 |
logger.log(settings.LOGGING_LEVEL, msg) |
180 |
inviter_invitations = invitation.inviter.invitations |
181 |
invitation.inviter.invitations = max(0, inviter_invitations - 1) |
182 |
invitation.inviter.save() |
183 |
|
184 |
|
185 |
def send_greeting(user, email_template_name='im/welcome_email.txt'): |
186 |
"""
|
187 |
Send welcome email to an accepted/activated user.
|
188 |
|
189 |
Raises SMTPException, socket.error
|
190 |
"""
|
191 |
subject = _(astakos_messages.GREETING_EMAIL_SUBJECT) |
192 |
message = render_to_string(email_template_name, { |
193 |
'user': user,
|
194 |
'url': join_urls(settings.BASE_HOST,
|
195 |
reverse('index')),
|
196 |
'baseurl': settings.BASE_URL,
|
197 |
'site_name': settings.SITENAME,
|
198 |
'support': settings.CONTACT_EMAIL})
|
199 |
sender = settings.SERVER_EMAIL |
200 |
send_mail(subject, message, sender, [user.email], |
201 |
connection=get_connection()) |
202 |
msg = 'Sent greeting %s' % user.log_display
|
203 |
logger.log(settings.LOGGING_LEVEL, msg) |
204 |
|
205 |
|
206 |
def send_feedback(msg, data, user, email_template_name='im/feedback_mail.txt'): |
207 |
subject = _(astakos_messages.FEEDBACK_EMAIL_SUBJECT) |
208 |
from_email = settings.SERVER_EMAIL |
209 |
recipient_list = [e[1] for e in settings.HELPDESK] |
210 |
content = render_to_string(email_template_name, { |
211 |
'message': msg,
|
212 |
'data': data,
|
213 |
'user': user})
|
214 |
send_mail(subject, content, from_email, recipient_list, |
215 |
connection=get_connection()) |
216 |
msg = 'Sent feedback from %s' % user.log_display
|
217 |
logger.log(settings.LOGGING_LEVEL, msg) |
218 |
|
219 |
|
220 |
def send_change_email( |
221 |
ec, request, email_template_name='registration/email_change_email.txt'
|
222 |
): |
223 |
url = ec.get_url() |
224 |
url = request.build_absolute_uri(url) |
225 |
c = {'url': url, 'site_name': settings.SITENAME, |
226 |
'support': settings.CONTACT_EMAIL,
|
227 |
'ec': ec}
|
228 |
message = render_to_string(email_template_name, c) |
229 |
from_email = settings.SERVER_EMAIL |
230 |
send_mail(_(astakos_messages.EMAIL_CHANGE_EMAIL_SUBJECT), message, |
231 |
from_email, |
232 |
[ec.new_email_address], connection=get_connection()) |
233 |
msg = 'Sent change email for %s' % ec.user.log_display
|
234 |
logger.log(settings.LOGGING_LEVEL, msg) |
235 |
|
236 |
|
237 |
def invite(inviter, email, realname): |
238 |
inv = Invitation(inviter=inviter, username=email, realname=realname) |
239 |
inv.save() |
240 |
send_invitation(inv) |
241 |
inviter.invitations = max(0, inviter.invitations - 1) |
242 |
inviter.save() |
243 |
|
244 |
|
245 |
### PROJECT FUNCTIONS ###
|
246 |
|
247 |
AUTO_ACCEPT_POLICY = 1
|
248 |
MODERATED_POLICY = 2
|
249 |
CLOSED_POLICY = 3
|
250 |
|
251 |
POLICIES = [AUTO_ACCEPT_POLICY, MODERATED_POLICY, CLOSED_POLICY] |
252 |
|
253 |
|
254 |
def get_related_project_id(application_id): |
255 |
try:
|
256 |
app = ProjectApplication.objects.get(id=application_id) |
257 |
return app.chain_id
|
258 |
except ProjectApplication.DoesNotExist:
|
259 |
return None |
260 |
|
261 |
|
262 |
def get_project_by_id(project_id): |
263 |
try:
|
264 |
return Project.objects.get(id=project_id)
|
265 |
except Project.DoesNotExist:
|
266 |
m = _(astakos_messages.UNKNOWN_PROJECT_ID) % project_id |
267 |
raise IOError(m) |
268 |
|
269 |
|
270 |
def get_project_for_update(project_id): |
271 |
try:
|
272 |
return Project.objects.get_for_update(id=project_id)
|
273 |
except Project.DoesNotExist:
|
274 |
m = _(astakos_messages.UNKNOWN_PROJECT_ID) % project_id |
275 |
raise IOError(m) |
276 |
|
277 |
|
278 |
def get_project_of_application_for_update(app_id): |
279 |
app = get_application(app_id) |
280 |
return get_project_for_update(app.chain_id)
|
281 |
|
282 |
|
283 |
def get_application(application_id): |
284 |
try:
|
285 |
return ProjectApplication.objects.get(id=application_id)
|
286 |
except ProjectApplication.DoesNotExist:
|
287 |
m = _(astakos_messages.UNKNOWN_PROJECT_APPLICATION_ID) % application_id |
288 |
raise IOError(m) |
289 |
|
290 |
|
291 |
def get_project_of_membership_for_update(memb_id): |
292 |
m = get_membership_by_id(memb_id) |
293 |
return get_project_for_update(m.project_id)
|
294 |
|
295 |
|
296 |
def get_user_by_id(user_id): |
297 |
try:
|
298 |
return AstakosUser.objects.get(id=user_id)
|
299 |
except AstakosUser.DoesNotExist:
|
300 |
m = _(astakos_messages.UNKNOWN_USER_ID) % user_id |
301 |
raise IOError(m) |
302 |
|
303 |
|
304 |
def get_user_by_uuid(uuid): |
305 |
try:
|
306 |
return AstakosUser.objects.get(uuid=uuid)
|
307 |
except AstakosUser.DoesNotExist:
|
308 |
m = _(astakos_messages.UNKNOWN_USER_ID) % uuid |
309 |
raise IOError(m) |
310 |
|
311 |
|
312 |
def get_membership(project_id, user_id): |
313 |
try:
|
314 |
objs = ProjectMembership.objects.select_related('project', 'person') |
315 |
return objs.get(project__id=project_id, person__id=user_id)
|
316 |
except ProjectMembership.DoesNotExist:
|
317 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
318 |
raise IOError(m) |
319 |
|
320 |
|
321 |
def get_membership_by_id(memb_id): |
322 |
try:
|
323 |
objs = ProjectMembership.objects.select_related('project', 'person') |
324 |
return objs.get(id=memb_id)
|
325 |
except ProjectMembership.DoesNotExist:
|
326 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
327 |
raise IOError(m) |
328 |
|
329 |
|
330 |
def checkAllowed(entity, request_user, admin_only=False): |
331 |
if isinstance(entity, Project): |
332 |
application = entity.application |
333 |
elif isinstance(entity, ProjectApplication): |
334 |
application = entity |
335 |
else:
|
336 |
m = "%s not a Project nor a ProjectApplication" % (entity,)
|
337 |
raise ValueError(m) |
338 |
|
339 |
if not request_user or request_user.is_project_admin(): |
340 |
return
|
341 |
|
342 |
if not admin_only and application.owner == request_user: |
343 |
return
|
344 |
|
345 |
m = _(astakos_messages.NOT_ALLOWED) |
346 |
raise PermissionDenied(m)
|
347 |
|
348 |
|
349 |
def checkAlive(project): |
350 |
if not project.is_alive: |
351 |
m = _(astakos_messages.NOT_ALIVE_PROJECT) % project.id |
352 |
raise PermissionDenied(m)
|
353 |
|
354 |
|
355 |
def accept_membership_project_checks(project, request_user): |
356 |
checkAllowed(project, request_user) |
357 |
checkAlive(project) |
358 |
|
359 |
join_policy = project.application.member_join_policy |
360 |
if join_policy == CLOSED_POLICY:
|
361 |
m = _(astakos_messages.MEMBER_JOIN_POLICY_CLOSED) |
362 |
raise PermissionDenied(m)
|
363 |
|
364 |
if project.violates_members_limit(adding=1): |
365 |
m = _(astakos_messages.MEMBER_NUMBER_LIMIT_REACHED) |
366 |
raise PermissionDenied(m)
|
367 |
|
368 |
|
369 |
def accept_membership_checks(membership, request_user): |
370 |
if not membership.can_accept(): |
371 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
372 |
raise PermissionDenied(m)
|
373 |
|
374 |
project = membership.project |
375 |
accept_membership_project_checks(project, request_user) |
376 |
|
377 |
|
378 |
def accept_membership(memb_id, request_user=None): |
379 |
project = get_project_of_membership_for_update(memb_id) |
380 |
membership = get_membership_by_id(memb_id) |
381 |
accept_membership_checks(membership, request_user) |
382 |
user = membership.person |
383 |
membership.accept() |
384 |
qh_sync_user(user) |
385 |
logger.info("User %s has been accepted in %s." %
|
386 |
(user.log_display, project)) |
387 |
|
388 |
membership_change_notify(project, user, 'accepted')
|
389 |
return membership
|
390 |
|
391 |
|
392 |
def reject_membership_checks(membership, request_user): |
393 |
if not membership.can_reject(): |
394 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
395 |
raise PermissionDenied(m)
|
396 |
|
397 |
project = membership.project |
398 |
checkAllowed(project, request_user) |
399 |
checkAlive(project) |
400 |
|
401 |
|
402 |
def reject_membership(memb_id, request_user=None): |
403 |
project = get_project_of_membership_for_update(memb_id) |
404 |
membership = get_membership_by_id(memb_id) |
405 |
reject_membership_checks(membership, request_user) |
406 |
user = membership.person |
407 |
membership.reject() |
408 |
logger.info("Request of user %s for %s has been rejected." %
|
409 |
(user.log_display, project)) |
410 |
|
411 |
membership_change_notify(project, user, 'rejected')
|
412 |
return membership
|
413 |
|
414 |
|
415 |
def cancel_membership_checks(membership, request_user): |
416 |
if not membership.can_cancel(): |
417 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
418 |
raise PermissionDenied(m)
|
419 |
|
420 |
if membership.person != request_user:
|
421 |
raise PermissionDenied()
|
422 |
|
423 |
project = membership.project |
424 |
checkAlive(project) |
425 |
|
426 |
|
427 |
def cancel_membership(memb_id, request_user): |
428 |
project = get_project_of_membership_for_update(memb_id) |
429 |
membership = get_membership_by_id(memb_id) |
430 |
cancel_membership_checks(membership, request_user) |
431 |
membership.cancel() |
432 |
logger.info("Request of user %s for %s has been cancelled." %
|
433 |
(membership.person.log_display, project)) |
434 |
|
435 |
|
436 |
def remove_membership_checks(membership, request_user=None): |
437 |
if not membership.can_remove(): |
438 |
m = _(astakos_messages.NOT_ACCEPTED_MEMBERSHIP) |
439 |
raise PermissionDenied(m)
|
440 |
|
441 |
project = membership.project |
442 |
checkAllowed(project, request_user) |
443 |
checkAlive(project) |
444 |
|
445 |
leave_policy = project.application.member_leave_policy |
446 |
if leave_policy == CLOSED_POLICY:
|
447 |
m = _(astakos_messages.MEMBER_LEAVE_POLICY_CLOSED) |
448 |
raise PermissionDenied(m)
|
449 |
|
450 |
|
451 |
def remove_membership(memb_id, request_user=None): |
452 |
project = get_project_of_membership_for_update(memb_id) |
453 |
membership = get_membership_by_id(memb_id) |
454 |
remove_membership_checks(membership, request_user) |
455 |
user = membership.person |
456 |
membership.remove() |
457 |
qh_sync_user(user) |
458 |
logger.info("User %s has been removed from %s." %
|
459 |
(user.log_display, project)) |
460 |
|
461 |
membership_change_notify(project, user, 'removed')
|
462 |
return membership
|
463 |
|
464 |
|
465 |
def enroll_member(project_id, user, request_user=None): |
466 |
project = get_project_for_update(project_id) |
467 |
accept_membership_project_checks(project, request_user) |
468 |
|
469 |
try:
|
470 |
membership = get_membership(project_id, user.id) |
471 |
if not membership.can_enroll(): |
472 |
m = _(astakos_messages.MEMBERSHIP_ACCEPTED) |
473 |
raise PermissionDenied(m)
|
474 |
membership.join() |
475 |
except IOError: |
476 |
membership = new_membership(project, user) |
477 |
|
478 |
membership.accept() |
479 |
qh_sync_user(user) |
480 |
logger.info("User %s has been enrolled in %s." %
|
481 |
(membership.person.log_display, project)) |
482 |
|
483 |
membership_enroll_notify(project, membership.person) |
484 |
return membership
|
485 |
|
486 |
|
487 |
def leave_project_checks(membership, request_user): |
488 |
if not membership.can_leave(): |
489 |
m = _(astakos_messages.NOT_ACCEPTED_MEMBERSHIP) |
490 |
raise PermissionDenied(m)
|
491 |
|
492 |
if membership.person != request_user:
|
493 |
raise PermissionDenied()
|
494 |
|
495 |
project = membership.project |
496 |
checkAlive(project) |
497 |
|
498 |
leave_policy = project.application.member_leave_policy |
499 |
if leave_policy == CLOSED_POLICY:
|
500 |
m = _(astakos_messages.MEMBER_LEAVE_POLICY_CLOSED) |
501 |
raise PermissionDenied(m)
|
502 |
|
503 |
|
504 |
def can_leave_request(project, user): |
505 |
m = user.get_membership(project) |
506 |
if m is None: |
507 |
return False |
508 |
try:
|
509 |
leave_project_checks(m, user) |
510 |
except PermissionDenied:
|
511 |
return False |
512 |
return True |
513 |
|
514 |
|
515 |
def leave_project(memb_id, request_user): |
516 |
project = get_project_of_membership_for_update(memb_id) |
517 |
membership = get_membership_by_id(memb_id) |
518 |
leave_project_checks(membership, request_user) |
519 |
|
520 |
auto_accepted = False
|
521 |
leave_policy = project.application.member_leave_policy |
522 |
if leave_policy == AUTO_ACCEPT_POLICY:
|
523 |
membership.remove() |
524 |
qh_sync_user(request_user) |
525 |
logger.info("User %s has left %s." %
|
526 |
(request_user.log_display, project)) |
527 |
auto_accepted = True
|
528 |
else:
|
529 |
membership.leave_request() |
530 |
logger.info("User %s requested to leave %s." %
|
531 |
(request_user.log_display, project)) |
532 |
membership_leave_request_notify(project, membership.person) |
533 |
return auto_accepted
|
534 |
|
535 |
|
536 |
def join_project_checks(project): |
537 |
checkAlive(project) |
538 |
|
539 |
join_policy = project.application.member_join_policy |
540 |
if join_policy == CLOSED_POLICY:
|
541 |
m = _(astakos_messages.MEMBER_JOIN_POLICY_CLOSED) |
542 |
raise PermissionDenied(m)
|
543 |
|
544 |
|
545 |
def can_join_request(project, user): |
546 |
try:
|
547 |
join_project_checks(project) |
548 |
except PermissionDenied:
|
549 |
return False |
550 |
|
551 |
m = user.get_membership(project) |
552 |
if not m: |
553 |
return True |
554 |
return m.can_join()
|
555 |
|
556 |
|
557 |
def new_membership(project, user): |
558 |
m = ProjectMembership.objects.create(project=project, person=user) |
559 |
m._log_create(None, ProjectMembership.REQUESTED)
|
560 |
return m
|
561 |
|
562 |
|
563 |
def join_project(project_id, request_user): |
564 |
project = get_project_for_update(project_id) |
565 |
join_project_checks(project) |
566 |
|
567 |
try:
|
568 |
membership = get_membership(project.id, request_user.id) |
569 |
if not membership.can_join(): |
570 |
msg = _(astakos_messages.MEMBERSHIP_ASSOCIATED) |
571 |
raise PermissionDenied(msg)
|
572 |
membership.join() |
573 |
except IOError: |
574 |
membership = new_membership(project, request_user) |
575 |
|
576 |
join_policy = project.application.member_join_policy |
577 |
if (join_policy == AUTO_ACCEPT_POLICY and ( |
578 |
not project.violates_members_limit(adding=1))): |
579 |
membership.accept() |
580 |
qh_sync_user(request_user) |
581 |
logger.info("User %s joined %s." %
|
582 |
(request_user.log_display, project)) |
583 |
else:
|
584 |
membership_request_notify(project, membership.person) |
585 |
logger.info("User %s requested to join %s." %
|
586 |
(request_user.log_display, project)) |
587 |
return membership
|
588 |
|
589 |
|
590 |
MEMBERSHIP_ACTION_CHECKS = { |
591 |
"leave": leave_project_checks,
|
592 |
"cancel": cancel_membership_checks,
|
593 |
"accept": accept_membership_checks,
|
594 |
"reject": reject_membership_checks,
|
595 |
"remove": remove_membership_checks,
|
596 |
} |
597 |
|
598 |
|
599 |
def membership_allowed_actions(membership, request_user): |
600 |
allowed = [] |
601 |
for action, check in MEMBERSHIP_ACTION_CHECKS.iteritems(): |
602 |
try:
|
603 |
check(membership, request_user) |
604 |
allowed.append(action) |
605 |
except PermissionDenied:
|
606 |
pass
|
607 |
return allowed
|
608 |
|
609 |
|
610 |
def submit_application(owner=None, |
611 |
name=None,
|
612 |
project_id=None,
|
613 |
homepage=None,
|
614 |
description=None,
|
615 |
start_date=None,
|
616 |
end_date=None,
|
617 |
member_join_policy=None,
|
618 |
member_leave_policy=None,
|
619 |
limit_on_members_number=None,
|
620 |
comments=None,
|
621 |
resources=None,
|
622 |
request_user=None):
|
623 |
|
624 |
project = None
|
625 |
if project_id is not None: |
626 |
project = get_project_for_update(project_id) |
627 |
|
628 |
if (request_user and |
629 |
(not project.application.owner == request_user and |
630 |
not request_user.is_superuser
|
631 |
and not request_user.is_project_admin())): |
632 |
m = _(astakos_messages.NOT_ALLOWED) |
633 |
raise PermissionDenied(m)
|
634 |
|
635 |
policies = validate_resource_policies(resources) |
636 |
|
637 |
force = request_user.is_project_admin() |
638 |
ok, limit = qh_add_pending_app(owner, project, force) |
639 |
if not ok: |
640 |
m = _(astakos_messages.REACHED_PENDING_APPLICATION_LIMIT) % limit |
641 |
raise PermissionDenied(m)
|
642 |
|
643 |
application = ProjectApplication( |
644 |
applicant=request_user, |
645 |
owner=owner, |
646 |
name=name, |
647 |
homepage=homepage, |
648 |
description=description, |
649 |
start_date=start_date, |
650 |
end_date=end_date, |
651 |
member_join_policy=member_join_policy, |
652 |
member_leave_policy=member_leave_policy, |
653 |
limit_on_members_number=limit_on_members_number, |
654 |
comments=comments) |
655 |
|
656 |
if project is None: |
657 |
chain = new_chain() |
658 |
application.chain_id = chain.chain |
659 |
application.save() |
660 |
Project.objects.create(id=chain.chain, application=application) |
661 |
else:
|
662 |
application.chain = project |
663 |
application.save() |
664 |
if project.application.state != ProjectApplication.APPROVED:
|
665 |
project.application = application |
666 |
project.save() |
667 |
|
668 |
pending = ProjectApplication.objects.filter( |
669 |
chain=project, |
670 |
state=ProjectApplication.PENDING).exclude(id=application.id) |
671 |
for app in pending: |
672 |
app.state = ProjectApplication.REPLACED |
673 |
app.save() |
674 |
|
675 |
if policies is not None: |
676 |
set_resource_policies(application, policies) |
677 |
logger.info("User %s submitted %s." %
|
678 |
(request_user.log_display, application.log_display)) |
679 |
application_submit_notify(application) |
680 |
return application
|
681 |
|
682 |
|
683 |
def validate_resource_policies(policies): |
684 |
if not isinstance(policies, dict): |
685 |
raise ProjectBadRequest("Malformed resource policies") |
686 |
|
687 |
resource_names = policies.keys() |
688 |
resources = Resource.objects.filter(name__in=resource_names) |
689 |
resource_d = {} |
690 |
for resource in resources: |
691 |
resource_d[resource.name] = resource |
692 |
|
693 |
found = resource_d.keys() |
694 |
nonex = [name for name in resource_names if name not in found] |
695 |
if nonex:
|
696 |
raise ValueError("Malformed resource policies") |
697 |
|
698 |
pols = [] |
699 |
for resource_name, specs in policies.iteritems(): |
700 |
p_capacity = specs.get("project_capacity")
|
701 |
m_capacity = specs.get("member_capacity")
|
702 |
|
703 |
if p_capacity is not None and not isinstance(p_capacity, (int, long)): |
704 |
raise ValueError("Malformed resource policies") |
705 |
if not isinstance(m_capacity, (int, long)): |
706 |
raise ValueError("Malformed resource policies") |
707 |
pols.append((resource_d[resource_name], m_capacity, p_capacity)) |
708 |
return pols
|
709 |
|
710 |
|
711 |
def set_resource_policies(application, policies): |
712 |
for resource, m_capacity, p_capacity in policies: |
713 |
g = application.projectresourcegrant_set |
714 |
g.create(resource=resource, |
715 |
member_capacity=m_capacity, |
716 |
project_capacity=p_capacity) |
717 |
|
718 |
|
719 |
def cancel_application(application_id, request_user=None, reason=""): |
720 |
get_project_of_application_for_update(application_id) |
721 |
application = get_application(application_id) |
722 |
checkAllowed(application, request_user) |
723 |
|
724 |
if not application.can_cancel(): |
725 |
m = _(astakos_messages.APPLICATION_CANNOT_CANCEL % |
726 |
(application.id, application.state_display())) |
727 |
raise PermissionDenied(m)
|
728 |
|
729 |
qh_release_pending_app(application.owner) |
730 |
|
731 |
application.cancel() |
732 |
logger.info("%s has been cancelled." % (application.log_display))
|
733 |
|
734 |
|
735 |
def dismiss_application(application_id, request_user=None, reason=""): |
736 |
get_project_of_application_for_update(application_id) |
737 |
application = get_application(application_id) |
738 |
checkAllowed(application, request_user) |
739 |
|
740 |
if not application.can_dismiss(): |
741 |
m = _(astakos_messages.APPLICATION_CANNOT_DISMISS % |
742 |
(application.id, application.state_display())) |
743 |
raise PermissionDenied(m)
|
744 |
|
745 |
application.dismiss() |
746 |
logger.info("%s has been dismissed." % (application.log_display))
|
747 |
|
748 |
|
749 |
def deny_application(application_id, request_user=None, reason=""): |
750 |
get_project_of_application_for_update(application_id) |
751 |
application = get_application(application_id) |
752 |
|
753 |
checkAllowed(application, request_user, admin_only=True)
|
754 |
|
755 |
if not application.can_deny(): |
756 |
m = _(astakos_messages.APPLICATION_CANNOT_DENY % |
757 |
(application.id, application.state_display())) |
758 |
raise PermissionDenied(m)
|
759 |
|
760 |
qh_release_pending_app(application.owner) |
761 |
|
762 |
application.deny(reason) |
763 |
logger.info("%s has been denied with reason \"%s\"." %
|
764 |
(application.log_display, reason)) |
765 |
application_deny_notify(application) |
766 |
|
767 |
|
768 |
def check_conflicting_projects(application): |
769 |
project = application.chain |
770 |
new_project_name = application.name |
771 |
try:
|
772 |
q = Q(name=new_project_name) & ~Q(state=Project.TERMINATED) |
773 |
conflicting_project = Project.objects.get(q) |
774 |
if (conflicting_project != project):
|
775 |
m = (_("cannot approve: project with name '%s' "
|
776 |
"already exists (id: %s)") %
|
777 |
(new_project_name, conflicting_project.id)) |
778 |
raise PermissionDenied(m) # invalid argument |
779 |
except Project.DoesNotExist:
|
780 |
pass
|
781 |
|
782 |
|
783 |
def approve_application(app_id, request_user=None, reason=""): |
784 |
project = get_project_of_application_for_update(app_id) |
785 |
application = get_application(app_id) |
786 |
|
787 |
checkAllowed(application, request_user, admin_only=True)
|
788 |
|
789 |
if not application.can_approve(): |
790 |
m = _(astakos_messages.APPLICATION_CANNOT_APPROVE % |
791 |
(application.id, application.state_display())) |
792 |
raise PermissionDenied(m)
|
793 |
|
794 |
check_conflicting_projects(application) |
795 |
|
796 |
# Pre-lock members and owner together in order to impose an ordering
|
797 |
# on locking users
|
798 |
members = members_to_sync(project) |
799 |
uids_to_sync = [member.id for member in members] |
800 |
owner = application.owner |
801 |
uids_to_sync.append(owner.id) |
802 |
get_users_for_update(uids_to_sync) |
803 |
|
804 |
qh_release_pending_app(owner, locked=True)
|
805 |
application.approve(reason) |
806 |
project.application = application |
807 |
project.name = application.name |
808 |
project.save() |
809 |
if project.is_deactivated():
|
810 |
project.resume() |
811 |
qh_sync_locked_users(members) |
812 |
logger.info("%s has been approved." % (application.log_display))
|
813 |
application_approve_notify(application) |
814 |
|
815 |
|
816 |
def check_expiration(execute=False): |
817 |
objects = Project.objects |
818 |
expired = objects.expired_projects() |
819 |
if execute:
|
820 |
for project in expired: |
821 |
terminate(project.pk) |
822 |
|
823 |
return [project.expiration_info() for project in expired] |
824 |
|
825 |
|
826 |
def terminate(project_id, request_user=None): |
827 |
project = get_project_for_update(project_id) |
828 |
checkAllowed(project, request_user, admin_only=True)
|
829 |
checkAlive(project) |
830 |
|
831 |
project.terminate() |
832 |
qh_sync_project(project) |
833 |
logger.info("%s has been terminated." % (project))
|
834 |
|
835 |
project_termination_notify(project) |
836 |
|
837 |
|
838 |
def suspend(project_id, request_user=None): |
839 |
project = get_project_for_update(project_id) |
840 |
checkAllowed(project, request_user, admin_only=True)
|
841 |
checkAlive(project) |
842 |
|
843 |
project.suspend() |
844 |
qh_sync_project(project) |
845 |
logger.info("%s has been suspended." % (project))
|
846 |
|
847 |
project_suspension_notify(project) |
848 |
|
849 |
|
850 |
def resume(project_id, request_user=None): |
851 |
project = get_project_for_update(project_id) |
852 |
checkAllowed(project, request_user, admin_only=True)
|
853 |
|
854 |
if not project.is_suspended: |
855 |
m = _(astakos_messages.NOT_SUSPENDED_PROJECT) % project.id |
856 |
raise PermissionDenied(m)
|
857 |
|
858 |
project.resume() |
859 |
qh_sync_project(project) |
860 |
logger.info("%s has been unsuspended." % (project))
|
861 |
|
862 |
|
863 |
def _partition_by(f, l): |
864 |
d = {} |
865 |
for x in l: |
866 |
group = f(x) |
867 |
group_l = d.get(group, []) |
868 |
group_l.append(x) |
869 |
d[group] = group_l |
870 |
return d
|
871 |
|
872 |
|
873 |
def count_pending_app(users): |
874 |
users = list(users)
|
875 |
apps = ProjectApplication.objects.filter(state=ProjectApplication.PENDING, |
876 |
owner__in=users) |
877 |
apps_d = _partition_by(lambda a: a.owner.uuid, apps)
|
878 |
|
879 |
usage = {} |
880 |
for user in users: |
881 |
uuid = user.uuid |
882 |
usage[uuid] = len(apps_d.get(uuid, []))
|
883 |
return usage
|
884 |
|
885 |
|
886 |
def get_pending_app_diff(user, project): |
887 |
if project is None: |
888 |
diff = 1
|
889 |
else:
|
890 |
objs = ProjectApplication.objects |
891 |
q = objs.filter(chain=project, state=ProjectApplication.PENDING) |
892 |
count = q.count() |
893 |
diff = 1 - count
|
894 |
return diff
|
895 |
|
896 |
|
897 |
def qh_add_pending_app(user, project=None, force=False): |
898 |
user = AstakosUser.forupdate.get_for_update(id=user.id) |
899 |
diff = get_pending_app_diff(user, project) |
900 |
return register_pending_apps(user, diff, force)
|
901 |
|
902 |
|
903 |
def check_pending_app_quota(user, project=None): |
904 |
diff = get_pending_app_diff(user, project) |
905 |
quota = get_pending_app_quota(user) |
906 |
limit = quota['limit']
|
907 |
usage = quota['usage']
|
908 |
if usage + diff > limit:
|
909 |
return False, limit |
910 |
return True, None |
911 |
|
912 |
|
913 |
def qh_release_pending_app(user, locked=False): |
914 |
if not locked: |
915 |
user = AstakosUser.forupdate.get_for_update(id=user.id) |
916 |
register_pending_apps(user, -1)
|