コード例 #1
0
    def render(self):
        conn = ldap.initialize(ALT_LDAP_URI)
        conn.simple_bind_s(ALT_LDAP_DN, ALT_LDAP_PASSWORD)

        try:
            results = conn.search_s(BASEDN, ldap.SCOPE_SUBTREE, '(objectClass=groupOfNames)', ['cn'])
        except:
            # Just in case the user raise a "SIZE_LIMIT_EXCEEDED"
            api.portal.send_email(
                recipient="*****@*****.**",
                sender="*****@*****.**",
                subject="[uLearn] Exception raised: SIZE_LIMIT_EXCEEDED",
                body="The sync view on the uLearn instance has reached the SIZE_LIMIT_EXCEEDED and the groups has not been updated",
            )

        if results:
            portal = api.portal.get()
            soup = get_soup('ldap_groups', portal)
            to_print = []

            for dn, attrs in results:
                group_id = attrs['cn'][0]
                exist = [r for r in soup.query(Eq('id', group_id))]
                if exist:
                    to_print.append('* Already existing record for group: {}'.format(group_id))
                else:
                    record = Record()
                    record.attrs['id'] = group_id
                    record.attrs['searchable_id'] = group_id
                    soup.add(record)
                    to_print.append('Added record for group: {}'.format(group_id))

            return '\n'.join(to_print)
        else:
            return 'No results'
コード例 #2
0
    def render(self):
        portal = getSite()
        current_user = api.user.get_current()
        userid = current_user.id
        search_items_string = self.request.form['items']
        search_items = search_items_string.split(',')
        soup_searches = get_soup('user_news_searches', portal)
        exist = [r for r in soup_searches.query(Eq('id', userid))]
        if not exist:
            record = Record()
            record.attrs['id'] = userid
            record.attrs['searches'] = [search_items]
            record_id = soup_searches.add(record)
            acl_record = soup_searches.get(record_id)
        else:
            acl_record = exist[0]
            in_list = False
            total_searches = acl_record.attrs['searches']
            if acl_record.attrs['searches']:
                for search in acl_record.attrs['searches']:
                    for i, item in enumerate(search_items):
                        if item not in search:
                            break
                        if i == len(search_items) - 1:
                            if len(search_items) < len(search):
                                break
                            else:
                                in_list = True
            if not in_list:
                total_searches.append(search_items)
                acl_record.attrs['searches'] = total_searches
            else:
                acl_record.attrs['searches'] = total_searches

        soup_searches.reindex(records=[acl_record])
コード例 #3
0
    def test_edit_acl(self):
        login(self.portal, 'ulearn.testuser1')
        community = self.create_test_community()
        acl = dict(users=[
            dict(id=u'janet.dura', displayName=u'Janet Durà', role=u'writer'),
            dict(id=u'victor.fernandez',
                 displayName=u'Víctor Fernández de Alba',
                 role=u'reader')
        ],
                   groups=[
                       dict(id=u'PAS', displayName=u'PAS UPC', role=u'writer'),
                       dict(id=u'UPCnet',
                            displayName=u'UPCnet',
                            role=u'reader')
                   ])

        httpretty.enable()
        http_mock_hub_syncacl(acl, self.settings.hub_server)

        adapter = community.adapted()
        adapter.update_acl(acl)

        httpretty.disable()
        httpretty.reset()

        soup = get_soup('communities_acl', self.portal)
        records = [
            r for r in soup.query(Eq('gwuuid',
                                     IGWUUID(community).get()))
        ]

        self.assertEqual(cmp(records[0].attrs['acl'], acl), 0)
コード例 #4
0
 def _soup(self):
     """get soup storage for bookmarks"""
     soup = getattr(self, "_soup_instance", None)
     if soup is None:
         soup = get_soup("collective_bookmarks", api.portal.get())
         setattr(self, "_soup_instance", soup)
     return soup
コード例 #5
0
ファイル: test_ldap.py プロジェクト: UPCnet/ulearn.core
    def test_group_sync(self):
        sync_view = getMultiAdapter((self.portal, self.request), name='syncldapgroups')
        sync_view.render()

        soup = get_soup('ldap_groups', self.portal)

        self.assertTrue(len(soup.data.keys()) > 0)
コード例 #6
0
ファイル: subscribednews.py プロジェクト: UPCnet/ulearn.udemo
    def _data(self):
        # facultiesList = faculties(None).by_value.keys()
        news = []
        news_filtered = []
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request), name='plone_portal_state')
        path = portal_state.navigation_root_path()
        limit = self.data.count
        state = self.data.state

        portal = getSite()
        current_user = api.user.get_current()
        userid = current_user.id

        soup_tags = get_soup('user_subscribed_tags', portal)
        tags_soup = [r for r in soup_tags.query(Eq('id', userid))]
        if tags_soup:
            tags = tags_soup[0].attrs['tags']
            news += self.get_news(context, state, path, limit, tags)
            for newObject in news:
                if newObject not in news_filtered and newObject['subject'] is not ():
                    news_filtered.append(newObject)

            newsSorted = sorted(news_filtered, key=lambda new: new['date'], reverse=True)
            return newsSorted
        else:
            return []
コード例 #7
0
ファイル: soup.py プロジェクト: collective/rapido.souper
 def initialize(self):
     """ setup the storage
     """
     alsoProvides(self.root, ISoupRoot)
     locator = StorageLocator(self.root)
     locator.storage(self.id)
     self._soup = get_soup(self.id, self.root)
