def get_ogds_config(self): """Returns the DSN URL for the OGDS DB connection currently being used. """ session = create_session() engine = session.bind return "%s" % engine.url
def import_users(self): """Imports users from all the configured LDAP plugins into OGDS. """ session = create_session() # Set all SQL users inactive first - the ones still contained in the LDAP # will be set active again below (in the same transaction). for user in session.query(User): user.active = 0 for plugin in self._ldap_plugins(): ldap_userfolder = plugin._getLDAPUserFolder() uid_attr = self._get_uid_attr(ldap_userfolder) ldap_util = ILDAPSearch(ldap_userfolder) ldap_users = ldap_util.get_users() for ldap_user in ldap_users: dn, info = ldap_user # Ignore users without an UID in LDAP if not uid_attr in info: continue userid = info[uid_attr] # Skip users with uid longer than SQL 'userid' column # FIXME: Increase size of SQL column to 64 if len(userid) > 30: continue if not self.user_exists(userid): # Create the new user user = User(userid) session.add(user) else: # Get the existing user user = session.query(User).filter_by(userid=userid).first() # Iterate over all SQL columns and update their values columns = User.__table__.columns for col in columns: if col.name == 'userid': # We already set the userid when creating the user # object, and it may not be called the same in LDAP as # in our SQL model continue value = info.get(col.name) # We can't store sequences in SQL columns. So if we do get a multi-valued field # to be stored directly in OGDS, we treat it as a multi-line string and join it. if isinstance(value, list) or isinstance(value, tuple): value = ' '.join([str(v) for v in value]) setattr(user, col.name, value) # Set the user active user.active = 1 logger.info("Imported user '%s'..." % userid) session.flush()
def list_users(self): """A list of dicts. """ session = create_session() userdata_keys = User.__table__.columns.keys() result = session.execute(User.__table__.select()) return [UserDict(**dict(zip(userdata_keys, row))) for row in result]
def is_group_member(self, groupid, userid): in_group = create_session().query( Group.groupid).join(groups_users).filter( Group.groupid == groupid, groups_users.columns.userid == userid).count() return in_group > 0
def create_ogds_user(userid, session=None, groups=("og_mandant1_users",), assigned_client=[], **properties): session = session or create_session() defaults = {"firstname": "Hugo", "lastname": "Boss", "email": "*****@*****.**"} options = defaults.copy() options.update(properties) try: user = session.query(User).filter_by(userid=userid).one() except NoResultFound: user = User(userid, **options) else: for key, value in options.items(): setattr(user, key, value) session.add(user) for groupid in groups: ogds_add_user_to_group(user, groupid, session=session) for client in assigned_client: assign_user_to_client(user, client, session=session) reset_ogds_sync_stamp(getSite()) return user
def migrate(self): log.info("Migrating notification settings for aliased groups...") self.session = create_session() self.new_settings_to_insert = {} # Determine notification defaults *once*, ahead of time self.notification_defaults = { default.kind: default for default in NotificationDefault.query } # Get a list of distinct userids of users that have any settings stored users_with_settings = [ r[0] for r in self.session.query(NotificationSetting.userid.distinct()) ] # For each user, homogenize their settings for userid in users_with_settings: self.homogenize_settings(userid) # Finally, add any new setting rows that were missing (necessary where # only some kinds of an alias group had non-default settings) self.insert_newly_required_settings() log.info("Done migrating notification settings for aliased groups")
def list_user_groups(self, userid): if userid: session = create_session() groups = session.query(User).filter( User.userid == userid).first().group_users return groups return []
def create_sql_tables(): """Creates the sql tables for the models. """ session = create_session() BASE.metadata.create_all(session.bind) DictStorageModel.metadata.create_all(session.bind)
def truncate_sql_tables(): tables = BASE.metadata.tables.values() + \ model.Base.metadata.tables.values() session = create_session() for table in tables: session.execute(table.delete())
def setUp(self): super(TestResponse, self).setUp() self.portal.portal_types['opengever.task.task'].global_allow = True session = create_session() create_client('plone', group='og_mandant1_users', inbox_group='og_mandant1_inbox', session=session) create_client('client2', group='og_mandant2_users', inbox_group='og_mandant2_inbox', session=session) set_current_client_id(self.portal, 'plone') create_ogds_user(TEST_USER_ID, groups=('og_mandant1_users', 'og_mandant1_inbox', 'og_mandant2_users'), firstname='Test', lastname='User', session=session) create_plone_user(self.portal, 'testuser2') create_ogds_user('testuser2', groups=('og_mandant2_users', 'og_mandant2_inbox'), firstname='Test', lastname='User 2', session=session) self.grant('Contributor', 'Editor') login(self.portal, TEST_USER_NAME) self.dossier = create(Builder("dossier")) self.task = create( Builder('task').within(self.dossier).having( title="Test task 1", issuer=TEST_USER_ID, text=u'', responsible='testuser2', responsible_client='client2', task_type="direct-execution")) self.successor = create( Builder('task').within(self.dossier).having( title="Test task 1", responsible='testuser2', issuer=TEST_USER_ID, text=u'', task_type="direct-execution", responsible_client='client2')) self.doc1 = create( Builder("document").within(self.dossier).titled("Doc 1")) self.doc2 = create( Builder("document").within(self.dossier).titled("Doc 2")) transaction.commit()
def list_group_users(self, groupid): """Return all users of a group""" if groupid: session = create_session() group = session.query(Group).get(groupid) if group: return group.users return []
def setUp(self): super(TestResponse, self).setUp() self.portal.portal_types['opengever.task.task'].global_allow = True session = create_session() create_client('plone', group='og_mandant1_users', inbox_group='og_mandant1_inbox', session=session) create_client('client2', group='og_mandant2_users', inbox_group='og_mandant2_inbox', session=session) set_current_client_id(self.portal, 'plone') create_ogds_user(TEST_USER_ID, groups=('og_mandant1_users', 'og_mandant1_inbox', 'og_mandant2_users'), firstname='Test', lastname='User', session=session) create_plone_user(self.portal, 'testuser2') create_ogds_user('testuser2', groups=('og_mandant2_users', 'og_mandant2_inbox'), firstname='Test', lastname='User 2', session=session) self.grant('Contributor', 'Editor') login(self.portal, TEST_USER_NAME) self.dossier = create(Builder("dossier")) self.task = create(Builder('task') .within(self.dossier) .having(title="Test task 1", issuer=TEST_USER_ID, text=u'', responsible='testuser2', responsible_client='client2', task_type="direct-execution")) self.successor = create(Builder('task') .within(self.dossier) .having(title="Test task 1", responsible='testuser2', issuer=TEST_USER_ID, text=u'', task_type="direct-execution", responsible_client='client2')) self.doc1 = create(Builder("document") .within(self.dossier) .titled("Doc 1")) self.doc2 = create(Builder("document") .within(self.dossier) .titled("Doc 2")) transaction.commit()
def ogds_add_user_to_group(user, groupid, session=None): session = session or create_session() try: group = session.query(Group).filter_by(groupid=groupid).one() except NoResultFound: group = Group(groupid) group.users.append(user) session.add(group)
def list_group_users(self, groupid): """Return all users of a group""" if groupid: session = create_session() groups = session.query(Group).filter( Group.groupid == groupid).all() if len(groups) > 0: return groups[0].users return []
def is_group_member(self, groupid, userid): in_group = ( create_session() .query(Group.groupid) .join(groups_users) .filter(Group.groupid == groupid, groups_users.columns.userid == userid) .count() ) return in_group > 0
def setup_sql_tables(): # Create opengever.ogds.base SQL tables create_sql_tables() # Create opengever.globalindex SQL tables model.Base.metadata.create_all(create_session().bind) # Activate savepoint "support" for sqlite # We need savepoint support for version retrieval with CMFEditions. if 'sqlite' in datamanager.NO_SAVEPOINT_SUPPORT: datamanager.NO_SAVEPOINT_SUPPORT.remove('sqlite')
def __init__(self, portal, principal_mapping, mode='move', strict=True): self.portal = portal self.principal_mapping = principal_mapping if mode != 'move': raise NotImplementedError( "OGDSMigrator only supports 'move' mode as of yet") self.mode = mode self.strict = strict self.session = create_session()
def _is_client_assigned(self, userid, client_id): session = create_session() # check if the specified user is in the user_group of the specified # client if session.query(Client).join(Client.users_group).join( Group.users).filter(User.userid == userid).filter( Client.client_id == client_id).count() > 0: return True return False
def create_example(portal_setup): """Creates some example users and clients in the mysql db and in the acl_users folder. """ # Only run step if a flag file is present if portal_setup.readDataFile( 'opengever.ogds.base.create_users.txt') is None: return session = create_session() site = portal_setup.getSite() # USERS _create_example_user(session, site, 'hugo.boss', { 'firstname': 'Hugo', 'lastname': 'Boss' }, ('og_mandant1_users', )) _create_example_user(session, site, 'peter.muster', { 'firstname': 'Peter', 'lastname': 'Muster' }, ('og_mandant2_users', )) _create_example_user(session, site, 'franz.michel', { 'firstname': 'Franz', 'lastname': 'Michel' }, ('og_mandant1_users', 'og_mandant2_users')) # CLIENTS _create_example_client( session, 'mandant1', { 'title': 'Mandant 1', 'ip_address': '127.0.0.1', 'site_url': 'http://localhost:8080/mandant1', 'public_url': 'http://localhost:8080/mandant1', 'group': 'og_mandant1_users', 'inbox_group': 'og_mandant1_inbox' }) _create_example_client( session, 'mandant2', { 'title': 'Mandant 2', 'ip_address': '127.0.0.1', 'site_url': 'http://127.0.0.1:8080/mandant2', 'public_url': 'http://127.0.0.1:8080/mandant2', 'group': 'og_mandant2_users', 'inbox_group': 'og_mandant2_inbox' })
def create_example(portal_setup): """Creates some example users and clients in the mysql db and in the acl_users folder. """ # Only run step if a flag file is present if portal_setup.readDataFile( 'opengever.ogds.base.create_users.txt') is None: return session = create_session() site = portal_setup.getSite() # USERS _create_example_user(session, site, 'hugo.boss', {'firstname': 'Hugo', 'lastname': 'Boss'}, ('og_mandant1_users',)) _create_example_user(session, site, 'peter.muster', {'firstname': 'Peter', 'lastname': 'Muster'}, ('og_mandant2_users',)) _create_example_user(session, site, 'franz.michel', {'firstname': 'Franz', 'lastname': 'Michel'}, ('og_mandant1_users', 'og_mandant2_users')) # CLIENTS _create_example_client(session, 'mandant1', {'title': 'Mandant 1', 'ip_address': '127.0.0.1', 'site_url': 'http://localhost:8080/mandant1', 'public_url': 'http://localhost:8080/mandant1', 'group': 'og_mandant1_users', 'inbox_group': 'og_mandant1_inbox'}) _create_example_client(session, 'mandant2', {'title': 'Mandant 2', 'ip_address': '127.0.0.1', 'site_url': 'http://127.0.0.1:8080/mandant2', 'public_url': 'http://127.0.0.1:8080/mandant2', 'group': 'og_mandant2_users', 'inbox_group': 'og_mandant2_inbox'})
def testSetUp(self): super(MemoryDBLayer, self).testSetUp() engine_factory = EngineFactory('sqlite:///:memory:') provideUtility( engine_factory, provides=IEngineFactory, name=u'opengever_db') scoped_session = GloballyScopedSession(engine=u'opengever_db') provideUtility( scoped_session, provides=IScopedSession, name=u'opengever') setup_sql_tables() self.session = create_session()
def list_assigned_users(self, client_id=None): """Lists all users assigned to a client. """ if not client_id: client_id = get_client_id() if not client_id: logger.warn("can't list assigned users, without a client_id") return [] session = create_session() users = session.query(Group).join(Client.users_group).filter(Client.client_id == client_id).first().users return users
def get_assigned_clients(self, userid=None): """Returns all assigned clients (home clients). """ if not userid: member = getToolByName(getSite(), "portal_membership").getAuthenticatedMember() userid = member.getId() session = create_session() # select all clients with the user in the user group clients = session.query(Client).join(Client.users_group).join(Group.users).filter(User.userid == userid).all() return clients
def setUp(self): super(TestDictstorageMigrator, self).setUp() self.portal = self.layer['portal'] self.session = create_session() self.old_user = create(Builder('ogds_user').id('old.user')) self.new_user = create(Builder('ogds_user').id('new.user')) self.old_user_with_dash = create(Builder('ogds_user').id('old-user')) self.new_user_with_dash = create(Builder('ogds_user').id('new-user')) self.session.add(self.old_user) self.session.add(self.new_user) self.session.add(self.old_user_with_dash) self.session.add(self.new_user_with_dash)
def testSetUp(self): super(MemoryDBLayer, self).testSetUp() engine_factory = EngineFactory('sqlite:///:memory:') provideUtility(engine_factory, provides=IEngineFactory, name=u'opengever_db') scoped_session = GloballyScopedSession(engine=u'opengever_db') provideUtility(scoped_session, provides=IScopedSession, name=u'opengever') setup_sql_tables() self.session = create_session()
def list_assigned_users(self, client_id=None): """Lists all users assigned to a client. """ if not client_id: client_id = get_client_id() if not client_id: logger.warn("can't list assigned users, without a client_id") return [] session = create_session() users = session.query(Group).join(Client.users_group).filter( Client.client_id == client_id).first().users return users
def create_client(clientid="client1", session=None, **properties): session = session or create_session() defaults = { "title": clientid.capitalize(), "ip_address": "127.0.0.1", "site_url": "http://nohost/%s" % clientid, "public_url": "http://nohost/%s" % clientid, "group": "%s_users" % clientid, "inbox_group": "%s_inbox_users" % clientid, } options = defaults.copy() options.update(properties) return _create_example_client(session, clientid, options)
def get_assigned_clients(self, userid=None): """Returns all assigned clients (home clients). """ if not userid: member = getToolByName( getSite(), 'portal_membership').getAuthenticatedMember() userid = member.getId() session = create_session() # select all clients with the user in the user group clients = session.query(Client).join(Client.users_group).join( Group.users).filter(User.userid == userid).all() return clients
def get_user_sort_dict(self): """Returns a dict presenting userid and the fullname, that allows correct sorting on the fullname. Including also every client inbox. """ session = create_session() query = session.query(User.userid, User.lastname, User.firstname) query = query.order_by(User.lastname, User.firstname) ids = query.all() sort_dict = {} for userid, lastname, firstname in ids: sort_dict[userid] = u"%s %s" % (lastname, firstname) # includes every client inbox active_clients = self._clients_query().filter_by(enabled=True) for client in active_clients: principal = u"inbox:%s" % client.client_id sort_dict[principal] = translate(self.describe(principal)) return sort_dict
def get_user_sort_dict(self): """Returns a dict presenting userid and the fullname, that allows correct sorting on the fullname. Including also every client inbox. """ session = create_session() query = session.query(User.userid, User.lastname, User.firstname) query = query.order_by(User.lastname, User.firstname) ids = query.all() sort_dict = {} for userid, lastname, firstname in ids: sort_dict[userid] = u'%s %s' % (lastname, firstname) #includes every client inbox active_clients = self._clients_query().filter_by(enabled=True) for client in active_clients: principal = u'inbox:%s' % client.client_id sort_dict[principal] = translate(self.describe(principal)) return sort_dict
def migrate(self): log.info("Migrating notification settings for aliased groups...") self.session = create_session() self.new_settings_to_insert = {} # Determine notification defaults *once*, ahead of time self.notification_defaults = { default.kind: default for default in NotificationDefault.query} # Get a list of distinct userids of users that have any settings stored users_with_settings = [ r[0] for r in self.session.query( NotificationSetting.userid.distinct()) ] # For each user, homogenize their settings for userid in users_with_settings: self.homogenize_settings(userid) # Finally, add any new setting rows that were missing (necessary where # only some kinds of an alias group had non-default settings) self.insert_newly_required_settings() log.info("Done migrating notification settings for aliased groups")
def get_base_query(self): """Returns the base search query (sqlalchemy) """ return create_session().query(Client)
def list_inactive_users(self): session = create_session() users = session.query(User).filter(User.active == False) return users
def import_groups(self): """Imports groups from all the configured LDAP plugins into OGDS. """ session = create_session() for plugin in self._ldap_plugins(): ldap_userfolder = plugin._getLDAPUserFolder() ldap_util = ILDAPSearch(ldap_userfolder) ldap_groups = ldap_util.get_groups() for ldap_group in ldap_groups: dn, info = ldap_group # Group name is in the 'cn' attribute, which may be mapped to 'fullname' if 'cn' in info: groupid = info['cn'] if isinstance(groupid, list): groupid = groupid[0] else: groupid = info['fullname'] groupid = groupid.decode('utf-8') info['groupid'] = groupid if not self.group_exists(groupid): # Create the new group group = Group(groupid) session.add(group) else: # Get the existing group group = session.query(Group).filter_by( groupid=groupid).first() # Iterate over all SQL columns and update their values columns = Group.__table__.columns for col in columns: value = info.get(col.name) # We can't store sequences in SQL columns. So if we do get # a multi-valued field to be stored directly in OGDS, we # treat it as a multi-line string and join it. if isinstance(value, list) or isinstance(value, tuple): value = ' '.join([str(v) for v in value]) setattr(group, col.name, value) contained_users = [] group_members = ldap_util.get_group_members(info) for user_dn in group_members: try: ldap_user = ldap_util.entry_by_dn(user_dn) user_dn, user_info = ldap_user if not ldap_util.is_ad: if not 'userid' in user_info: logger.warn(NO_UID_MSG % user_dn) continue userid = user_info['userid'] else: # Active Directory uid_found = False for uid_key in AD_UID_KEYS: if uid_key in user_info: userid = user_info[uid_key] uid_found = True break if not uid_found: # No suitable UID found, skip this user logger.warn(NO_UID_AD_MSG % (AD_UID_KEYS, user_dn)) continue if isinstance(userid, list): userid = userid[0] user = self.get_sql_user(userid) if user is None: logger.warn(USER_NOT_FOUND_SQL % userid) continue contained_users.append(user) logger.info("Importing user '%s'..." % userid) except NO_SUCH_OBJECT: logger.warn(USER_NOT_FOUND_LDAP % user_dn) group.users = contained_users session.flush()
def user_exists(self, userid): """Checks whether the OGDS user identified by `userid` exists or not. """ session = create_session() return session.query(User).filter_by(userid=userid).count() != 0
def get_sql_user(self, userid): """Returns the OGDS user object identified by `userid`. """ session = create_session() return session.query(User).filter_by(userid=userid).first()
def group_exists(self, groupid): """Checks whether the OGDS group identified by `groupid` exists or not. """ session = create_session() return session.query(Group).filter_by(groupid=groupid).count() != 0
def __call__(self): form = self.request.form session = create_session() policy_id = form['policy'] client_registry = getUtility(IClientConfigurationRegistry) config = client_registry.get_policy(policy_id) # drop sql tables if form.get('first', False) and config.get('purge_sql', False): self.drop_sql_tables(session) ext_profiles = list(EXTENSION_PROFILES) if config.get('base_profile', None): ext_profiles.append(config.get('base_profile')) # create plone site site = addPloneSite( self.context, form['client_id'], title=form['title'], profile_id=_DEFAULT_PROFILE, extension_ids=ext_profiles, setup_content=False, default_language=config.get('language', 'de-ch'), ) # ldap stool = getToolByName(site, 'portal_setup') if form.get('ldap', False): stool = getToolByName(site, 'portal_setup') stool.runAllImportStepsFromProfile('profile-%s' % form.get('ldap')) # Configure credentials from JSON file at # ~/.opengever/ldap/{hostname}.json configure_ldap_credentials(site) acl_users = getToolByName(site, 'acl_users') plugins = acl_users.plugins # disable source_groups when using ldap for ptype in plugins.listPluginTypeInfo(): try: plugins.deactivatePlugin(ptype['interface'], 'source_groups') except KeyError: pass # deactivate recursive groups for ptype in plugins.listPluginTypeInfo(): try: plugins.deactivatePlugin(ptype['interface'], 'recursive_groups') except KeyError: pass # move ldap up plugins.movePluginsUp(IPropertiesPlugin, ('ldap',)) plugins.movePluginsUp(IPropertiesPlugin, ('ldap',)) plugins.movePluginsUp(IPropertiesPlugin, ('ldap',)) if form.get('first', False) and form.get('import_users', False): print '===== SYNC LDAP ====' class Object(object): pass # Import LDAP users and groups options = Object() options.site_root = '/' + form['client_id'] options.update_syncstamp = False sync_ldap.run_import(self.context, options) if form.get('configsql'): # register the client in the ogds # is the client already configured? -> delete it clients = session.query(Client).filter_by( client_id=form['client_id']).all() if clients: session.delete(clients[0]) # groups must exist users_groups = session.query(Group).filter_by( groupid=form['group']) inbox_groups = session.query(Group).filter_by( groupid=form['inbox_group']) try: users_group = users_groups[0] except IndexError: raise SetupError("User group '%s' could not be found." % form['group']) try: inbox_group = inbox_groups[0] except IndexError: raise SetupError("Inbox group '%s' could not be found." % form['inbox_group']) active = bool(form.get('active', False)) client = Client(form['client_id'], enabled=active, title=form['title'], ip_address=form['ip_address'], site_url=form['site_url'], public_url=form['public_url'], ) client.users_group = users_group client.inbox_group = inbox_group session.add(client) # create the admin user in the ogds if he not exist # and add it to the specified user_group # so we avoid a constraintError in the choice fields if session.query(User).filter_by(userid=ADMIN_USER_ID).count() == 0: og_admin_user = User(ADMIN_USER_ID, firstname='OG', lastname='Administrator', active=True) session.add(og_admin_user) else: og_admin_user = session.query(User).filter_by( userid=ADMIN_USER_ID).first() og_admin_user.active = True users_group = session.query(Group).filter_by( groupid=form['group']).first() if og_admin_user not in users_group.users: users_group.users.append(og_admin_user) # set the client id in the registry client_id = form['client_id'].decode('utf-8') registry = getUtility(IRegistry) proxy = registry.forInterface(IClientConfiguration) proxy.client_id = form['client_id'].decode('utf-8') # set the mail domain in the registry registry = getUtility(IRegistry) proxy = registry.forInterface(IMailSettings) proxy.mail_domain = form['mail_domain'].decode('utf-8') mail_from_address = self.get_mail_from_address() site.manage_changeProperties({'email_from_address': mail_from_address, 'email_from_name': client_id}) # set global Member role for the client users group site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Member', form['group']) # set global Member role for readers group if form['reader_group']: site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Member', form['reader_group']) # set Role Manager role for rolemanager group if form['rolemanager_group']: site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Role Manager', form['rolemanager_group']) # provide the repository root for opengever.setup:default repository_root = config.get('repository_root', None) if repository_root: self.request.set('repository_root', repository_root) # import the defaul generic setup profiles if needed stool = getToolByName(site, 'portal_setup') for profile in config.get('additional_profiles', ()): stool.runAllImportStepsFromProfile('profile-%s' % profile) # set the site title site.manage_changeProperties(title=form['title']) # REALLY set the language - the plone4 addPloneSite is really # buggy with languages. langCP = getAdapter(site, ILanguageSelectionSchema) langCP.default_language = 'de-ch' # the og_admin_user is not longer used so we set him to inactive og_admin_user.active = False return 'ok'
def list_inactive_users(self): session = create_session() users = session.query(User).filter_by(active=False) return users
def __call__(self): form = self.request.form session = create_session() policy_id = form['policy'] client_registry = getUtility(IClientConfigurationRegistry) config = client_registry.get_policy(policy_id) # drop sql tables if form.get('first', False) and config.get('purge_sql', False): self.drop_sql_tables(session) ext_profiles = list(EXTENSION_PROFILES) if config.get('base_profile', None): ext_profiles.append(config.get('base_profile')) # create plone site site = addPloneSite( self.context, form['client_id'], title=form['title'], profile_id=_DEFAULT_PROFILE, extension_ids=ext_profiles, setup_content=False, default_language=config.get('language', 'de-ch'), ) # ldap stool = getToolByName(site, 'portal_setup') if form.get('ldap', False): stool = getToolByName(site, 'portal_setup') stool.runAllImportStepsFromProfile('profile-%s' % form.get('ldap')) # Configure credentials from JSON file at # ~/.opengever/ldap/{hostname}.json configure_ldap_credentials(site) acl_users = getToolByName(site, 'acl_users') plugins = acl_users.plugins # disable source_groups when using ldap for ptype in plugins.listPluginTypeInfo(): try: plugins.deactivatePlugin(ptype['interface'], 'source_groups') except KeyError: pass # deactivate recursive groups for ptype in plugins.listPluginTypeInfo(): try: plugins.deactivatePlugin(ptype['interface'], 'recursive_groups') except KeyError: pass # move ldap up plugins.movePluginsUp(IPropertiesPlugin, ('ldap', )) plugins.movePluginsUp(IPropertiesPlugin, ('ldap', )) plugins.movePluginsUp(IPropertiesPlugin, ('ldap', )) if form.get('first', False) and form.get('import_users', False): print '===== SYNC LDAP ====' class Object(object): pass # Import LDAP users and groups options = Object() options.site_root = '/' + form['client_id'] options.update_syncstamp = False sync_ldap.run_import(self.context, options) if form.get('configsql'): # register the client in the ogds # is the client already configured? -> delete it clients = session.query(Client).filter_by( client_id=form['client_id']).all() if clients: session.delete(clients[0]) # groups must exist users_groups = session.query(Group).filter_by( groupid=form['group']) inbox_groups = session.query(Group).filter_by( groupid=form['inbox_group']) try: users_group = users_groups[0] except IndexError: raise SetupError("User group '%s' could not be found." % form['group']) try: inbox_group = inbox_groups[0] except IndexError: raise SetupError("Inbox group '%s' could not be found." % form['inbox_group']) active = bool(form.get('active', False)) client = Client( form['client_id'], enabled=active, title=form['title'], ip_address=form['ip_address'], site_url=form['site_url'], public_url=form['public_url'], ) client.users_group = users_group client.inbox_group = inbox_group session.add(client) # create the admin user in the ogds if he not exist # and add it to the specified user_group # so we avoid a constraintError in the choice fields if session.query(User).filter_by(userid=ADMIN_USER_ID).count() == 0: og_admin_user = User(ADMIN_USER_ID, firstname='OG', lastname='Administrator', active=True) session.add(og_admin_user) else: og_admin_user = session.query(User).filter_by( userid=ADMIN_USER_ID).first() og_admin_user.active = True users_group = session.query(Group).filter_by( groupid=form['group']).first() if og_admin_user not in users_group.users: users_group.users.append(og_admin_user) # set the client id in the registry client_id = form['client_id'].decode('utf-8') registry = getUtility(IRegistry) proxy = registry.forInterface(IClientConfiguration) proxy.client_id = form['client_id'].decode('utf-8') # set the mail domain in the registry registry = getUtility(IRegistry) proxy = registry.forInterface(IMailSettings) proxy.mail_domain = form['mail_domain'].decode('utf-8') mail_from_address = self.get_mail_from_address() site.manage_changeProperties({ 'email_from_address': mail_from_address, 'email_from_name': client_id }) # set global Member role for the client users group site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Member', form['group']) # set global Member role for readers group if form['reader_group']: site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Member', form['reader_group']) # set Role Manager role for rolemanager group if form['rolemanager_group']: site.acl_users.portal_role_manager.assignRoleToPrincipal( 'Role Manager', form['rolemanager_group']) # provide the repository root for opengever.setup:default repository_root = config.get('repository_root', None) if repository_root: self.request.set('repository_root', repository_root) # import the defaul generic setup profiles if needed stool = getToolByName(site, 'portal_setup') for profile in config.get('additional_profiles', ()): stool.runAllImportStepsFromProfile('profile-%s' % profile) # set the site title site.manage_changeProperties(title=form['title']) # REALLY set the language - the plone4 addPloneSite is really # buggy with languages. langCP = getAdapter(site, ILanguageSelectionSchema) langCP.default_language = 'de-ch' # the og_admin_user is not longer used so we set him to inactive og_admin_user.active = False return 'ok'
def __call__(self): session = create_session() alter_column_length(session, 'task_principals', 'principal', 255)
def list_user_groups(self, userid): if userid: session = create_session() groups = session.query(User).get(userid).groups return groups return []
def _clients_query(self): session = create_session() return session.query(Client)
def assign_user_to_client(user, client, session=None): session = session or create_session() client.users_group.users.append(user) session.add(client.users_group)
def _users_query(self): session = create_session() return session.query(User)
def __call__(self): session = create_session() for tbl_name, col_name, new_length in [('users', 'userid', 255), ('groups', 'groupid', 255), ]: alter_column_length(session, tbl_name, col_name, new_length)