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