コード例 #8
0
    def test_endpoint_returns_data(self):
        url = "{}/@subscriptions".format(self.portal_url)
        response = self.api_session.get(url)
        res = response.json()
        self.assertEqual(res["items_total"], 0)

        now = datetime.now()
        soup = get_soup("subscriptions_soup", self.portal)
        transaction.commit()
        record = Record()
        record.attrs["name"] = "John"
        record.attrs["email"] = "*****@*****.**"
        record.attrs["date"] = now
        intid = soup.add(record)
        transaction.commit()

        url = "{}/@subscriptions".format(self.portal_url)
        response = self.api_session.get(url)
        res = response.json()

        self.assertEqual(res["items_total"], 1)
        self.assertEqual(
            res["items"],
            [
                {
                    "id": intid,
                    "email": "*****@*****.**",
                    "name": "John",
                    "date": json_compatible(now),
                }
            ],
        )
コード例 #9
0
ファイル: views.py プロジェクト: andreesg/bda.plone.orders
    def __call__(self):
        soup = get_soup(self.soup_name, self.context)
        aaData = list()
        length, lazydata = self.query(soup)
        columns = self.columns
        colnames = [_['id'] for _ in columns]

        # todo json response header einbaun

        def record2list(record):
            result = list()
            for colname in colnames:
                coldef = self.column_def(colname)
                renderer = coldef.get('renderer')
                if renderer:
                    value = renderer(colname, record)
                else:
                    value = record.attrs.get(colname, '')
                result.append(value)
            return result

        for lazyrecord in self.slice(lazydata):
            aaData.append(record2list(lazyrecord()))
        data = {
            "sEcho": int(self.request.form['sEcho']),
            "iTotalRecords": soup.storage.length.value,
            "iTotalDisplayRecords": length,
            "aaData": aaData,
        }
        self.request.response.setHeader("Content-type", "application/json")
        return json.dumps(data)
コード例 #10
0
ファイル: utils.py プロジェクト: UPCnet/genweb.core
def get_safe_member_by_id(username):
    """Gets user info from the repoze.catalog based user properties catalog.
       This is a safe implementation for getMemberById portal_membership to
       avoid useless searches to the LDAP server. It gets only exact matches (as
       the original does) and returns a dict. It DOES NOT return a Member
       object.
    """
    portal = api.portal.get()
    soup = get_soup('user_properties', portal)
    username = username.lower()
    records = [r for r in soup.query(Eq('id', username))]
    if records:
        properties = {}
        for attr in records[0].attrs:
            if records[0].attrs.get(attr, False):
                properties[attr] = records[0].attrs[attr]

        # Make sure that the key 'fullname' is returned anyway for it's used in
        # the wild without guards
        if 'fullname' not in properties:
            properties['fullname'] = ''

        return properties
    else:
        # No such member: removed?  We return something useful anyway.
        return {'username': username, 'description': '', 'language': '',
                'home_page': '', 'name_or_id': username, 'location': '',
                'fullname': ''}
コード例 #11
0
def do_transition_for_booking(booking, transition, order_data, event=False):
    """do any transition for a given single booking

    this mixes main state and salaried!
    """
    # XXX: currently we need to delete attribute before setting to a new
    #      value in order to persist change. fix in appropriate place.
    if transition == interfaces.SALARIED_TRANSITION_SALARIED:
        del booking.attrs['salaried']
        booking.attrs['salaried'] = interfaces.SALARIED_YES
    elif transition == interfaces.SALARIED_TRANSITION_OUTSTANDING:
        del booking.attrs['salaried']
        booking.attrs['salaried'] = interfaces.SALARIED_NO
    elif transition == interfaces.STATE_TRANSITION_RENEW:
        del booking.attrs['state']
        booking.attrs['state'] = interfaces.STATE_NEW
        # fix stock item available
        order_data.decrease_stock([booking])
    elif transition == interfaces.STATE_TRANSITION_PROCESS:
        del booking.attrs['state']
        booking.attrs['state'] = interfaces.STATE_PROCESSING
    elif transition == interfaces.STATE_TRANSITION_FINISH:
        del booking.attrs['state']
        booking.attrs['state'] = interfaces.STATE_FINISHED
    elif transition == interfaces.STATE_TRANSITION_CANCEL:
        del booking.attrs['state']
        booking.attrs['state'] = interfaces.STATE_CANCELLED
        # fix stock item available
        order_data.increase_stock([booking])
    else:
        raise ValueError(u"invalid transition: %s" % transition)
    bookings_soup = get_soup('bda_plone_orders_bookings', order_data.context)
    bookings_soup.reindex(records=[booking])
コード例 #12
0
def get_safe_member_by_id(username):
    """Gets user info from the repoze.catalog based user properties catalog.
       This is a safe implementation for getMemberById portal_membership to
       avoid useless searches to the LDAP server. It gets only exact matches (as
       the original does) and returns a dict. It DOES NOT return a Member
       object.
    """
    portal = api.portal.get()
    soup = get_soup('user_properties', portal)
    username = username.lower()
    records = [r for r in soup.query(Eq('id', username))]
    if records:
        properties = {}
        for attr in records[0].attrs:
            if records[0].attrs.get(attr, False):
                properties[attr] = records[0].attrs[attr]

        # Make sure that the key 'fullname' is returned anyway for it's used in
        # the wild without guards
        if 'fullname' not in properties:
            properties['fullname'] = ''

        return properties
    else:
        # No such member: removed?  We return something useful anyway.
        return {
            'username': username,
            'description': '',
            'language': '',
            'home_page': '',
            'name_or_id': username,
            'location': '',
            'fullname': ''
        }
