pyceo/ceod/transactions/groups/AddMemberToGroupTransaction.py

90 lines
3.1 KiB
Python

import traceback
from zope import component
from ..AbstractTransaction import AbstractTransaction
from ceo_common.errors import UserAlreadyInGroupError, UserAlreadySubscribedError
from ceo_common.interfaces import ILDAPService, IConfig
from ceo_common.logger_factory import logger_factory
logger = logger_factory(__name__)
class AddMemberToGroupTransaction(AbstractTransaction):
"""A transaction to add a member to a group."""
operations = [
'add_user_to_group',
'add_user_to_auxiliary_groups',
'subscribe_user_to_auxiliary_mailing_lists',
]
def __init__(self, username: str, group_name: str, subscribe_to_lists: bool):
super().__init__()
self.username = username
self.group_name = group_name
self.subscribe_to_lists = subscribe_to_lists
# a list of auxiliary Groups to which the user will be added
self.aux_groups = []
# a list of mailing list names to which the user will be subscribed
self.aux_lists = []
self.user = None
self.group = None
def child_execute_iter(self):
cfg = component.getUtility(IConfig)
ldap_srv = component.getUtility(ILDAPService)
user = ldap_srv.get_user(self.username)
self.user = user
group = ldap_srv.get_group(self.group_name)
self.group = group
group.add_member(self.username)
yield 'add_user_to_group'
try:
aux_groups = cfg.get('auxiliary groups_' + self.group_name)
for aux_group_name in aux_groups:
try:
aux_group = ldap_srv.get_group(aux_group_name)
aux_group.add_member(self.username)
self.aux_groups.append(aux_group)
except UserAlreadyInGroupError:
pass
if self.aux_groups:
yield 'add_user_to_auxiliary_groups'
except KeyError:
pass
if self.subscribe_to_lists:
try:
aux_lists = cfg.get('auxiliary mailing lists_' + self.group_name)
for aux_list in aux_lists:
try:
user.subscribe_to_mailing_list(aux_list)
self.aux_lists.append(aux_list)
except UserAlreadySubscribedError:
pass
if self.aux_lists:
yield 'subscribe_user_to_auxiliary_mailing_lists'
except KeyError:
pass
except Exception:
logger.error(traceback.format_exc())
yield 'failed_to_subscribe_user_to_auxiliary_mailing_lists'
result = {
'added_to_groups': [self.group_name] + [
group.cn for group in self.aux_groups
],
}
if self.aux_lists:
result['subscribed_to_lists'] = self.aux_lists
self.finish(result)
def rollback(self):
for aux_group in self.aux_groups:
aux_group.remove_member(self.username)
if 'add_user_to_group' in self.finished_operations:
self.group.remove_member(self.username)