root / snf-astakos-app / astakos / im / functions.py @ e872c133
History | View | Annotate | Download (32.9 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.db.models import Q |
42 |
|
43 |
from synnefo_branding.utils import render_to_string |
44 |
|
45 |
from synnefo.lib import join_urls |
46 |
from astakos.im.models import AstakosUser, Invitation, ProjectMembership, \ |
47 |
ProjectApplication, Project, new_chain, Resource, ProjectLock |
48 |
from astakos.im.quotas import qh_sync_user, get_pending_app_quota, \ |
49 |
register_pending_apps, qh_sync_project, qh_sync_locked_users, \ |
50 |
get_users_for_update, members_to_sync |
51 |
from astakos.im.project_notif import membership_change_notify, \ |
52 |
membership_enroll_notify, membership_request_notify, \ |
53 |
membership_leave_request_notify, application_submit_notify, \ |
54 |
application_approve_notify, application_deny_notify, \ |
55 |
project_termination_notify, project_suspension_notify, \ |
56 |
project_unsuspension_notify, project_reinstatement_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 |
|
248 |
class ProjectError(Exception): |
249 |
pass
|
250 |
|
251 |
|
252 |
class ProjectNotFound(ProjectError): |
253 |
pass
|
254 |
|
255 |
|
256 |
class ProjectForbidden(ProjectError): |
257 |
pass
|
258 |
|
259 |
|
260 |
class ProjectBadRequest(ProjectError): |
261 |
pass
|
262 |
|
263 |
|
264 |
class ProjectConflict(ProjectError): |
265 |
pass
|
266 |
|
267 |
AUTO_ACCEPT_POLICY = 1
|
268 |
MODERATED_POLICY = 2
|
269 |
CLOSED_POLICY = 3
|
270 |
|
271 |
POLICIES = [AUTO_ACCEPT_POLICY, MODERATED_POLICY, CLOSED_POLICY] |
272 |
|
273 |
|
274 |
def get_related_project_id(application_id): |
275 |
try:
|
276 |
app = ProjectApplication.objects.get(id=application_id) |
277 |
return app.chain_id
|
278 |
except ProjectApplication.DoesNotExist:
|
279 |
return None |
280 |
|
281 |
|
282 |
def get_project_by_id(project_id): |
283 |
try:
|
284 |
return Project.objects.get(id=project_id)
|
285 |
except Project.DoesNotExist:
|
286 |
m = _(astakos_messages.UNKNOWN_PROJECT_ID) % project_id |
287 |
raise ProjectNotFound(m)
|
288 |
|
289 |
|
290 |
def get_project_for_update(project_id): |
291 |
try:
|
292 |
return Project.objects.get_for_update(id=project_id)
|
293 |
except Project.DoesNotExist:
|
294 |
m = _(astakos_messages.UNKNOWN_PROJECT_ID) % project_id |
295 |
raise ProjectNotFound(m)
|
296 |
|
297 |
|
298 |
def get_project_of_application_for_update(app_id): |
299 |
app = get_application(app_id) |
300 |
return get_project_for_update(app.chain_id)
|
301 |
|
302 |
|
303 |
def get_project_lock(): |
304 |
ProjectLock.objects.get_for_update(pk=1)
|
305 |
|
306 |
|
307 |
def get_application(application_id): |
308 |
try:
|
309 |
return ProjectApplication.objects.get(id=application_id)
|
310 |
except ProjectApplication.DoesNotExist:
|
311 |
m = _(astakos_messages.UNKNOWN_PROJECT_APPLICATION_ID) % application_id |
312 |
raise ProjectNotFound(m)
|
313 |
|
314 |
|
315 |
def get_project_of_membership_for_update(memb_id): |
316 |
m = get_membership_by_id(memb_id) |
317 |
return get_project_for_update(m.project_id)
|
318 |
|
319 |
|
320 |
def get_user_by_id(user_id): |
321 |
try:
|
322 |
return AstakosUser.objects.get(id=user_id)
|
323 |
except AstakosUser.DoesNotExist:
|
324 |
m = _(astakos_messages.UNKNOWN_USER_ID) % user_id |
325 |
raise ProjectNotFound(m)
|
326 |
|
327 |
|
328 |
def get_user_by_uuid(uuid): |
329 |
try:
|
330 |
return AstakosUser.objects.get(uuid=uuid)
|
331 |
except AstakosUser.DoesNotExist:
|
332 |
m = _(astakos_messages.UNKNOWN_USER_ID) % uuid |
333 |
raise ProjectNotFound(m)
|
334 |
|
335 |
|
336 |
def get_membership(project_id, user_id): |
337 |
try:
|
338 |
objs = ProjectMembership.objects.select_related('project', 'person') |
339 |
return objs.get(project__id=project_id, person__id=user_id)
|
340 |
except ProjectMembership.DoesNotExist:
|
341 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
342 |
raise ProjectNotFound(m)
|
343 |
|
344 |
|
345 |
def get_membership_by_id(memb_id): |
346 |
try:
|
347 |
objs = ProjectMembership.objects.select_related('project', 'person') |
348 |
return objs.get(id=memb_id)
|
349 |
except ProjectMembership.DoesNotExist:
|
350 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
351 |
raise ProjectNotFound(m)
|
352 |
|
353 |
|
354 |
ALLOWED_CHECKS = [ |
355 |
(lambda u, a: not u or u.is_project_admin()), |
356 |
(lambda u, a: a.owner == u),
|
357 |
(lambda u, a: a.applicant == u),
|
358 |
(lambda u, a: a.chain.overall_state() == Project.O_ACTIVE
|
359 |
or bool(a.chain.projectmembership_set.any_accepted().filter(person=u))), |
360 |
] |
361 |
|
362 |
ADMIN_LEVEL = 0
|
363 |
OWNER_LEVEL = 1
|
364 |
APPLICANT_LEVEL = 2
|
365 |
ANY_LEVEL = 3
|
366 |
|
367 |
|
368 |
def _check_yield(b, silent=False): |
369 |
if b:
|
370 |
return True |
371 |
|
372 |
if silent:
|
373 |
return False |
374 |
|
375 |
m = _(astakos_messages.NOT_ALLOWED) |
376 |
raise ProjectForbidden(m)
|
377 |
|
378 |
|
379 |
def membership_check_allowed(membership, request_user, |
380 |
level=OWNER_LEVEL, silent=False):
|
381 |
r = project_check_allowed( |
382 |
membership.project, request_user, level, silent=True)
|
383 |
|
384 |
return _check_yield(r or membership.person == request_user, silent) |
385 |
|
386 |
|
387 |
def project_check_allowed(project, request_user, |
388 |
level=OWNER_LEVEL, silent=False):
|
389 |
return app_check_allowed(project.application, request_user, level, silent)
|
390 |
|
391 |
|
392 |
def app_check_allowed(application, request_user, |
393 |
level=OWNER_LEVEL, silent=False):
|
394 |
checks = (f(request_user, application) for f in ALLOWED_CHECKS[:level+1]) |
395 |
return _check_yield(any(checks), silent) |
396 |
|
397 |
|
398 |
def checkAlive(project): |
399 |
if not project.is_alive: |
400 |
m = _(astakos_messages.NOT_ALIVE_PROJECT) % project.id |
401 |
raise ProjectConflict(m)
|
402 |
|
403 |
|
404 |
def accept_membership_project_checks(project, request_user): |
405 |
project_check_allowed(project, request_user) |
406 |
checkAlive(project) |
407 |
|
408 |
join_policy = project.application.member_join_policy |
409 |
if join_policy == CLOSED_POLICY:
|
410 |
m = _(astakos_messages.MEMBER_JOIN_POLICY_CLOSED) |
411 |
raise ProjectConflict(m)
|
412 |
|
413 |
if project.violates_members_limit(adding=1): |
414 |
m = _(astakos_messages.MEMBER_NUMBER_LIMIT_REACHED) |
415 |
raise ProjectConflict(m)
|
416 |
|
417 |
|
418 |
def accept_membership_checks(membership, request_user): |
419 |
if not membership.check_action("accept"): |
420 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
421 |
raise ProjectConflict(m)
|
422 |
|
423 |
project = membership.project |
424 |
accept_membership_project_checks(project, request_user) |
425 |
|
426 |
|
427 |
def accept_membership(memb_id, request_user=None, reason=None): |
428 |
project = get_project_of_membership_for_update(memb_id) |
429 |
membership = get_membership_by_id(memb_id) |
430 |
accept_membership_checks(membership, request_user) |
431 |
user = membership.person |
432 |
membership.perform_action("accept", actor=request_user, reason=reason)
|
433 |
qh_sync_user(user) |
434 |
logger.info("User %s has been accepted in %s." %
|
435 |
(user.log_display, project)) |
436 |
|
437 |
membership_change_notify(project, user, 'accepted')
|
438 |
return membership
|
439 |
|
440 |
|
441 |
def reject_membership_checks(membership, request_user): |
442 |
if not membership.check_action("reject"): |
443 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
444 |
raise ProjectConflict(m)
|
445 |
|
446 |
project = membership.project |
447 |
project_check_allowed(project, request_user) |
448 |
checkAlive(project) |
449 |
|
450 |
|
451 |
def reject_membership(memb_id, request_user=None, reason=None): |
452 |
project = get_project_of_membership_for_update(memb_id) |
453 |
membership = get_membership_by_id(memb_id) |
454 |
reject_membership_checks(membership, request_user) |
455 |
user = membership.person |
456 |
membership.perform_action("reject", actor=request_user, reason=reason)
|
457 |
logger.info("Request of user %s for %s has been rejected." %
|
458 |
(user.log_display, project)) |
459 |
|
460 |
membership_change_notify(project, user, 'rejected')
|
461 |
return membership
|
462 |
|
463 |
|
464 |
def cancel_membership_checks(membership, request_user): |
465 |
if not membership.check_action("cancel"): |
466 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
467 |
raise ProjectConflict(m)
|
468 |
|
469 |
membership_check_allowed(membership, request_user, level=ADMIN_LEVEL) |
470 |
project = membership.project |
471 |
checkAlive(project) |
472 |
|
473 |
|
474 |
def cancel_membership(memb_id, request_user, reason=None): |
475 |
project = get_project_of_membership_for_update(memb_id) |
476 |
membership = get_membership_by_id(memb_id) |
477 |
cancel_membership_checks(membership, request_user) |
478 |
membership.perform_action("cancel", actor=request_user, reason=reason)
|
479 |
logger.info("Request of user %s for %s has been cancelled." %
|
480 |
(membership.person.log_display, project)) |
481 |
|
482 |
|
483 |
def remove_membership_checks(membership, request_user=None): |
484 |
if not membership.check_action("remove"): |
485 |
m = _(astakos_messages.NOT_ACCEPTED_MEMBERSHIP) |
486 |
raise ProjectConflict(m)
|
487 |
|
488 |
project = membership.project |
489 |
project_check_allowed(project, request_user) |
490 |
checkAlive(project) |
491 |
|
492 |
leave_policy = project.application.member_leave_policy |
493 |
if leave_policy == CLOSED_POLICY:
|
494 |
m = _(astakos_messages.MEMBER_LEAVE_POLICY_CLOSED) |
495 |
raise ProjectConflict(m)
|
496 |
|
497 |
|
498 |
def remove_membership(memb_id, request_user=None, reason=None): |
499 |
project = get_project_of_membership_for_update(memb_id) |
500 |
membership = get_membership_by_id(memb_id) |
501 |
remove_membership_checks(membership, request_user) |
502 |
user = membership.person |
503 |
membership.perform_action("remove", actor=request_user, reason=reason)
|
504 |
qh_sync_user(user) |
505 |
logger.info("User %s has been removed from %s." %
|
506 |
(user.log_display, project)) |
507 |
|
508 |
membership_change_notify(project, user, 'removed')
|
509 |
return membership
|
510 |
|
511 |
|
512 |
def enroll_member(project_id, user, request_user=None, reason=None): |
513 |
project = get_project_for_update(project_id) |
514 |
try:
|
515 |
project = get_project_for_update(project_id) |
516 |
except ProjectNotFound as e: |
517 |
raise ProjectConflict(e.message)
|
518 |
accept_membership_project_checks(project, request_user) |
519 |
|
520 |
try:
|
521 |
membership = get_membership(project_id, user.id) |
522 |
if not membership.check_action("enroll"): |
523 |
m = _(astakos_messages.MEMBERSHIP_ACCEPTED) |
524 |
raise ProjectConflict(m)
|
525 |
membership.perform_action("join", actor=request_user, reason=reason)
|
526 |
except ProjectNotFound:
|
527 |
membership = new_membership(project, user, actor=request_user) |
528 |
|
529 |
membership.perform_action("accept", actor=request_user, reason=reason)
|
530 |
qh_sync_user(user) |
531 |
logger.info("User %s has been enrolled in %s." %
|
532 |
(membership.person.log_display, project)) |
533 |
|
534 |
membership_enroll_notify(project, membership.person) |
535 |
return membership
|
536 |
|
537 |
|
538 |
def leave_project_checks(membership, request_user): |
539 |
if not membership.check_action("leave"): |
540 |
m = _(astakos_messages.NOT_ACCEPTED_MEMBERSHIP) |
541 |
raise ProjectConflict(m)
|
542 |
|
543 |
membership_check_allowed(membership, request_user, level=ADMIN_LEVEL) |
544 |
project = membership.project |
545 |
checkAlive(project) |
546 |
|
547 |
leave_policy = project.application.member_leave_policy |
548 |
if leave_policy == CLOSED_POLICY:
|
549 |
m = _(astakos_messages.MEMBER_LEAVE_POLICY_CLOSED) |
550 |
raise ProjectConflict(m)
|
551 |
|
552 |
|
553 |
def can_leave_request(project, user): |
554 |
m = user.get_membership(project) |
555 |
if m is None: |
556 |
return False |
557 |
try:
|
558 |
leave_project_checks(m, user) |
559 |
except ProjectError:
|
560 |
return False |
561 |
return True |
562 |
|
563 |
|
564 |
def leave_project(memb_id, request_user, reason=None): |
565 |
project = get_project_of_membership_for_update(memb_id) |
566 |
membership = get_membership_by_id(memb_id) |
567 |
leave_project_checks(membership, request_user) |
568 |
|
569 |
auto_accepted = False
|
570 |
leave_policy = project.application.member_leave_policy |
571 |
if leave_policy == AUTO_ACCEPT_POLICY:
|
572 |
membership.perform_action("remove", actor=request_user, reason=reason)
|
573 |
qh_sync_user(request_user) |
574 |
logger.info("User %s has left %s." %
|
575 |
(request_user.log_display, project)) |
576 |
auto_accepted = True
|
577 |
else:
|
578 |
membership.perform_action("leave_request", actor=request_user,
|
579 |
reason=reason) |
580 |
logger.info("User %s requested to leave %s." %
|
581 |
(request_user.log_display, project)) |
582 |
membership_leave_request_notify(project, membership.person) |
583 |
return auto_accepted
|
584 |
|
585 |
|
586 |
def join_project_checks(project): |
587 |
checkAlive(project) |
588 |
|
589 |
join_policy = project.application.member_join_policy |
590 |
if join_policy == CLOSED_POLICY:
|
591 |
m = _(astakos_messages.MEMBER_JOIN_POLICY_CLOSED) |
592 |
raise ProjectConflict(m)
|
593 |
|
594 |
|
595 |
def can_join_request(project, user): |
596 |
try:
|
597 |
join_project_checks(project) |
598 |
except ProjectError:
|
599 |
return False |
600 |
|
601 |
m = user.get_membership(project) |
602 |
if not m: |
603 |
return True |
604 |
return m.check_action("join") |
605 |
|
606 |
|
607 |
def new_membership(project, user, actor=None, reason=None): |
608 |
m = ProjectMembership.objects.create(project=project, person=user) |
609 |
m._log_create(None, ProjectMembership.REQUESTED, actor=actor,
|
610 |
reason=reason) |
611 |
return m
|
612 |
|
613 |
|
614 |
def join_project(project_id, request_user, reason=None): |
615 |
project = get_project_for_update(project_id) |
616 |
join_project_checks(project) |
617 |
|
618 |
try:
|
619 |
membership = get_membership(project.id, request_user.id) |
620 |
if not membership.check_action("join"): |
621 |
msg = _(astakos_messages.MEMBERSHIP_ASSOCIATED) |
622 |
raise ProjectConflict(msg)
|
623 |
membership.perform_action("join", actor=request_user, reason=reason)
|
624 |
except ProjectNotFound:
|
625 |
membership = new_membership(project, request_user, actor=request_user, |
626 |
reason=reason) |
627 |
|
628 |
join_policy = project.application.member_join_policy |
629 |
if (join_policy == AUTO_ACCEPT_POLICY and ( |
630 |
not project.violates_members_limit(adding=1))): |
631 |
membership.perform_action("accept", actor=request_user, reason=reason)
|
632 |
qh_sync_user(request_user) |
633 |
logger.info("User %s joined %s." %
|
634 |
(request_user.log_display, project)) |
635 |
else:
|
636 |
membership_request_notify(project, membership.person) |
637 |
logger.info("User %s requested to join %s." %
|
638 |
(request_user.log_display, project)) |
639 |
return membership
|
640 |
|
641 |
|
642 |
MEMBERSHIP_ACTION_CHECKS = { |
643 |
"leave": leave_project_checks,
|
644 |
"cancel": cancel_membership_checks,
|
645 |
"accept": accept_membership_checks,
|
646 |
"reject": reject_membership_checks,
|
647 |
"remove": remove_membership_checks,
|
648 |
} |
649 |
|
650 |
|
651 |
def membership_allowed_actions(membership, request_user): |
652 |
allowed = [] |
653 |
for action, check in MEMBERSHIP_ACTION_CHECKS.iteritems(): |
654 |
try:
|
655 |
check(membership, request_user) |
656 |
allowed.append(action) |
657 |
except ProjectError:
|
658 |
pass
|
659 |
return allowed
|
660 |
|
661 |
|
662 |
def submit_application(owner=None, |
663 |
name=None,
|
664 |
project_id=None,
|
665 |
homepage=None,
|
666 |
description=None,
|
667 |
start_date=None,
|
668 |
end_date=None,
|
669 |
member_join_policy=None,
|
670 |
member_leave_policy=None,
|
671 |
limit_on_members_number=None,
|
672 |
comments=None,
|
673 |
resources=None,
|
674 |
request_user=None):
|
675 |
|
676 |
project = None
|
677 |
if project_id is not None: |
678 |
project = get_project_for_update(project_id) |
679 |
project_check_allowed(project, request_user, level=APPLICANT_LEVEL) |
680 |
|
681 |
policies = validate_resource_policies(resources) |
682 |
|
683 |
force = request_user.is_project_admin() |
684 |
ok, limit = qh_add_pending_app(owner, project, force) |
685 |
if not ok: |
686 |
m = _(astakos_messages.REACHED_PENDING_APPLICATION_LIMIT) % limit |
687 |
raise ProjectConflict(m)
|
688 |
|
689 |
application = ProjectApplication( |
690 |
applicant=request_user, |
691 |
owner=owner, |
692 |
name=name, |
693 |
homepage=homepage, |
694 |
description=description, |
695 |
start_date=start_date, |
696 |
end_date=end_date, |
697 |
member_join_policy=member_join_policy, |
698 |
member_leave_policy=member_leave_policy, |
699 |
limit_on_members_number=limit_on_members_number, |
700 |
comments=comments) |
701 |
|
702 |
if project is None: |
703 |
chain = new_chain() |
704 |
application.chain_id = chain.chain |
705 |
application.save() |
706 |
Project.objects.create(id=chain.chain, application=application) |
707 |
else:
|
708 |
application.chain = project |
709 |
application.save() |
710 |
if project.application.state != ProjectApplication.APPROVED:
|
711 |
project.application = application |
712 |
project.save() |
713 |
|
714 |
pending = ProjectApplication.objects.filter( |
715 |
chain=project, |
716 |
state=ProjectApplication.PENDING).exclude(id=application.id) |
717 |
for app in pending: |
718 |
app.state = ProjectApplication.REPLACED |
719 |
app.save() |
720 |
|
721 |
if policies is not None: |
722 |
set_resource_policies(application, policies) |
723 |
logger.info("User %s submitted %s." %
|
724 |
(request_user.log_display, application.log_display)) |
725 |
application_submit_notify(application) |
726 |
return application
|
727 |
|
728 |
|
729 |
def validate_resource_policies(policies): |
730 |
if not isinstance(policies, dict): |
731 |
raise ProjectBadRequest("Malformed resource policies") |
732 |
|
733 |
resource_names = policies.keys() |
734 |
resources = Resource.objects.filter(name__in=resource_names) |
735 |
resource_d = {} |
736 |
for resource in resources: |
737 |
resource_d[resource.name] = resource |
738 |
|
739 |
found = resource_d.keys() |
740 |
nonex = [name for name in resource_names if name not in found] |
741 |
if nonex:
|
742 |
raise ProjectBadRequest("Malformed resource policies") |
743 |
|
744 |
pols = [] |
745 |
for resource_name, specs in policies.iteritems(): |
746 |
p_capacity = specs.get("project_capacity")
|
747 |
m_capacity = specs.get("member_capacity")
|
748 |
|
749 |
if p_capacity is not None and not isinstance(p_capacity, (int, long)): |
750 |
raise ProjectBadRequest("Malformed resource policies") |
751 |
if not isinstance(m_capacity, (int, long)): |
752 |
raise ProjectBadRequest("Malformed resource policies") |
753 |
pols.append((resource_d[resource_name], m_capacity, p_capacity)) |
754 |
return pols
|
755 |
|
756 |
|
757 |
def set_resource_policies(application, policies): |
758 |
for resource, m_capacity, p_capacity in policies: |
759 |
g = application.projectresourcegrant_set |
760 |
g.create(resource=resource, |
761 |
member_capacity=m_capacity, |
762 |
project_capacity=p_capacity) |
763 |
|
764 |
|
765 |
def cancel_application(application_id, request_user=None, reason=""): |
766 |
get_project_of_application_for_update(application_id) |
767 |
application = get_application(application_id) |
768 |
app_check_allowed(application, request_user, level=APPLICANT_LEVEL) |
769 |
|
770 |
if not application.can_cancel(): |
771 |
m = _(astakos_messages.APPLICATION_CANNOT_CANCEL % |
772 |
(application.id, application.state_display())) |
773 |
raise ProjectConflict(m)
|
774 |
|
775 |
qh_release_pending_app(application.owner) |
776 |
|
777 |
application.cancel(actor=request_user, reason=reason) |
778 |
logger.info("%s has been cancelled." % (application.log_display))
|
779 |
|
780 |
|
781 |
def dismiss_application(application_id, request_user=None, reason=""): |
782 |
get_project_of_application_for_update(application_id) |
783 |
application = get_application(application_id) |
784 |
app_check_allowed(application, request_user, level=APPLICANT_LEVEL) |
785 |
|
786 |
if not application.can_dismiss(): |
787 |
m = _(astakos_messages.APPLICATION_CANNOT_DISMISS % |
788 |
(application.id, application.state_display())) |
789 |
raise ProjectConflict(m)
|
790 |
|
791 |
application.dismiss(actor=request_user, reason=reason) |
792 |
logger.info("%s has been dismissed." % (application.log_display))
|
793 |
|
794 |
|
795 |
def deny_application(application_id, request_user=None, reason=""): |
796 |
get_project_of_application_for_update(application_id) |
797 |
application = get_application(application_id) |
798 |
|
799 |
app_check_allowed(application, request_user, level=ADMIN_LEVEL) |
800 |
|
801 |
if not application.can_deny(): |
802 |
m = _(astakos_messages.APPLICATION_CANNOT_DENY % |
803 |
(application.id, application.state_display())) |
804 |
raise ProjectConflict(m)
|
805 |
|
806 |
qh_release_pending_app(application.owner) |
807 |
|
808 |
application.deny(actor=request_user, reason=reason) |
809 |
logger.info("%s has been denied with reason \"%s\"." %
|
810 |
(application.log_display, reason)) |
811 |
application_deny_notify(application) |
812 |
|
813 |
|
814 |
def check_conflicting_projects(application): |
815 |
project = application.chain |
816 |
new_project_name = application.name |
817 |
try:
|
818 |
q = Q(name=new_project_name) & ~Q(state=Project.TERMINATED) |
819 |
conflicting_project = Project.objects.get(q) |
820 |
if (conflicting_project != project):
|
821 |
m = (_("cannot approve: project with name '%s' "
|
822 |
"already exists (id: %s)") %
|
823 |
(new_project_name, conflicting_project.id)) |
824 |
raise ProjectConflict(m) # invalid argument |
825 |
except Project.DoesNotExist:
|
826 |
pass
|
827 |
|
828 |
|
829 |
def approve_application(app_id, request_user=None, reason=""): |
830 |
get_project_lock() |
831 |
project = get_project_of_application_for_update(app_id) |
832 |
application = get_application(app_id) |
833 |
|
834 |
app_check_allowed(application, request_user, level=ADMIN_LEVEL) |
835 |
|
836 |
if not application.can_approve(): |
837 |
m = _(astakos_messages.APPLICATION_CANNOT_APPROVE % |
838 |
(application.id, application.state_display())) |
839 |
raise ProjectConflict(m)
|
840 |
|
841 |
check_conflicting_projects(application) |
842 |
|
843 |
# Pre-lock members and owner together in order to impose an ordering
|
844 |
# on locking users
|
845 |
members = members_to_sync(project) |
846 |
uids_to_sync = [member.id for member in members] |
847 |
owner = application.owner |
848 |
uids_to_sync.append(owner.id) |
849 |
get_users_for_update(uids_to_sync) |
850 |
|
851 |
qh_release_pending_app(owner, locked=True)
|
852 |
application.approve(actor=request_user, reason=reason) |
853 |
project.application = application |
854 |
project.name = application.name |
855 |
project.save() |
856 |
if project.is_deactivated():
|
857 |
project.resume(actor=request_user, reason="APPROVE")
|
858 |
qh_sync_locked_users(members) |
859 |
logger.info("%s has been approved." % (application.log_display))
|
860 |
application_approve_notify(application) |
861 |
|
862 |
|
863 |
def check_expiration(execute=False): |
864 |
objects = Project.objects |
865 |
expired = objects.expired_projects() |
866 |
if execute:
|
867 |
for project in expired: |
868 |
terminate(project.pk) |
869 |
|
870 |
return [project.expiration_info() for project in expired] |
871 |
|
872 |
|
873 |
def terminate(project_id, request_user=None, reason=None): |
874 |
project = get_project_for_update(project_id) |
875 |
project_check_allowed(project, request_user, level=ADMIN_LEVEL) |
876 |
checkAlive(project) |
877 |
|
878 |
project.terminate(actor=request_user, reason=reason) |
879 |
qh_sync_project(project) |
880 |
logger.info("%s has been terminated." % (project))
|
881 |
|
882 |
project_termination_notify(project) |
883 |
|
884 |
|
885 |
def suspend(project_id, request_user=None, reason=None): |
886 |
project = get_project_for_update(project_id) |
887 |
project_check_allowed(project, request_user, level=ADMIN_LEVEL) |
888 |
checkAlive(project) |
889 |
|
890 |
project.suspend(actor=request_user, reason=reason) |
891 |
qh_sync_project(project) |
892 |
logger.info("%s has been suspended." % (project))
|
893 |
|
894 |
project_suspension_notify(project) |
895 |
|
896 |
|
897 |
def unsuspend(project_id, request_user=None, reason=None): |
898 |
project = get_project_for_update(project_id) |
899 |
project_check_allowed(project, request_user, level=ADMIN_LEVEL) |
900 |
|
901 |
if not project.is_suspended: |
902 |
m = _(astakos_messages.NOT_SUSPENDED_PROJECT) % project.id |
903 |
raise ProjectConflict(m)
|
904 |
|
905 |
project.resume(actor=request_user, reason=reason) |
906 |
qh_sync_project(project) |
907 |
logger.info("%s has been unsuspended." % (project))
|
908 |
project_unsuspension_notify(project) |
909 |
|
910 |
|
911 |
def reinstate(project_id, request_user=None, reason=None): |
912 |
get_project_lock() |
913 |
project = get_project_for_update(project_id) |
914 |
project_check_allowed(project, request_user, level=ADMIN_LEVEL) |
915 |
|
916 |
if not project.is_terminated: |
917 |
m = _(astakos_messages.NOT_TERMINATED_PROJECT) % project.id |
918 |
raise ProjectConflict(m)
|
919 |
|
920 |
check_conflicting_projects(project.application) |
921 |
project.resume(actor=request_user, reason=reason) |
922 |
qh_sync_project(project) |
923 |
logger.info("%s has been reinstated" % (project))
|
924 |
project_reinstatement_notify(project) |
925 |
|
926 |
|
927 |
def _partition_by(f, l): |
928 |
d = {} |
929 |
for x in l: |
930 |
group = f(x) |
931 |
group_l = d.get(group, []) |
932 |
group_l.append(x) |
933 |
d[group] = group_l |
934 |
return d
|
935 |
|
936 |
|
937 |
def count_pending_app(users): |
938 |
users = list(users)
|
939 |
apps = ProjectApplication.objects.filter(state=ProjectApplication.PENDING, |
940 |
owner__in=users) |
941 |
apps_d = _partition_by(lambda a: a.owner.uuid, apps)
|
942 |
|
943 |
usage = {} |
944 |
for user in users: |
945 |
uuid = user.uuid |
946 |
usage[uuid] = len(apps_d.get(uuid, []))
|
947 |
return usage
|
948 |
|
949 |
|
950 |
def get_pending_app_diff(user, project): |
951 |
if project is None: |
952 |
diff = 1
|
953 |
else:
|
954 |
objs = ProjectApplication.objects |
955 |
q = objs.filter(chain=project, state=ProjectApplication.PENDING) |
956 |
count = q.count() |
957 |
diff = 1 - count
|
958 |
return diff
|
959 |
|
960 |
|
961 |
def qh_add_pending_app(user, project=None, force=False): |
962 |
user = AstakosUser.forupdate.get_for_update(id=user.id) |
963 |
diff = get_pending_app_diff(user, project) |
964 |
return register_pending_apps(user, diff, force)
|
965 |
|
966 |
|
967 |
def check_pending_app_quota(user, project=None): |
968 |
diff = get_pending_app_diff(user, project) |
969 |
quota = get_pending_app_quota(user) |
970 |
limit = quota['limit']
|
971 |
usage = quota['usage']
|
972 |
if usage + diff > limit:
|
973 |
return False, limit |
974 |
return True, None |
975 |
|
976 |
|
977 |
def qh_release_pending_app(user, locked=False): |
978 |
if not locked: |
979 |
user = AstakosUser.forupdate.get_for_update(id=user.id) |
980 |
register_pending_apps(user, -1)
|