コード例 #13
0
ファイル: views.py プロジェクト: espenmn/bda.plone.orders
    def __call__(self):
        soup = get_soup(self.soup_name, self.context)
        aaData = list()
        length, lazydata = self.query(soup)
        columns = self.columns
        colnames = [_['id'] for _ in columns]
        # todo json response header einbaun

        def record2list(record):
            result = list()
            for colname in colnames:
                coldef = self.column_def(colname)
                renderer = coldef.get('renderer')
                if renderer:
                    value = renderer(colname, record)
                else:
                    value = record.attrs.get(colname, '')
                result.append(value)
            return result
        for lazyrecord in self.slice(lazydata):
            aaData.append(record2list(lazyrecord()))
        data = {
            "sEcho": int(self.request.form['sEcho']),
            "iTotalRecords": soup.storage.length.value,
            "iTotalDisplayRecords": length,
            "aaData": aaData,
        }
        self.request.response.setHeader("Content-type", "application/json")
        return json.dumps(data)
コード例 #14
0
 def render(self):
     portal = getSite()
     current_user = api.user.get_current()
     userid = current_user.id
     search_items = self.request.form['items']
     search_items = search_items.split(',')
     in_list = False
     soup_searches = get_soup('user_news_searches', portal)
     exist = [r for r in soup_searches.query(Eq('id', userid))]
     if exist:
         acl_record = exist[0]
         total_searches = acl_record.attrs['searches']
         for search in exist[0].attrs['searches']:
             for i, item in enumerate(search_items):
                 if item not in search:
                     break
                 if i == len(search_items) - 1:
                     if len(search_items) < len(search):
                         break
                     else:
                         in_list = True
                 if in_list:
                     total_searches.remove(search_items)
                     acl_record.attrs['searches'] = total_searches
                     soup_searches.reindex(records=[acl_record])
コード例 #15
0
def add_user_to_catalog(principal, event):
    """ This subscriber hooks on user creation and adds user properties to the
        soup-based catalog for later searches
    """
    portal = api.portal.get()
    soup = get_soup('user_properties', portal)
    exist = [r for r in soup.query(Eq('username', principal.getUserName()))]
    user_properties_utility = getUtility(ICatalogFactory, name='user_properties')
    indexed_attrs = user_properties_utility(portal).keys()

    if exist:
        user_record = exist[0]
    else:
        record = Record()
        record_id = soup.add(record)
        user_record = soup.get(record_id)

    user_record.attrs['username'] = principal.getUserName()
    user_record.attrs['id'] = principal.getUserName()

    if IPropertiesUpdatedEvent.providedBy(event):
        for attr in indexed_attrs + METADATA_USER_ATTRS:
            if attr in event.properties:
                if isinstance(event.properties[attr], str):
                    user_record.attrs[attr] = event.properties[attr].decode('utf-8')
                else:
                    user_record.attrs[attr] = event.properties[attr]

    soup.reindex(records=[user_record])
コード例 #16
0
    def render(self):
        portal = getSite()
        current_user = api.user.get_current()
        userid = current_user.id
        tag = self.request.form['tag']
        soup_tags = get_soup('user_subscribed_tags', portal)
        exist = [r for r in soup_tags.query(Eq('id', userid))]

        if not exist:
            record = Record()
            record.attrs['id'] = userid
            record.attrs['tags'] = [tag]
            soup_tags.add(record)
        else:
            subscribed = [
                True for utag in exist[0].attrs['tags'] if utag == tag
            ]
            if subscribed:
                exist[0].attrs['tags'].remove(tag)
            else:
                exist[0].attrs['tags'].append(tag)
        soup_tags.reindex()

        if IPloneSiteRoot.providedBy(self.context):
            self.request.response.redirect(self.context.absolute_url() +
                                           '/alltags')
        else:
            self.request.response.redirect(self.context.absolute_url())
コード例 #17
0
ファイル: views.py プロジェクト: UPCnet/genweb.core
    def render(self):
        portal = getSite()
        current_user = api.user.get_current()
        userid = current_user.id
        tag = self.request.form['tag']
        soup_tags = get_soup('user_subscribed_tags', portal)
        exist = [r for r in soup_tags.query(Eq('id', userid))]

        if not exist:
            record = Record()
            record.attrs['id'] = userid
            record.attrs['tags'] = [tag]
            soup_tags.add(record)
        else:
            subscribed = [True for utag in exist[0].attrs['tags'] if utag == tag]
            if subscribed:
                exist[0].attrs['tags'].remove(tag)
            else:
                exist[0].attrs['tags'].append(tag)
        soup_tags.reindex()

        if IPloneSiteRoot.providedBy(self.context):
            self.request.response.redirect(self.context.absolute_url() + '/alltags')
        else:
            self.request.response.redirect(self.context.absolute_url())
コード例 #18
0
ファイル: setup.py プロジェクト: UPCnet/base5.core
    def render(self):
        try:
            from plone.protect.interfaces import IDisableCSRFProtection
            alsoProvides(self.request, IDisableCSRFProtection)
        except:
            pass

        results = []
        try:
            portal = api.portal.get()
            soup_users_delete = get_soup('users_delete_local_roles', portal)
            users = [r for r in soup_users_delete.data.items()]

            for user in users:
                member_id = user[1].attrs['id_username']
                if member_id:
                    results.append('User to delete: {}'.format(member_id))
                    logger.info('User to delete: {}'.format(member_id))

            logger.info(
                'Finish users_to_delete_local_roles portal {}'.format(portal))
            results.append('Finish users_to_delete_local_roles')
            return '\n'.join([str(item) for item in results])
        except:
            logger.info('Except Users to delete local roles')
            results.append('Except Users to delete local roles')
            return 'Error: ' + '\n'.join([str(item) for item in results])
コード例 #19
0
ファイル: views.py プロジェクト: erral/souper.plone
 def rebuild_soup(self):
     sid = self.request.form.get('id')
     if not sid:
         return self.redirect_base('No soup id given')
     soup = get_soup(sid, self.context)
     soup.rebuild()
     msg = '%s rebuilt.' % sid
     return self.redirect_base(msg)
