root / snf-astakos-app / astakos / im / functions.py @ a75dbd7b
History | View | Annotate | Download (25.8 kB)
1 |
# Copyright 2011 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
import logging |
35 |
import socket |
36 |
|
37 |
from django.utils.translation import ugettext as _ |
38 |
from django.template.loader import render_to_string |
39 |
from django.core.mail import send_mail, get_connection |
40 |
from django.core.urlresolvers import reverse |
41 |
from django.template import Context, loader |
42 |
from django.contrib.auth import ( |
43 |
login as auth_login,
|
44 |
logout as auth_logout)
|
45 |
from django.conf import settings |
46 |
from django.contrib.auth.models import AnonymousUser |
47 |
from django.core.exceptions import PermissionDenied |
48 |
from django.db import IntegrityError |
49 |
from django.http import Http404 |
50 |
|
51 |
from urllib import quote |
52 |
from urlparse import urljoin |
53 |
from smtplib import SMTPException |
54 |
from datetime import datetime |
55 |
from functools import wraps |
56 |
|
57 |
from astakos.im.settings import ( |
58 |
DEFAULT_CONTACT_EMAIL, SITENAME, BASEURL, LOGGING_LEVEL, |
59 |
VERIFICATION_EMAIL_SUBJECT, ACCOUNT_CREATION_SUBJECT, |
60 |
GROUP_CREATION_SUBJECT, HELPDESK_NOTIFICATION_EMAIL_SUBJECT, |
61 |
INVITATION_EMAIL_SUBJECT, GREETING_EMAIL_SUBJECT, FEEDBACK_EMAIL_SUBJECT, |
62 |
EMAIL_CHANGE_EMAIL_SUBJECT, |
63 |
PROJECT_CREATION_SUBJECT, PROJECT_APPROVED_SUBJECT, |
64 |
PROJECT_TERMINATION_SUBJECT, PROJECT_SUSPENSION_SUBJECT, |
65 |
PROJECT_MEMBERSHIP_CHANGE_SUBJECT, |
66 |
PROJECT_MEMBER_JOIN_POLICIES, PROJECT_MEMBER_LEAVE_POLICIES) |
67 |
from astakos.im.notifications import build_notification, NotificationError |
68 |
from astakos.im.models import ( |
69 |
AstakosUser, ProjectMembership, ProjectApplication, Project, |
70 |
PendingMembershipError, get_resource_names, new_chain) |
71 |
from astakos.im.project_notif import ( |
72 |
membership_change_notify, |
73 |
application_submit_notify, application_approve_notify, |
74 |
application_deny_notify, |
75 |
project_termination_notify, project_suspension_notify) |
76 |
from astakos.im.endpoints.qh import qh_register_user_with_quotas, qh_get_quota |
77 |
|
78 |
import astakos.im.messages as astakos_messages |
79 |
|
80 |
logger = logging.getLogger(__name__) |
81 |
|
82 |
|
83 |
def logged(func, msg): |
84 |
@wraps(func)
|
85 |
def with_logging(*args, **kwargs): |
86 |
email = ''
|
87 |
user = None
|
88 |
try:
|
89 |
request = args[0]
|
90 |
email = request.user.email |
91 |
except (KeyError, AttributeError), e: |
92 |
email = ''
|
93 |
r = func(*args, **kwargs) |
94 |
if LOGGING_LEVEL:
|
95 |
logger.log(LOGGING_LEVEL, msg % email) |
96 |
return r
|
97 |
return with_logging
|
98 |
|
99 |
|
100 |
def login(request, user): |
101 |
auth_login(request, user) |
102 |
from astakos.im.models import SessionCatalog |
103 |
SessionCatalog( |
104 |
session_key=request.session.session_key, |
105 |
user=user |
106 |
).save() |
107 |
|
108 |
login = logged(login, '%s logged in.')
|
109 |
logout = logged(auth_logout, '%s logged out.')
|
110 |
|
111 |
|
112 |
def send_verification(user, template_name='im/activation_email.txt'): |
113 |
"""
|
114 |
Send email to user to verify his/her email and activate his/her account.
|
115 |
|
116 |
Raises SendVerificationError
|
117 |
"""
|
118 |
url = '%s?auth=%s&next=%s' % (urljoin(BASEURL, reverse('activate')), |
119 |
quote(user.auth_token), |
120 |
quote(urljoin(BASEURL, reverse('index'))))
|
121 |
message = render_to_string(template_name, { |
122 |
'user': user,
|
123 |
'url': url,
|
124 |
'baseurl': BASEURL,
|
125 |
'site_name': SITENAME,
|
126 |
'support': DEFAULT_CONTACT_EMAIL})
|
127 |
sender = settings.SERVER_EMAIL |
128 |
try:
|
129 |
send_mail(_(VERIFICATION_EMAIL_SUBJECT), message, sender, [user.email], |
130 |
connection=get_connection()) |
131 |
|
132 |
except (SMTPException, socket.error) as e: |
133 |
logger.exception(e) |
134 |
raise SendVerificationError()
|
135 |
else:
|
136 |
msg = 'Sent activation %s' % user.email
|
137 |
logger.log(LOGGING_LEVEL, msg) |
138 |
|
139 |
|
140 |
def send_activation(user, template_name='im/activation_email.txt'): |
141 |
send_verification(user, template_name) |
142 |
user.activation_sent = datetime.now() |
143 |
user.save() |
144 |
|
145 |
|
146 |
def _send_admin_notification(template_name, |
147 |
dictionary=None,
|
148 |
subject='alpha2 testing notification',):
|
149 |
"""
|
150 |
Send notification email to settings.ADMINS.
|
151 |
|
152 |
Raises SendNotificationError
|
153 |
"""
|
154 |
if not settings.ADMINS: |
155 |
return
|
156 |
dictionary = dictionary or {}
|
157 |
message = render_to_string(template_name, dictionary) |
158 |
sender = settings.SERVER_EMAIL |
159 |
try:
|
160 |
send_mail(subject, message, sender, [i[1] for i in settings.ADMINS], |
161 |
connection=get_connection()) |
162 |
except (SMTPException, socket.error) as e: |
163 |
logger.exception(e) |
164 |
raise SendNotificationError()
|
165 |
else:
|
166 |
msg = 'Sent admin notification for user %s' % dictionary.get('email', |
167 |
None)
|
168 |
logger.log(LOGGING_LEVEL, msg) |
169 |
|
170 |
|
171 |
def send_account_creation_notification(template_name, dictionary=None): |
172 |
user = dictionary.get('user', AnonymousUser())
|
173 |
subject = _(ACCOUNT_CREATION_SUBJECT) % {'user':user.get('email', '')} |
174 |
return _send_admin_notification(template_name, dictionary, subject=subject)
|
175 |
|
176 |
|
177 |
def send_helpdesk_notification(user, template_name='im/helpdesk_notification.txt'): |
178 |
"""
|
179 |
Send email to DEFAULT_CONTACT_EMAIL to notify for a new user activation.
|
180 |
|
181 |
Raises SendNotificationError
|
182 |
"""
|
183 |
if not DEFAULT_CONTACT_EMAIL: |
184 |
return
|
185 |
message = render_to_string( |
186 |
template_name, |
187 |
{'user': user}
|
188 |
) |
189 |
sender = settings.SERVER_EMAIL |
190 |
try:
|
191 |
send_mail(_(HELPDESK_NOTIFICATION_EMAIL_SUBJECT) % {'user': user.email},
|
192 |
message, sender, [DEFAULT_CONTACT_EMAIL], |
193 |
connection=get_connection()) |
194 |
except (SMTPException, socket.error) as e: |
195 |
logger.exception(e) |
196 |
raise SendNotificationError()
|
197 |
else:
|
198 |
msg = 'Sent helpdesk admin notification for %s' % user.email
|
199 |
logger.log(LOGGING_LEVEL, msg) |
200 |
|
201 |
|
202 |
def send_invitation(invitation, template_name='im/invitation.txt'): |
203 |
"""
|
204 |
Send invitation email.
|
205 |
|
206 |
Raises SendInvitationError
|
207 |
"""
|
208 |
subject = _(INVITATION_EMAIL_SUBJECT) |
209 |
url = '%s?code=%d' % (urljoin(BASEURL, reverse('index')), invitation.code) |
210 |
message = render_to_string(template_name, { |
211 |
'invitation': invitation,
|
212 |
'url': url,
|
213 |
'baseurl': BASEURL,
|
214 |
'site_name': SITENAME,
|
215 |
'support': DEFAULT_CONTACT_EMAIL})
|
216 |
sender = settings.SERVER_EMAIL |
217 |
try:
|
218 |
send_mail(subject, message, sender, [invitation.username], |
219 |
connection=get_connection()) |
220 |
except (SMTPException, socket.error) as e: |
221 |
logger.exception(e) |
222 |
raise SendInvitationError()
|
223 |
else:
|
224 |
msg = 'Sent invitation %s' % invitation
|
225 |
logger.log(LOGGING_LEVEL, msg) |
226 |
inviter_invitations = invitation.inviter.invitations |
227 |
invitation.inviter.invitations = max(0, inviter_invitations - 1) |
228 |
invitation.inviter.save() |
229 |
|
230 |
|
231 |
def send_greeting(user, email_template_name='im/welcome_email.txt'): |
232 |
"""
|
233 |
Send welcome email.
|
234 |
|
235 |
Raises SMTPException, socket.error
|
236 |
"""
|
237 |
subject = _(GREETING_EMAIL_SUBJECT) |
238 |
message = render_to_string(email_template_name, { |
239 |
'user': user,
|
240 |
'url': urljoin(BASEURL, reverse('index')), |
241 |
'baseurl': BASEURL,
|
242 |
'site_name': SITENAME,
|
243 |
'support': DEFAULT_CONTACT_EMAIL})
|
244 |
sender = settings.SERVER_EMAIL |
245 |
try:
|
246 |
send_mail(subject, message, sender, [user.email], |
247 |
connection=get_connection()) |
248 |
except (SMTPException, socket.error) as e: |
249 |
logger.exception(e) |
250 |
raise SendGreetingError()
|
251 |
else:
|
252 |
msg = 'Sent greeting %s' % user.email
|
253 |
logger.log(LOGGING_LEVEL, msg) |
254 |
|
255 |
|
256 |
def send_feedback(msg, data, user, email_template_name='im/feedback_mail.txt'): |
257 |
subject = _(FEEDBACK_EMAIL_SUBJECT) |
258 |
from_email = settings.SERVER_EMAIL |
259 |
recipient_list = [DEFAULT_CONTACT_EMAIL] |
260 |
content = render_to_string(email_template_name, { |
261 |
'message': msg,
|
262 |
'data': data,
|
263 |
'user': user})
|
264 |
try:
|
265 |
send_mail(subject, content, from_email, recipient_list, |
266 |
connection=get_connection()) |
267 |
except (SMTPException, socket.error) as e: |
268 |
logger.exception(e) |
269 |
raise SendFeedbackError()
|
270 |
else:
|
271 |
msg = 'Sent feedback from %s' % user.email
|
272 |
logger.log(LOGGING_LEVEL, msg) |
273 |
|
274 |
|
275 |
def send_change_email( |
276 |
ec, request, email_template_name='registration/email_change_email.txt'):
|
277 |
try:
|
278 |
url = ec.get_url() |
279 |
url = request.build_absolute_uri(url) |
280 |
t = loader.get_template(email_template_name) |
281 |
c = {'url': url, 'site_name': SITENAME} |
282 |
from_email = settings.SERVER_EMAIL |
283 |
send_mail(_(EMAIL_CHANGE_EMAIL_SUBJECT), t.render(Context(c)), |
284 |
from_email, [ec.new_email_address], |
285 |
connection=get_connection()) |
286 |
except (SMTPException, socket.error) as e: |
287 |
logger.exception(e) |
288 |
raise ChangeEmailError()
|
289 |
else:
|
290 |
msg = 'Sent change email for %s' % ec.user.email
|
291 |
logger.log(LOGGING_LEVEL, msg) |
292 |
|
293 |
|
294 |
def activate( |
295 |
user, |
296 |
email_template_name='im/welcome_email.txt',
|
297 |
helpdesk_email_template_name='im/helpdesk_notification.txt',
|
298 |
verify_email=False):
|
299 |
"""
|
300 |
Activates the specific user and sends email.
|
301 |
|
302 |
Raises SendGreetingError, ValidationError
|
303 |
"""
|
304 |
user.is_active = True
|
305 |
user.email_verified = True
|
306 |
if not user.activation_sent: |
307 |
user.activation_sent = datetime.now() |
308 |
user.save() |
309 |
qh_register_user_with_quotas(user) |
310 |
send_helpdesk_notification(user, helpdesk_email_template_name) |
311 |
send_greeting(user, email_template_name) |
312 |
|
313 |
def deactivate(user): |
314 |
user.is_active = False
|
315 |
user.save() |
316 |
|
317 |
def invite(inviter, email, realname): |
318 |
inv = Invitation(inviter=inviter, username=email, realname=realname) |
319 |
inv.save() |
320 |
send_invitation(inv) |
321 |
inviter.invitations = max(0, self.invitations - 1) |
322 |
inviter.save() |
323 |
|
324 |
def switch_account_to_shibboleth(user, local_user, |
325 |
greeting_template_name='im/welcome_email.txt'):
|
326 |
try:
|
327 |
provider = user.provider |
328 |
except AttributeError: |
329 |
return
|
330 |
else:
|
331 |
if not provider == 'shibboleth': |
332 |
return
|
333 |
user.delete() |
334 |
local_user.provider = 'shibboleth'
|
335 |
local_user.third_party_identifier = user.third_party_identifier |
336 |
local_user.save() |
337 |
send_greeting(local_user, greeting_template_name) |
338 |
return local_user
|
339 |
|
340 |
|
341 |
class SendMailError(Exception): |
342 |
pass
|
343 |
|
344 |
|
345 |
class SendAdminNotificationError(SendMailError): |
346 |
def __init__(self): |
347 |
self.message = _(astakos_messages.ADMIN_NOTIFICATION_SEND_ERR)
|
348 |
super(SendAdminNotificationError, self).__init__() |
349 |
|
350 |
|
351 |
class SendVerificationError(SendMailError): |
352 |
def __init__(self): |
353 |
self.message = _(astakos_messages.VERIFICATION_SEND_ERR)
|
354 |
super(SendVerificationError, self).__init__() |
355 |
|
356 |
|
357 |
class SendInvitationError(SendMailError): |
358 |
def __init__(self): |
359 |
self.message = _(astakos_messages.INVITATION_SEND_ERR)
|
360 |
super(SendInvitationError, self).__init__() |
361 |
|
362 |
|
363 |
class SendGreetingError(SendMailError): |
364 |
def __init__(self): |
365 |
self.message = _(astakos_messages.GREETING_SEND_ERR)
|
366 |
super(SendGreetingError, self).__init__() |
367 |
|
368 |
|
369 |
class SendFeedbackError(SendMailError): |
370 |
def __init__(self): |
371 |
self.message = _(astakos_messages.FEEDBACK_SEND_ERR)
|
372 |
super(SendFeedbackError, self).__init__() |
373 |
|
374 |
|
375 |
class ChangeEmailError(SendMailError): |
376 |
def __init__(self): |
377 |
self.message = _(astakos_messages.CHANGE_EMAIL_SEND_ERR)
|
378 |
super(ChangeEmailError, self).__init__() |
379 |
|
380 |
|
381 |
class SendNotificationError(SendMailError): |
382 |
def __init__(self): |
383 |
self.message = _(astakos_messages.NOTIFICATION_SEND_ERR)
|
384 |
super(SendNotificationError, self).__init__() |
385 |
|
386 |
|
387 |
def get_quota(users): |
388 |
resources = get_resource_names() |
389 |
return qh_get_quota(users, resources)
|
390 |
|
391 |
|
392 |
### PROJECT VIEWS ###
|
393 |
|
394 |
AUTO_ACCEPT_POLICY = 1
|
395 |
MODERATED_POLICY = 2
|
396 |
CLOSED_POLICY = 3
|
397 |
|
398 |
POLICIES = [ AUTO_ACCEPT_POLICY, MODERATED_POLICY, CLOSED_POLICY ] |
399 |
|
400 |
def get_project_by_application_id(project_application_id): |
401 |
try:
|
402 |
return Project.objects.get(application__id=project_application_id)
|
403 |
except Project.DoesNotExist:
|
404 |
raise IOError( |
405 |
_(astakos_messages.UNKNOWN_PROJECT_APPLICATION_ID) % project_application_id) |
406 |
|
407 |
def get_project_id_of_application_id(project_application_id): |
408 |
try:
|
409 |
return Project.objects.get(application__id=project_application_id).id
|
410 |
except Project.DoesNotExist:
|
411 |
raise IOError( |
412 |
_(astakos_messages.UNKNOWN_PROJECT_APPLICATION_ID) % project_application_id) |
413 |
|
414 |
def get_related_project_id(application_id): |
415 |
try:
|
416 |
app = ProjectApplication.objects.get(id=application_id) |
417 |
chain = app.chain |
418 |
project = Project.objects.get(id=chain) |
419 |
return chain
|
420 |
except:
|
421 |
return None |
422 |
|
423 |
def get_project_by_id(project_id): |
424 |
try:
|
425 |
return Project.objects.get(id=project_id)
|
426 |
except Project.DoesNotExist:
|
427 |
raise IOError( |
428 |
_(astakos_messages.UNKNOWN_PROJECT_ID) % project_id) |
429 |
|
430 |
def get_project_for_update(project_id): |
431 |
try:
|
432 |
return Project.objects.select_for_update().get(id=project_id)
|
433 |
except Project.DoesNotExist:
|
434 |
raise IOError( |
435 |
_(astakos_messages.UNKNOWN_PROJECT_ID) % project_id) |
436 |
|
437 |
def get_application_for_update(application_id): |
438 |
try:
|
439 |
objects = ProjectApplication.objects.select_for_update() |
440 |
return objects.get(id=application_id)
|
441 |
except ProjectApplication.DoesNotExist:
|
442 |
m = _(astakos_messages.UNKNOWN_PROJECT_APPLICATION_ID) % application_id |
443 |
raise IOError(m) |
444 |
|
445 |
def get_user_by_id(user_id): |
446 |
try:
|
447 |
return AstakosUser.objects.get(id=user_id)
|
448 |
except AstakosUser.DoesNotExist:
|
449 |
raise IOError(_(astakos_messages.UNKNOWN_USER_ID) % user_id) |
450 |
|
451 |
def get_user_by_uuid(uuid): |
452 |
try:
|
453 |
return AstakosUser.objects.get(uuid=uuid)
|
454 |
except AstakosUser.DoesNotExist:
|
455 |
raise IOError(_(astakos_messages.UNKNOWN_USER_ID) % user_id) |
456 |
|
457 |
def create_membership(project, user): |
458 |
if isinstance(project, int): |
459 |
project = get_project_by_id(project) |
460 |
if isinstance(user, int): |
461 |
user = get_user_by_id(user) |
462 |
m = ProjectMembership( |
463 |
project=project, |
464 |
person=user, |
465 |
request_date=datetime.now()) |
466 |
try:
|
467 |
m.save() |
468 |
except IntegrityError, e:
|
469 |
raise IOError(_(astakos_messages.MEMBERSHIP_REQUEST_EXISTS)) |
470 |
else:
|
471 |
return m
|
472 |
|
473 |
def get_membership_for_update(project, user): |
474 |
if isinstance(project, int): |
475 |
project = get_project_by_id(project) |
476 |
if isinstance(user, int): |
477 |
user = get_user_by_id(user) |
478 |
try:
|
479 |
sfu = ProjectMembership.objects.select_for_update() |
480 |
m = sfu.get(project=project, person=user) |
481 |
if m.is_pending:
|
482 |
raise PendingMembershipError()
|
483 |
return m
|
484 |
except ProjectMembership.DoesNotExist:
|
485 |
raise IOError(_(astakos_messages.NOT_MEMBERSHIP_REQUEST)) |
486 |
|
487 |
def checkAllowed(entity, request_user): |
488 |
if isinstance(entity, Project): |
489 |
application = entity.application |
490 |
elif isinstance(entity, ProjectApplication): |
491 |
application = entity |
492 |
else:
|
493 |
m = "%s not a Project nor a ProjectApplication" % (entity,)
|
494 |
raise ValueError(m) |
495 |
|
496 |
if request_user and \ |
497 |
(not application.owner == request_user and \ |
498 |
not request_user.is_superuser):
|
499 |
raise PermissionDenied(_(astakos_messages.NOT_ALLOWED))
|
500 |
|
501 |
def checkAlive(project): |
502 |
if not project.is_alive: |
503 |
raise PermissionDenied(
|
504 |
_(astakos_messages.NOT_ALIVE_PROJECT) % project.__dict__) |
505 |
|
506 |
def accept_membership_checks(project, request_user): |
507 |
checkAllowed(project, request_user) |
508 |
checkAlive(project) |
509 |
|
510 |
join_policy = project.application.member_join_policy |
511 |
if join_policy == CLOSED_POLICY:
|
512 |
raise PermissionDenied(_(astakos_messages.MEMBER_JOIN_POLICY_CLOSED))
|
513 |
|
514 |
if project.violates_members_limit(adding=1): |
515 |
raise PermissionDenied(_(astakos_messages.MEMBER_NUMBER_LIMIT_REACHED))
|
516 |
|
517 |
def accept_membership(project_id, user, request_user=None): |
518 |
project = get_project_for_update(project_id) |
519 |
accept_membership_checks(project, request_user) |
520 |
|
521 |
membership = get_membership_for_update(project, user) |
522 |
if not membership.can_accept(): |
523 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
524 |
raise PermissionDenied(m)
|
525 |
|
526 |
membership.accept() |
527 |
|
528 |
membership_change_notify(project, membership.person, 'accepted')
|
529 |
|
530 |
return membership
|
531 |
|
532 |
def reject_membership_checks(project, request_user): |
533 |
checkAllowed(project, request_user) |
534 |
checkAlive(project) |
535 |
|
536 |
def reject_membership(project_id, user, request_user=None): |
537 |
project = get_project_for_update(project_id) |
538 |
reject_membership_checks(project, request_user) |
539 |
membership = get_membership_for_update(project, user) |
540 |
if not membership.can_reject(): |
541 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
542 |
raise PermissionDenied(m)
|
543 |
|
544 |
membership.reject() |
545 |
|
546 |
membership_change_notify(project, membership.person, 'rejected')
|
547 |
|
548 |
return membership
|
549 |
|
550 |
def cancel_membership_checks(project): |
551 |
checkAlive(project) |
552 |
|
553 |
def cancel_membership(project_id, user_id): |
554 |
project = get_project_for_update(project_id) |
555 |
cancel_membership_checks(project) |
556 |
membership = get_membership_for_update(project, user_id) |
557 |
if not membership.can_cancel(): |
558 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
559 |
raise PermissionDenied(m)
|
560 |
|
561 |
membership.cancel() |
562 |
|
563 |
def remove_membership_checks(project, request_user=None): |
564 |
checkAllowed(project, request_user) |
565 |
checkAlive(project) |
566 |
|
567 |
leave_policy = project.application.member_leave_policy |
568 |
if leave_policy == CLOSED_POLICY:
|
569 |
raise PermissionDenied(_(astakos_messages.MEMBER_LEAVE_POLICY_CLOSED))
|
570 |
|
571 |
def remove_membership(project_id, user, request_user=None): |
572 |
project = get_project_for_update(project_id) |
573 |
remove_membership_checks(project, request_user) |
574 |
membership = get_membership_for_update(project, user) |
575 |
if not membership.can_remove(): |
576 |
m = _(astakos_messages.NOT_ACCEPTED_MEMBERSHIP) |
577 |
raise PermissionDenied(m)
|
578 |
|
579 |
membership.remove() |
580 |
|
581 |
membership_change_notify(project, membership.person, 'removed')
|
582 |
|
583 |
return membership
|
584 |
|
585 |
def enroll_member(project_id, user, request_user=None): |
586 |
project = get_project_for_update(project_id) |
587 |
accept_membership_checks(project, request_user) |
588 |
membership = create_membership(project_id, user) |
589 |
|
590 |
if not membership.can_accept(): |
591 |
m = _(astakos_messages.NOT_MEMBERSHIP_REQUEST) |
592 |
raise PermissionDenied(m)
|
593 |
|
594 |
membership.accept() |
595 |
|
596 |
# TODO send proper notification
|
597 |
return membership
|
598 |
|
599 |
def leave_project_checks(project): |
600 |
checkAlive(project) |
601 |
|
602 |
leave_policy = project.application.member_leave_policy |
603 |
if leave_policy == CLOSED_POLICY:
|
604 |
raise PermissionDenied(_(astakos_messages.MEMBER_LEAVE_POLICY_CLOSED))
|
605 |
|
606 |
def can_leave_request(project, user): |
607 |
leave_policy = project.application.member_leave_policy |
608 |
if leave_policy == CLOSED_POLICY:
|
609 |
return False |
610 |
m = user.get_membership(project) |
611 |
if m is None: |
612 |
return False |
613 |
if m.state != ProjectMembership.ACCEPTED:
|
614 |
return False |
615 |
return True |
616 |
|
617 |
def leave_project(project_id, user_id): |
618 |
project = get_project_for_update(project_id) |
619 |
leave_project_checks(project) |
620 |
membership = get_membership_for_update(project, user_id) |
621 |
if not membership.can_leave(): |
622 |
m = _(astakos_messages.NOT_ACCEPTED_MEMBERSHIP) |
623 |
raise PermissionDenied(m)
|
624 |
|
625 |
leave_policy = project.application.member_leave_policy |
626 |
if leave_policy == AUTO_ACCEPT_POLICY:
|
627 |
membership.remove() |
628 |
else:
|
629 |
membership.leave_request_date = datetime.now() |
630 |
membership.save() |
631 |
return membership
|
632 |
|
633 |
def join_project_checks(project): |
634 |
checkAlive(project) |
635 |
|
636 |
join_policy = project.application.member_join_policy |
637 |
if join_policy == CLOSED_POLICY:
|
638 |
raise PermissionDenied(_(astakos_messages.MEMBER_JOIN_POLICY_CLOSED))
|
639 |
|
640 |
def can_join_request(project, user): |
641 |
join_policy = project.application.member_join_policy |
642 |
if join_policy == CLOSED_POLICY:
|
643 |
return False |
644 |
m = user.get_membership(project) |
645 |
if m:
|
646 |
return False |
647 |
return True |
648 |
|
649 |
def join_project(project_id, user_id): |
650 |
project = get_project_for_update(project_id) |
651 |
join_project_checks(project) |
652 |
membership = create_membership(project, user_id) |
653 |
|
654 |
join_policy = project.application.member_join_policy |
655 |
if (join_policy == AUTO_ACCEPT_POLICY and |
656 |
not project.violates_members_limit(adding=1)): |
657 |
membership.accept() |
658 |
return membership
|
659 |
|
660 |
def submit_application(kw, request_user=None): |
661 |
|
662 |
kw['applicant'] = request_user
|
663 |
resource_policies = kw.pop('resource_policies', None) |
664 |
|
665 |
precursor = None
|
666 |
precursor_id = kw.get('precursor_application', None) |
667 |
if precursor_id is not None: |
668 |
sfu = ProjectApplication.objects.select_for_update() |
669 |
precursor = sfu.get(id=precursor_id) |
670 |
kw['precursor_application'] = precursor
|
671 |
|
672 |
if (request_user and |
673 |
(not precursor.owner == request_user and |
674 |
not request_user.is_superuser)):
|
675 |
m = _(astakos_messages.NOT_ALLOWED) |
676 |
raise PermissionDenied(m)
|
677 |
|
678 |
application = ProjectApplication(**kw) |
679 |
|
680 |
if precursor is None: |
681 |
application.chain = new_chain() |
682 |
else:
|
683 |
chain = precursor.chain |
684 |
application.chain = chain |
685 |
sfu = ProjectApplication.objects.select_for_update() |
686 |
pending = sfu.filter(chain=chain, state=ProjectApplication.PENDING) |
687 |
for app in pending: |
688 |
app.state = ProjectApplication.REPLACED |
689 |
app.save() |
690 |
|
691 |
application.save() |
692 |
application.resource_policies = resource_policies |
693 |
application_submit_notify(application) |
694 |
return application
|
695 |
|
696 |
def cancel_application(application_id, request_user=None): |
697 |
application = get_application_for_update(application_id) |
698 |
checkAllowed(application, request_user) |
699 |
|
700 |
if not application.can_cancel(): |
701 |
m = _(astakos_messages.APPLICATION_CANNOT_CANCEL % ( |
702 |
application.id, application.state_display())) |
703 |
raise PermissionDenied(m)
|
704 |
|
705 |
application.cancel() |
706 |
|
707 |
def dismiss_application(application_id, request_user=None): |
708 |
application = get_application_for_update(application_id) |
709 |
checkAllowed(application, request_user) |
710 |
|
711 |
if not application.can_dismiss(): |
712 |
m = _(astakos_messages.APPLICATION_CANNOT_DISMISS % ( |
713 |
application.id, application.state_display())) |
714 |
raise PermissionDenied(m)
|
715 |
|
716 |
application.dismiss() |
717 |
|
718 |
def deny_application(application_id): |
719 |
application = get_application_for_update(application_id) |
720 |
|
721 |
if not application.can_deny(): |
722 |
m = _(astakos_messages.APPLICATION_CANNOT_DENY % ( |
723 |
application.id, application.state_display())) |
724 |
raise PermissionDenied(m)
|
725 |
|
726 |
application.deny() |
727 |
application_deny_notify(application) |
728 |
|
729 |
def approve_application(app): |
730 |
|
731 |
app_id = app if isinstance(app, int) else app.id |
732 |
|
733 |
try:
|
734 |
objects = ProjectApplication.objects.select_for_update() |
735 |
application = objects.get(id=app_id) |
736 |
except ProjectApplication.DoesNotExist:
|
737 |
raise PermissionDenied()
|
738 |
|
739 |
if not application.can_approve(): |
740 |
m = _(astakos_messages.APPLICATION_CANNOT_APPROVE % ( |
741 |
application.id, application.state_display())) |
742 |
raise PermissionDenied(m)
|
743 |
|
744 |
application.approve() |
745 |
application_approve_notify(application) |
746 |
|
747 |
def check_expiration(execute=False): |
748 |
objects = Project.objects |
749 |
expired = objects.expired_projects() |
750 |
if execute:
|
751 |
for project in expired: |
752 |
terminate(project.id) |
753 |
|
754 |
return [project.expiration_info() for project in expired] |
755 |
|
756 |
def terminate(project_id): |
757 |
project = get_project_for_update(project_id) |
758 |
checkAlive(project) |
759 |
|
760 |
project.terminate() |
761 |
|
762 |
project_termination_notify(project) |
763 |
|
764 |
def suspend(project_id): |
765 |
project = get_project_by_id(project_id) |
766 |
checkAlive(project) |
767 |
|
768 |
project.suspend() |
769 |
|
770 |
project_suspension_notify(project) |
771 |
|
772 |
def resume(project_id): |
773 |
project = get_project_for_update(project_id) |
774 |
|
775 |
if not project.is_suspended: |
776 |
m = _(astakos_messages.NOT_SUSPENDED_PROJECT) % project.__dict__ |
777 |
raise PermissionDenied(m)
|
778 |
|
779 |
project.resume() |
780 |
|
781 |
def get_by_chain_or_404(chain_id): |
782 |
try:
|
783 |
project = Project.objects.get(id=chain_id) |
784 |
application = project.application |
785 |
return project, application
|
786 |
except:
|
787 |
application = ProjectApplication.objects.latest_of_chain(chain_id) |
788 |
if application is None: |
789 |
raise Http404
|
790 |
else:
|
791 |
return None, application |