コード例 #20
0
ファイル: views.py プロジェクト: kombinat/souper.plone
 def rebuild_soup(self):
     sid = self.request.form.get("id")
     if not sid:
         return self.redirect_base("No soup id given")
     soup = get_soup(sid, self.context)
     soup.rebuild()
     msg = "%s rebuilt." % sid
     return self.redirect_base(msg)
コード例 #21
0
    def test_group_sync(self):
        sync_view = getMultiAdapter((self.portal, self.request),
                                    name='syncldapgroups')
        sync_view.render()

        soup = get_soup('ldap_groups', self.portal)

        self.assertTrue(len(soup.data.keys()) > 0)
コード例 #22
0
ファイル: views.py プロジェクト: erral/souper.plone
 def clear_soup(self):
     sid = self.request.form.get('id')
     if not sid:
         return self.redirect_base('No soup id given!') 
     soup = get_soup(sid, self.context)
     soup.clear()
     msg = '%s cleared.' % sid
     return self.redirect_base(msg)
コード例 #23
0
    def update(self):
        try:
            from plone.protect.interfaces import IDisableCSRFProtection
            alsoProvides(self.request, IDisableCSRFProtection)
        except:
            pass

        if self.request.environ['REQUEST_METHOD'] == 'POST':

            if self.request.form['users'] != '':
                users = self.request.form['users'].split(',')

                for user in users:
                    user = user.strip()
                    try:
                        pc = api.portal.get_tool(name='portal_catalog')
                        username = user
                        communities = pc.unrestrictedSearchResults(
                            portal_type="ulearn.community")
                        for num, community in enumerate(communities):
                            obj = community._unrestrictedGetObject()
                            self.context.plone_log(
                                'Processant {} de {}. Comunitat {}'.format(
                                    num, len(communities), obj))
                            gwuuid = IGWUUID(obj).get()
                            portal = api.portal.get()
                            soup = get_soup('communities_acl', portal)

                            records = [
                                r for r in soup.query(Eq('gwuuid', gwuuid))
                            ]

                            # Save ACL into the communities_acl soup
                            if records:
                                acl_record = records[0]
                                acl = acl_record.attrs['acl']
                                exist = [
                                    a for a in acl['users']
                                    if a['id'] == unicode(username)
                                ]
                                if exist:
                                    acl['users'].remove(exist[0])
                                    acl_record.attrs['acl'] = acl
                                    soup.reindex(records=[acl_record])
                                    adapter = obj.adapted()
                                    adapter.set_plone_permissions(
                                        adapter.get_acl())

                        logger.info(
                            'Deleted user in communities: {}'.format(user))
                    except:
                        logger.error(
                            'User not deleted in communities: {}'.format(user))
                        pass

                logger.info(
                    'Finished. Deleted users from communities: {}'.format(
                        users))
コード例 #24
0
ファイル: views.py プロジェクト: kombinat/souper.plone
 def rebuild_length(self):
     sid = self.request.form.get("id")
     if not sid:
         return self.redirect_base("No soup id given")
     soup = get_soup(sid, self.context)
     newlen = len(soup.storage.data)
     soup.storage.length.set(newlen)
     transaction.commit()
     return self.redirect_base(u"Length of storage %s is %s" % (sid, newlen))
コード例 #25
0
ファイル: views.py プロジェクト: jean/souper.plone
 def rebuild_length(self):
     sid = self.request.form.get('id')
     if not sid:
         return self.redirect_base('No soup id given')
     soup = get_soup(sid, self.context)
     newlen = len(soup.storage.data)
     soup.storage.length.set(newlen)
     transaction.commit()
     return self.redirect_base(u'Length of storage %s is %s' % (id, newlen))
コード例 #26
0
ファイル: utils.py プロジェクト: UPCnet/genweb.core
def remove_user_from_catalog(username):
    portal = api.portal.get()
    soup = get_soup('user_properties', portal)
    exists = [r for r in soup.query(Eq('id', username))]
    if exists:
        user_record = exists[0]
        del soup[user_record]

    if IAMULEARN:
        extender_name = api.portal.get_registry_record('genweb.controlpanel.core.IGenwebCoreControlPanelSettings.user_properties_extender')
        # Make sure that, in fact we have such a extender in place
        if extender_name in [a[0] for a in getUtilitiesFor(ICatalogFactory)]:
            extended_soup = get_soup(extender_name, portal)
            exist = []
            exist = [r for r in extended_soup.query(Eq('id', username))]
            if exist:
                extended_user_record = exist[0]
                del extended_soup[extended_user_record]
コード例 #27
0
ファイル: mytags.py プロジェクト: UPCnet/ulearn.theme
    def getMyTags(self):
        portal = getSite()
        current_user = api.user.get_current()
        userid = current_user.id

        soup_tags = get_soup('user_subscribed_tags', portal)
        tags_soup = [r for r in soup_tags.query(Eq('id', userid))]

        return tags_soup[0].attrs['tags'] if tags_soup else []
コード例 #28
0
    def DELETE(self):
        """
            Deletes a user from the plone & max & communities subscribe
        """
        self.deleteMembers([self.params['username']])
        remove_user_from_catalog(self.params['username'].lower())
        pc = api.portal.get_tool(name='portal_catalog')
        username = self.params['username']

        maxclient, settings = getUtility(IMAXClient)()
        maxclient.setActor(settings.max_restricted_username)
        maxclient.setToken(settings.max_restricted_token)

        # portal_url = api.portal.get().absolute_url()
        communities_subscription = maxclient.people[
            username].subscriptions.get()

        if communities_subscription != []:

            for num, community_subscription in enumerate(
                    communities_subscription):
                community = pc.unrestrictedSearchResults(
                    portal_type="ulearn.community",
                    community_hash=community_subscription['hash'])
                try:
                    obj = community[0]._unrestrictedGetObject()
                    self.context.plone_log(
                        'Processant {} de {}. Comunitat {}'.format(
                            num, len(communities_subscription), obj))
                    gwuuid = IGWUUID(obj).get()
                    portal = api.portal.get()
                    soup = get_soup('communities_acl', portal)

                    records = [r for r in soup.query(Eq('gwuuid', gwuuid))]

                    # Save ACL into the communities_acl soup
                    if records:
                        acl_record = records[0]
                        acl = acl_record.attrs['acl']
                        exist = [
                            a for a in acl['users']
                            if a['id'] == unicode(username)
                        ]
                        if exist:
                            acl['users'].remove(exist[0])
                            acl_record.attrs['acl'] = acl
                            soup.reindex(records=[acl_record])
                            adapter = obj.adapted()
                            adapter.set_plone_permissions(adapter.get_acl())

                except:
                    continue

        maxclient.people[username].delete()
        logger.info('Delete user: {}'.format(username))
        return ApiResponse({}, code=204)
コード例 #29
0
    def test_delete_community(self):
        login(self.portal, 'ulearn.testuser1')
        community = self.create_test_community()
        gwuuid = IGWUUID(community).get()
        api.content.delete(obj=community)

        soup = get_soup('communities_acl', self.portal)
        records = [r for r in soup.query(Eq('gwuuid', gwuuid))]

        self.assertFalse(records)
コード例 #30
0
    def test_delete_community(self):
        login(self.portal, 'ulearn.testuser1')
        community = self.create_test_community()
        gwuuid = IGWUUID(community).get()
        api.content.delete(obj=community)

        soup = get_soup('communities_acl', self.portal)
        records = [r for r in soup.query(Eq('gwuuid', gwuuid))]

        self.assertFalse(records)
コード例 #31
0
    def get_editacl(self, community):
        # The user has role Manager

        gwuuid = community.gwuuid
        portal = api.portal.get()
        soup = get_soup('communities_acl', portal)

        records = [r for r in soup.query(Eq('gwuuid', gwuuid))]
        editacl = dict(users=records[0].attrs['acl'].get('users', ''),
                       groups=records[0].attrs['acl'].get('groups', ''))
        return editacl
コード例 #32
0
    def test_community_creation_closed(self):
        nom = u'community-test'
        description = 'Blabla'
        image = None
        community_type = 'Closed'
        twitter_hashtag = 'helou'

        login(self.portal, 'ulearn.testuser1')

        self.portal.invokeFactory('ulearn.community', 'community-test',
                                 title=nom,
                                 description=description,
                                 image=image,
                                 community_type=community_type,
                                 twitter_hashtag=twitter_hashtag)

        community = self.portal['community-test']

        logout()

        # Test for the acl registry
        soup = get_soup('communities_acl', self.portal)
        # By the gwuuid
        records = [r for r in soup.query(Eq('gwuuid', IGWUUID(community).get()))]
        self.assertEqual(len(records), 1)
        self.assertEqual(records[0].attrs.get('gwuuid', ''), IGWUUID(community).get())
        self.assertEqual(records[0].attrs.get('path', ''), '/'.join(community.getPhysicalPath()))
        self.assertEqual(records[0].attrs.get('hash', ''), sha1(community.absolute_url()).hexdigest())
        self.assertEqual(records[0].attrs.get('acl', '').get('users', [])[0]['role'], u'owner')
        self.assertEqual(records[0].attrs.get('acl', '').get('users', [])[0]['id'], u'ulearn.testuser1')

        # Test for internal objects
        self.assertEqual(community.objectIds(), ['documents', 'events', 'discussion'])

        # Test for photo folder
        self.assertEqual(community['documents'].objectIds(), ['media', ])

        # Test for subscribed users
        self.assertTrue(u'ulearn.testuser1' in self.get_max_subscribed_users(community))

        # Test for Plone permissions/local roles
        self.assertTrue('Reader' not in community.get_local_roles_for_userid(userid='AuthenticatedUsers'))
        self.assertTrue('Editor' in community.get_local_roles_for_userid(userid='ulearn.testuser1'))
        self.assertTrue('Owner' in community.get_local_roles_for_userid(userid='ulearn.testuser1'))
        self.assertTrue('Reader' in community.get_local_roles_for_userid(userid='ulearn.testuser1'))

        # Test the initial MAX properties
        max_community_info = self.get_max_context_info(community)
        self.assertEqual('helou', max_community_info.get(u'twitterHashtag', ''))
        self.assertFalse(max_community_info.get(u'notifications', False))
        self.assertTrue(u'[COMMUNITY]' in max_community_info.get('tags', []))

        for key in CLOSED_PERMISSIONS:
            self.assertEqual(max_community_info['permissions'].get(key, ''), CLOSED_PERMISSIONS[key])
コード例 #33
0
ファイル: communities.py プロジェクト: UPCnet/ulearn.core
    def get_editacl(self, community):
        # The user has role Manager

        gwuuid = community.gwuuid
        portal = api.portal.get()
        soup = get_soup('communities_acl', portal)

        records = [r for r in soup.query(Eq('gwuuid', gwuuid))]
        editacl = dict(users=records[0].attrs['acl'].get('users', ''),
                       groups=records[0].attrs['acl'].get('groups', ''))
        return editacl
コード例 #34
0
def remove_user_from_catalog(username):
    portal = api.portal.get()
    soup = get_soup('user_properties', portal)
    exists = [r for r in soup.query(Eq('id', username))]
    if exists:
        user_record = exists[0]
        del soup[user_record]

    if IAMULEARN:
        extender_name = api.portal.get_registry_record(
            'genweb.controlpanel.core.IGenwebCoreControlPanelSettings.user_properties_extender'
        )
        # Make sure that, in fact we have such a extender in place
        if extender_name in [a[0] for a in getUtilitiesFor(ICatalogFactory)]:
            extended_soup = get_soup(extender_name, portal)
            exist = []
            exist = [r for r in extended_soup.query(Eq('id', username))]
            if exist:
                extended_user_record = exist[0]
                del extended_soup[extended_user_record]
コード例 #35
0
ファイル: omega13.py プロジェクト: UPCnet/ulearn.core
    def render(self):
        query = self.request.form.get('q', '')
        if query:
            portal = api.portal.get()
            soup = get_soup('ldap_groups', portal)
            normalized_query = query.replace('.', ' ') + '*'

            results = [dict(id=r.attrs.get('id')) for r in soup.query(Eq('searchable_id', normalized_query))]
            return json.dumps(dict(results=results))
        else:
            return json.dumps(dict(id='No results yet.'))
コード例 #36
0
    def isTagFollowed(self, category):
        portal = getSite()
        current_user = api.user.get_current()
        userid = current_user.id

        soup_tags = get_soup('user_subscribed_tags', portal)
        tags_soup = [r for r in soup_tags.query(Eq('id', userid))]
        if tags_soup:
            tags = tags_soup[0].attrs['tags']
            return True if category in tags else False
        else:
            return False
コード例 #37
0
ファイル: viewlets.py プロジェクト: UPCnet/ulearn.core
    def isTagFollowed(self, category):
        portal = getSite()
        current_user = api.user.get_current()
        userid = current_user.id

        soup_tags = get_soup('user_subscribed_tags', portal)
        tags_soup = [r for r in soup_tags.query(Eq('id', userid))]
        if tags_soup:
            tags = tags_soup[0].attrs['tags']
            return True if category in tags else False
        else:
            return False
コード例 #38
0
ファイル: communities.py プロジェクト: UPCnet/ulearn.theme
        def get_data_acces_community_user():
            """ Returns the date of user access to the community.
            """
            user_community = user + '_' + community.id
            portal = api.portal.get()

            soup_access = get_soup('user_community_access', portal)
            exist = [r for r in soup_access.query(Eq('user_community', user_community))]
            if not exist:
                return DateTime()
            else:
                return exist[0].attrs['data_access']
コード例 #39
0
 def test_directory_self_updates_on_user_creation(self):
     api.user.create(email='*****@*****.**', username='******',
                     properties=dict(fullname='Test Directory User',
                                     location='Barcelona',
                                     ubicacio='NX',
                                     telefon='44002, 54390'))
     portal = api.portal.get()
     soup = get_soup('user_properties', portal)
     exist = [r for r in soup.query(Eq('username', 'testdirectory'))]
     self.assertEqual('44002, 54390', exist[0].attrs['telefon'])
     exist = [r for r in soup.query(Eq('fullname', 'Test*'))]
     self.assertEqual(u'Test Directory User', exist[0].attrs['fullname'])
コード例 #40
0
 def test_directory_self_updates_on_user_creation_with_unicode(self):
     api.user.create(email='*****@*****.**', username='******',
                     properties=dict(fullname=u'Víctor',
                                     location=u'Barcelona',
                                     ubicacio=u'NX',
                                     telefon=u'44002, 54390'))
     portal = api.portal.get()
     soup = get_soup('user_properties', portal)
     exist = [r for r in soup.query(Eq('username', 'testdirectory'))]
     self.assertEqual('44002, 54390', exist[0].attrs['telefon'])
     exist = [r for r in soup.query(Eq('fullname', u'Ví*'))]
     self.assertEqual(u'Víctor', exist[0].attrs['fullname'])
コード例 #41
0
ファイル: utils.py プロジェクト: UPCnet/genweb.core
    def render(self):
        portal = api.portal.get()
        soup = get_soup('uuid_preserver', portal)
        pc = api.portal.get_tool('portal_catalog')
        results = pc.searchResults()

        for result in results:
            record = Record()
            record.attrs['uuid'] = result.UID
            record.attrs['path'] = result.getPath()
            soup.add(record)
            logger.warning('Preserving {}: {}'.format(result.getPath(), result.UID))
コード例 #42
0
 def test_directory_self_updates_on_user_creation_with_unicode(self):
     api.user.create(email='*****@*****.**',
                     username='******',
                     properties=dict(fullname=u'Víctor',
                                     location=u'Barcelona',
                                     email=u'*****@*****.**'))
     portal = api.portal.get()
     soup = get_soup('user_properties', portal)
     exist = [r for r in soup.query(Eq('username', 'testdirectory'))]
     self.assertEqual('*****@*****.**', exist[0].attrs['email'])
     exist = [r for r in soup.query(Eq('fullname', u'Ví*'))]
     self.assertEqual(u'Víctor', exist[0].attrs['fullname'])
コード例 #43
0
ファイル: communities.py プロジェクト: UPCnet/ulearn.core
    def is_community_manager(self, community):
        # The user has role Manager
        if self.is_role_manager:
            return True

        gwuuid = community.gwuuid
        portal = api.portal.get()
        soup = get_soup('communities_acl', portal)

        records = [r for r in soup.query(Eq('gwuuid', gwuuid))]
        if records:
            return self.username in [a['id'] for a in records[0].attrs['acl']['users'] if a['role'] == u'owner']
コード例 #44
0
    def render(self):
        portal = api.portal.get()
        soup = get_soup('uuid_preserver', portal)
        pc = api.portal.get_tool('portal_catalog')
        results = pc.searchResults()

        for result in results:
            record = Record()
            record.attrs['uuid'] = result.UID
            record.attrs['path'] = result.getPath()
            soup.add(record)
            logger.warning('Preserving {}: {}'.format(result.getPath(),
                                                      result.UID))
コード例 #45
0
 def test_directory_self_updates_on_user_property_edit(self):
     api.user.create(email='*****@*****.**', username='******',
                     properties=dict(fullname='Test Directory User',
                                     location='Barcelona',
                                     ubicacio='NX',
                                     telefon='44002, 54390'))
     portal = api.portal.get()
     user = api.user.get(username='******')
     user.setMemberProperties(mapping={'location': 'Barcelona', 'telefon': '654321'})
     soup = get_soup('user_properties', portal)
     exist = [r for r in soup.query(Eq('username', 'testdirectory'))]
     self.assertEqual('654321', exist[0].attrs['telefon'])
     self.assertEqual('Barcelona', exist[0].attrs['location'])
コード例 #46
0
ファイル: views.py プロジェクト: UPCnet/ulearn.theme
 def render(self):
     """ clear the soup from links... recreated rendering the personal_bar.pt"""
     portal = getToolByName(self.context, 'portal_url').getPortalObject()
     soup_menu = get_soup('menu_soup', portal)
     soup_menu.clear()
     try:
         from plone.protect.interfaces import IDisableCSRFProtection
         alsoProvides(self.request, IDisableCSRFProtection)
     except:
         pass
     from ulearn.core import _
     IStatusMessage(self.request).addStatusMessage(_(u"menu-reset-menu-msg"), type='success')
     return self.request.response.redirect(self.context.absolute_url())
コード例 #47
0
ファイル: buttonbar.py プロジェクト: UPCnet/ulearn.theme
 def getSearchers(self):
     portal = getSite()
     current_user = api.user.get_current()
     userid = current_user.id
     soup_searches = get_soup('user_news_searches', portal)
     exist = [r for r in soup_searches.query(Eq('id', userid))]
     res = []
     if exist:
         values = exist[0].attrs['searches']
         if values:
             for val in values:
                 res.append(' '.join(val))
     return res
コード例 #48
0
 def test_directory_self_updates_on_user_property_edit(self):
     api.user.create(email='*****@*****.**', username='******',
                     properties=dict(fullname='Test Directory User',
                                     location='Barcelona',
                                     ubicacio='NX',
                                     telefon='44002, 54390'))
     portal = api.portal.get()
     user = api.user.get(username='******')
     user.setMemberProperties(mapping={'location': 'Barcelona', 'telefon': '654321'})
     soup = get_soup('user_properties', portal)
     exist = [r for r in soup.query(Eq('username', 'testdirectory'))]
     self.assertEqual('654321', exist[0].attrs['telefon'])
     self.assertEqual('Barcelona', exist[0].attrs['location'])
コード例 #49
0
    def enumerateUsers(self, id=None, login=None, exact_match=0, sort_by=None, max_results=None, **kw):
        """ Fullfill enumerateUsers requirements """
        # enumerateUsers Boilerplate
        plugin_id = self.getId()
        view_name = self.getId() + '_enumerateUsers'
        criteria = {'id': id, 'login': login, 'exact_match': exact_match,
                    'sort_by': sort_by, 'max_results': max_results}
        criteria.update(kw)

        cached_info = self.ZCacheable_get(view_name=view_name,
                                          keywords=criteria,
                                          default=None)

        if cached_info is not None:
            logger.warning('returning cached results from Omega13 enumerateUsers')
            return cached_info

        portal = api.portal.get()
        soup = get_soup('user_properties', portal)

        result = []
        if exact_match and (id or login):
            if id:
                records = [r for r in soup.query(Eq('username', id))]
            elif login:
                records = [r for r in soup.query(Eq('username', login))]

            if records:
                logger.warning('Omega13 found {} user: {}'.format(len(records), records))
                result.append({'id': records[0].attrs['username'],
                               'login': records[0].attrs['username'],
                               'pluginid': plugin_id,
                               })
        else:
            if id:
                records = [r for r in soup.query(Eq('username', id + '*'))]
            elif login:
                records = [r for r in soup.query(Eq('username', login + '*'))]

            if records:
                logger.warning('Omega13 found {} user: {}'.format(len(records), records))
                for record in records:
                    result.append({'id': record.attrs['username'],
                                   'login': record.attrs['username'],
                                   'pluginid': plugin_id,
                                   })

        result = tuple(result)
        self.ZCacheable_set(result, view_name=view_name, keywords=criteria)

        return result
コード例 #50
0
ファイル: setup.py プロジェクト: UPCnet/ulearn.core
    def update(self):
        try:
            from plone.protect.interfaces import IDisableCSRFProtection
            alsoProvides(self.request, IDisableCSRFProtection)
        except:
            pass
        if self.request.environ['REQUEST_METHOD'] == 'POST':

            if self.request.form['users'] != '':
                users = self.request.form['users'].split(',')

                for user in users:
                    user = user.strip()
                    try:
                        person = Person(self.context, [user])
                        person.deleteMembers([user])
                        remove_user_from_catalog(user.lower())
                        pc = api.portal.get_tool(name='portal_catalog')
                        username = user
                        communities = pc.unrestrictedSearchResults(portal_type="ulearn.community")
                        for num, community in enumerate(communities):
                            obj = community._unrestrictedGetObject()
                            self.context.plone_log('Processant {} de {}. Comunitat {}'.format(num, len(communities), obj))
                            gwuuid = IGWUUID(obj).get()
                            portal = api.portal.get()
                            soup = get_soup('communities_acl', portal)

                            records = [r for r in soup.query(Eq('gwuuid', gwuuid))]

                            # Save ACL into the communities_acl soup
                            if records:
                                acl_record = records[0]
                                acl = acl_record.attrs['acl']
                                exist = [a for a in acl['users'] if a['id'] == unicode(username)]
                                if exist:
                                    acl['users'].remove(exist[0])
                                    acl_record.attrs['acl'] = acl
                                    soup.reindex(records=[acl_record])
                                    adapter = obj.adapted()
                                    adapter.set_plone_permissions(adapter.get_acl())

                        maxclient, settings = getUtility(IMAXClient)()
                        maxclient.setActor(settings.max_restricted_username)
                        maxclient.setToken(settings.max_restricted_token)
                        maxclient.people[username].delete()
                        logger.info('Deleted user: {}'.format(user))
                    except:
                        logger.error('User not deleted: {}'.format(user))
                        pass

                logger.info('Finished process. Deleted users: {}'.format(users))
コード例 #51
0
    def render(self):
        query = self.request.form.get('q', '')
        if query:
            portal = api.portal.get()
            soup = get_soup('ldap_groups', portal)
            normalized_query = query.replace('.', ' ') + '*'

            results = [
                dict(id=r.attrs.get('id'))
                for r in soup.query(Eq('searchable_id', normalized_query))
            ]
            return json.dumps(dict(results=results))
        else:
            return json.dumps(dict(id='No results yet.'))
コード例 #52
0
    def render(self):
        portal = getSite()
        current_user = api.user.get_current()
        userid = current_user.id
        soup_searches = get_soup('user_news_searches', portal)
        exist = [r for r in soup_searches.query(Eq('id', userid))]

        res = []
        if exist:
            values = exist[0].attrs['searches']
            if values:
                for val in values:
                    res.append(' '.join(val))
        return res
コード例 #53
0
    def GET(self):
        portal = api.portal.get()
        soup = get_soup('user_properties', portal)
        records = [r for r in soup.data.items()]

        result = {}
        user_properties_utility = getUtility(ICatalogFactory,
                                             name='user_properties')
        extender_name = api.portal.get_registry_record(
            'genweb.controlpanel.core.IGenwebCoreControlPanelSettings.user_properties_extender'
        )
        for record in records:

            username = record[1].attrs['username']
            user = api.user.get(username=username)
            rendered_properties = []
            if extender_name in [
                    a[0] for a in getUtilitiesFor(ICatalogFactory)
            ]:
                extended_user_properties_utility = getUtility(
                    ICatalogFactory, name=extender_name)
                for prop in extended_user_properties_utility.directory_properties:
                    userProp = user.getProperty(prop, '')
                    if userProp:
                        rendered_properties.append(
                            dict(name=prop,
                                 value=userProp,
                                 icon=extended_user_properties_utility.
                                 directory_icons[prop]))
            else:
                # If it's not extended, then return the simple set of data we know
                # about the user using also the directory_properties field
                for prop in user_properties_utility.directory_properties:
                    try:
                        userProp = user.getProperty(prop, '')
                        if userProp:
                            rendered_properties.append(
                                dict(
                                    name=prop,
                                    value=userProp,
                                    icon=user_properties_utility.
                                    directory_icons[prop],
                                ))
                    except:
                        # Some users has @ in the username and is not valid...
                        pass
            result[record[1].attrs['id']] = rendered_properties

        return ApiResponse(result)
コード例 #54
0
    def is_community_manager(self, community):
        # The user has role Manager
        if self.is_role_manager:
            return True

        gwuuid = community.gwuuid
        portal = api.portal.get()
        soup = get_soup('communities_acl', portal)

        records = [r for r in soup.query(Eq('gwuuid', gwuuid))]
        if records:
            return self.username in [
                a['id'] for a in records[0].attrs['acl']['users']
                if a['role'] == u'owner'
            ]
コード例 #55
0
ファイル: utils.py プロジェクト: UPCnet/genweb.core
    def render(self):
        portal = api.portal.get()
        soup = get_soup('uuid_preserver', portal)
        pc = api.portal.get_tool('portal_catalog')
        results = pc.searchResults()

        for result in results:
            obj = [r for r in soup.query(Eq('path', result.getPath()))]
            if obj:
                try:
                    realobj = result.getObject()
                    IMutableUUID(realobj).set(str(obj[0].attrs['uuid']))
                    realobj.reindexObject(idxs=['UID'])
                    logger.warning('Set UUID per {}'.format(result.getPath()))
                except:
                    logger.warning('Can\'t set UUID for {}'.format(result.getPath()))
コード例 #56
0
ファイル: hooks.py プロジェクト: AndreaVentur10/ulearn.core
def UpdateUserCommunityAccess(content, event):
    """ Update data access to the user community when you add content to the community
    """
    portal = getSite()
    community = findContainerCommunity(content)
    current_user = api.user.get_current()
    user_community = current_user.id + '_' + community.id
    soup_access = get_soup('user_community_access', portal)
    exist = [r for r in soup_access.query(Eq('user_community', user_community))]
    if not exist:
        record = Record()
        record.attrs['user_community'] = user_community
        record.attrs['data_access'] = DateTime()
        soup_access.add(record)
    else:
        exist[0].attrs['data_access'] = DateTime()
    soup_access.reindex()
コード例 #57
0
    def render(self):
        portal = api.portal.get()
        soup = get_soup('uuid_preserver', portal)
        pc = api.portal.get_tool('portal_catalog')
        results = pc.searchResults()

        for result in results:
            obj = [r for r in soup.query(Eq('path', result.getPath()))]
            if obj:
                try:
                    realobj = result.getObject()
                    IMutableUUID(realobj).set(str(obj[0].attrs['uuid']))
                    realobj.reindexObject(idxs=['UID'])
                    logger.warning('Set UUID per {}'.format(result.getPath()))
                except:
                    logger.warning('Can\'t set UUID for {}'.format(
                        result.getPath()))