Exemple #1
0
 def test_has_permission(self):
     import mock
     from kotti.security import has_permission
     permission = 'edit'
     context = object()
     request = mock.MagicMock()
     has_permission(permission, context, request)
     assert request.has_permission.assert_called_once_with(
         permission, context=context) is None
Exemple #2
0
 def test_has_permission(self):
     import mock
     from kotti.security import has_permission
     permission = 'edit'
     context = object()
     request = mock.MagicMock()
     has_permission(permission, context, request)
     assert request.has_permission.assert_called_once_with(
         permission, context=context) is None
Exemple #3
0
def on_company_insert(event):

    log.info("YPCompany insert")

    wf = get_workflow(event.object)

    if has_permission('state_change', event.object, event.request):
        wf.transition(event.object, event.request, 'created_to_public')
    elif has_permission('submit', event.object, event.request):
        wf.transition(event.object, event.request, 'created_to_pending')
    else:
        log.warn("Company created, but no transition allowed for current user.")
Exemple #4
0
    def view(self):

        media = [c for c in self.context.children
                 if (c.type in ("audio", "video", ))
                 and has_permission("view", self.context, self.request)]
        result = {
            "media": media,
            "can_edit_player_options": has_permission(
                "edit", self.context, self.request),
        }

        return result
Exemple #5
0
def view_calendar(context, request):

    kotti_calendar_resources.need()
    locale_name = get_locale_name(request)
    if locale_name in fullcalendar_locales:
        fullcalendar_locales[locale_name].need()
    else:  # pragma: no cover (safety belt only, should never happen)
        fullcalendar_locales["en"].need()

    session = DBSession()
    now = datetime.datetime.now()
    query = session.query(Event).filter(Event.parent_id == context.id)
    future = or_(Event.start > now, Event.end > now)
    upcoming = query.filter(future).order_by(Event.start).all()
    past = query.filter(Event.start < now).order_by(desc(Event.start)).all()
    upcoming = [event for event in upcoming if
                has_permission('view', event, request)]
    past = [event for event in past if
            has_permission('view', event, request)]

    fmt = '%Y-%m-%d %H:%M:%S'
    fullcalendar_events = []
    for event in (upcoming + past):
        json_event = {
            'title': event.title,
            'url': resource_url(event, request),
            'start': event.start.strftime(fmt),
            'allDay': event.all_day,
            }
        if event.end:
            json_event['end'] = event.end.strftime(fmt)
        fullcalendar_events.append(json_event)

    fullcalendar_options = {
        'header': {
            'left': 'prev,next today',
            'center': 'title',
            'right': 'month,agendaWeek,agendaDay'
        },
        'eventSources': context.feeds,
        'weekends': context.weekends,
        'events': fullcalendar_events,
        }

    return {
        'api': template_api(context, request),
        'upcoming_events': upcoming,
        'past_events': past,
        'fullcalendar_options': json.dumps(fullcalendar_options),
        }
Exemple #6
0
    def test_basic(self):
        from kotti.security import has_permission

        permission, context, request = object(), object(), DummyRequest()
        args = []

        def has_permission_fake(permission, context, request):
            args.append((permission, context, request))
            assert request.environ['authz_context'] == context

        with patch('kotti.security.base_has_permission',
                   new=has_permission_fake):
            has_permission(permission, context, request)

        assert args == [(permission, context, request)]
Exemple #7
0
    def test_basic(self):
        from kotti.security import has_permission

        permission, context, request = object(), object(), DummyRequest()
        args = []

        def has_permission_fake(permission, context, request):
            args.append((permission, context, request))
            assert request.environ['authz_context'] == context

        with patch('kotti.security.base_has_permission',
                   new=has_permission_fake):
            has_permission(permission, context, request)

        assert args == [(permission, context, request)]
Exemple #8
0
    def news_items(self, num=None):
        """ Query the site for NewsItems and return them ordered by
            publish_date.

        :param num: Maximum number of NewsItems to return.  The default of
                    ``None`` means return all NewsItems.
        :type num: int or None

        :result: Sequence of NewsItems.
        :rtype: list
        """

        q = NewsItem.query \
            .filter(NewsItem.publish_date <= date.today())\
            .order_by(desc(NewsItem.publish_date))

        items = []

        for item in q.all():
            if has_permission('view', item, self.request):
                items.append(item)
                if num is not None and len(items) == num:
                    return items

        return items
Exemple #9
0
 def has_permission(self, permission, context=None):
     """ Convenience wrapper for :func:`pyramid.security.has_permission`
     with the same signature.  If ``context`` is ``None`` the current
     context is passed to ``has_permission``."""
     if context is None:
         context = self.context
     return has_permission(permission, context, self.request)
Exemple #10
0
def search_content(search_term, request=None, permission='pview'):

    searchstring = u'%{0}%'.format(search_term)

    # generic_filter can be applied to all Node (and subclassed) objects
    generic_filter = or_(Content.name.like(searchstring),
                         Content.title.like(searchstring),
                         Content.description.like(searchstring))

    results = DBSession.query(Content).filter(generic_filter).\
        order_by(Content.title.asc()).all()

    # specific result contain objects matching additional criteria
    # but must not match the generic criteria (because these objects
    # are already in the generic_results)
    document_results = DBSession.query(Document).filter(
        and_(Document.body.like(searchstring),
             not_(generic_filter)))

    for results_set in [content_with_tags([searchstring]),
                        document_results.all()]:
        [results.append(c) for c in results_set if c not in results]

    result_dicts = []

    for result in results:
        if has_permission(permission, result, request):
            result_dicts.append(dict(
                name=result.name,
                title=result.title,
                description=result.description,
                path=request.resource_path(result)))

    return result_dicts
Exemple #11
0
def default_search_content(search_term, request=None):

    searchstring = u'%%%s%%' % search_term

    # generic_filter can be applied to all Node (and subclassed) objects
    generic_filter = or_(Content.name.like(searchstring),
                         Content.title.like(searchstring),
                         Content.description.like(searchstring))

    results = DBSession.query(Content).filter(generic_filter).all()

    # specific result contain objects matching additional criteria
    # but must not match the generic criteria (because these objects
    # are already in the generic_results)
    document_results = DBSession.query(Document).filter(
        and_(Document.body.like(searchstring),
             not_(generic_filter)))

    for results_set in [content_with_tags([searchstring]),
                        document_results.all()]:
        [results.append(c) for c in results_set if not c in results]

    result_dicts = []

    for result in results:
        if has_permission('view', result, request):
            result_dicts.append(dict(
                name=result.name,
                title=result.title,
                description=result.description,
                path=request.resource_path(result)))

    return result_dicts
Exemple #12
0
def get_children(context, request):
    settings = navigation_settings()
    user = get_user(request)
    show_hidden = asbool(settings['show_hidden_while_logged_in'])
    ex_cts = settings['exclude_content_types']

    if show_hidden and user:
        childs = [child for child in context.values()
                   if has_permission('view', child, request) and
                   child.__class__ not in ex_cts]
    else:
        childs = [child for child in context.values()
                    if child.in_navigation and
                        has_permission('view', child, request) and
                        child.__class__ not in ex_cts]
    return childs
Exemple #13
0
 def has_permission(self, permission, context=None):
     """ Convenience wrapper for :func:`pyramid.security.has_permission`
     with the same signature.  If ``context`` is ``None`` the current
     context is passed to ``has_permission``."""
     if context is None:
         context = self.context
     return has_permission(permission, context, self.request)
Exemple #14
0
    def __init__(self, context, request):

        self.context = context
        self.request = request

        if has_permission("edit", self.context, self.request):
            kotti_forum_js.need()
Exemple #15
0
    def __init__(self, context, request):

        self.context = context
        self.request = request

        if has_permission("edit", self.context, self.request):
            kotti_software_js.need()
Exemple #16
0
def default_search_content(search_term, request=None):

    searchstring = u'%%%s%%' % search_term

    # generic_filter can be applied to all Node (and subclassed) objects
    generic_filter = or_(Content.name.like(searchstring),
                         Content.title.like(searchstring),
                         Content.description.like(searchstring))

    generic_results = DBSession.query(Content).filter(generic_filter)

    # specific result contain objects matching additional criteria
    # but must not match the generic criteria (because these objects
    # are already in the generic_results)
    document_results = DBSession.query(Document).filter(
        and_(Document.body.like(searchstring), not_(generic_filter)))

    all_results = [c for c in generic_results.all()] \
        + [c for c in document_results.all()]

    result_dicts = []

    for result in all_results:
        if has_permission('view', result, request):
            result_dicts.append(
                dict(name=result.name,
                     title=result.title,
                     description=result.description,
                     path=request.resource_path(result)))
    return result_dicts
Exemple #17
0
    def __init__(self, context, request):

        self.context = context
        self.request = request

        use_fanstatic = get_settings().get('kotti_media.use_fanstatic', True)
        if use_fanstatic and has_permission("edit", self.context, self.request):
            kotti_media_js.need()
Exemple #18
0
 def list_children(self, context=None, permission="view"):
     if context is None:
         context = self.context
     children = []
     if hasattr(context, "values"):
         for child in context.values():
             if not permission or has_permission(permission, child, self.request):
                 children.append(child)
     return children
Exemple #19
0
    def redirect(self):
        """View that redirects the user to the given link. If the user
           has the edit permission a template with a hint is presented.
        """
        if has_permission(u'edit', self.context, self.request):
            kotti_link.need()
            return {}

        return HTTPFound(location=self.context.link)
Exemple #20
0
def view_calendar(context, request):

    kotti_calendar_resources.need()
    locale_name = get_locale_name(request)
    if locale_name in fullcalendar_locales:
        fullcalendar_locales[locale_name].need()
    else:  # pragma: no cover (safety belt only, should never happen)
        fullcalendar_locales["en"].need()

    session = DBSession()
    now = datetime.datetime.now()
    query = session.query(Event).filter(Event.parent_id == context.id)
    future = or_(Event.start > now, Event.end > now)
    upcoming = query.filter(future).order_by(Event.start).all()
    past = query.filter(Event.start < now).order_by(desc(Event.start)).all()
    upcoming = [event for event in upcoming if has_permission("view", event, request)]
    past = [event for event in past if has_permission("view", event, request)]

    fmt = "%Y-%m-%d %H:%M:%S"
    fullcalendar_events = []
    for event in upcoming + past:
        json_event = {
            "title": event.title,
            "url": resource_url(event, request),
            "start": event.start.strftime(fmt),
            "allDay": event.all_day,
        }
        if event.end:
            json_event["end"] = event.end.strftime(fmt)
        fullcalendar_events.append(json_event)

    fullcalendar_options = {
        "header": {"left": "prev,next today", "center": "title", "right": "month,agendaWeek,agendaDay"},
        "eventSources": context.feeds,
        "weekends": context.weekends,
        "events": fullcalendar_events,
    }

    return {
        "api": template_api(context, request),
        "upcoming_events": upcoming,
        "past_events": past,
        "fullcalendar_options": json.dumps(fullcalendar_options),
    }
Exemple #21
0
    def files(self):
        """ Files that the event contains.
        :result: List of files.
        :rtype: list of :class:`kotti.resources.File`
        """

        files = File.query.filter(File.parent_id == self.context.id)\
            .order_by(File.position).all()

        return [f for f in files if has_permission('view', f, self.request)]
Exemple #22
0
def upcoming_events(context, request):
    now = datetime.datetime.now()
    settings = events_settings()
    future = or_(Event.start > now, Event.end > now)
    events = DBSession.query(Event).filter(future).order_by(Event.start).all()
    events = [event for event in events if
              has_permission('view', event, request)]
    if len(events) > settings['events_count']:
        events = events[:settings['events_count']]
    return {'events': events}
Exemple #23
0
def previous_events(context, request):
    now = datetime.datetime.now()
    settings = events_settings()
    past = or_(Event.start < now, Event.end < now)
    events = DBSession.query(Event).filter(past).order_by(Event.start).all()
    events = [event for event in events if\
                has_permission('view', event, request)]
    if len(events) > settings['events_count']:
        events = events[:settings['events_count']]
    return {'events': events}
Exemple #24
0
def result_items(context, request):
    settings = get_settings()
    content_types = settings.get(
        'kotti_feed.content_types', 'document').split(' ')
    items = DBSession.query(Content).filter(
        Content.type.in_(content_types)).order_by(Content.modification_date)
    context_path = request.resource_path(context)
    return [item for item in items
            if (has_permission('view', item, request) and
                request.resource_path(item).startswith(context_path))]
Exemple #25
0
 def list_children(self, context=None, permission='view'):
     if context is None:
         context = self.context
     children = []
     if hasattr(context, 'values'):
         for child in context.values():
             if (not permission or
                 has_permission(permission, child, self.request)):
                 children.append(child)
     return children
Exemple #26
0
    def files(self):
        """ Files that the event contains.
        :result: List of files.
        :rtype: list of :class:`kotti.resources.File`
        """

        files = File.query.filter(File.parent_id == self.context.id)\
            .order_by(File.position).all()

        return [f for f in files if has_permission('view', f, self.request)]
Exemple #27
0
def previous_events(context, request):
    now = datetime.datetime.now()
    settings = events_settings()
    past = or_(Event.start < now, Event.end < now)
    events = DBSession.query(Event).filter(past).order_by(Event.start).all()
    events = [event for event in events if\
                has_permission('view', event, request)]
    if len(events) > settings['events_count']:
        events = events[:settings['events_count']]
    return {'events': events}
Exemple #28
0
 def children(self):
     return [
         NodesTree(
             child,
             self._request,
             self._item_mapping,
             self._item_to_children,
             self._permission,
         ) for child in self._item_to_children[self.id]
         if has_permission(self._permission, child, self._request)
     ]
Exemple #29
0
def frontpage_view(context, request):
    session = DBSession()
    query = session.query(BlogEntry).order_by(BlogEntry.date.desc())
    items = query.all()[:3]
    items = [
        item for item in items if has_permission('view', item, request)
    ]
    return {
        'api': template_api(context, request),
        'items': items,
    }
Exemple #30
0
def upcoming_events(context, request):
    now = datetime.datetime.now()
    settings = events_settings()
    future = or_(Event.start > now, Event.end > now)
    events = DBSession.query(Event).filter(future).order_by(Event.start).all()
    events = [
        event for event in events if has_permission('view', event, request)
    ]
    if len(events) > settings['events_count']:
        events = events[:settings['events_count']]
    return {'events': events}
Exemple #31
0
 def children(self):
     return [
         NodesTree(
             child,
             self._request,
             self._item_mapping,
             self._item_to_children,
             self._permission,
         )
         for child in self._item_to_children[self.id]
         if has_permission(self._permission, child, self._request)
     ]
Exemple #32
0
def nodes_tree(request):
    item_mapping = {}
    item_to_children = defaultdict(lambda: [])
    for node in DBSession.query(Content).with_polymorphic(Content):
        item_mapping[node.id] = node
        if has_permission("view", node, request):
            item_to_children[node.parent_id].append(node)

    for children in item_to_children.values():
        children.sort(key=lambda ch: ch.position)

    return NavigationNodeWrapper(item_to_children[None][0], request, item_mapping, item_to_children)
Exemple #33
0
def view_site_gallery(context, request):

    sites = DBSession.query(Site)\
        .filter(Site.parent_id == context.id)\
        .all()

    sites = [s for s in sites if has_permission('view', s, request)]

    return dict(
        api=template_api(context, request),
        sites=sites,
    )
Exemple #34
0
def result_items(context, request):
    settings = get_settings()
    content_types = settings.get('kotti_feed.content_types',
                                 'document').split(' ')
    items = DBSession.query(Content).filter(
        Content.type.in_(content_types)).order_by(Content.modification_date)
    context_path = request.resource_path(context)
    return [
        item for item in items
        if (has_permission('view', item, request)
            and request.resource_path(item).startswith(context_path))
    ]
Exemple #35
0
def search_content_for_tags(tags, request=None):

    result_dicts = []

    for result in content_with_tags(tags):
        if has_permission('view', result, request):
            result_dicts.append(dict(
                name=result.name,
                title=result.title,
                description=result.description,
                path=request.resource_path(result)))

    return result_dicts
Exemple #36
0
def search_content_for_tags(tags, request=None):

    result_dicts = []

    for result in content_with_tags(tags):
        if has_permission('view', result, request):
            result_dicts.append(
                dict(name=result.name,
                     title=result.title,
                     description=result.description,
                     path=request.resource_path(result)))

    return result_dicts
Exemple #37
0
    def children_with_permission(self, request, permission="view"):
        """
        Return only those children for which the user initiating
        the request has the asked permission.

        :param request: current request
        :type request: :class:`pyramid.request.Request`
        :param permission: The permission for which you want the allowed
                           children
        :type permission: str
        :result: List of child nodes
        :rtype: list
        """

        return [c for c in self.children if has_permission(permission, c, request)]
Exemple #38
0
    def upcoming_events(self):
        """ List events in the future.

        :result: List of events.
        :rtype: list of :class:`kotti_calendar.resources.Event`
        """

        now = datetime.datetime.now()

        events = Event.query \
            .filter(Event.parent_id == self.context.id) \
            .filter(or_(Event.start > now, Event.end > now))\
            .order_by(Event.start)\
            .all()

        return [event for event in events
                if has_permission('view', event, self.request)]
Exemple #39
0
def nodes_tree(request):
    item_mapping = {}
    item_to_children = defaultdict(lambda: [])
    for node in DBSession.query(Content).with_polymorphic(Content):
        item_mapping[node.id] = node
        if has_permission('view', node, request):
            item_to_children[node.parent_id].append(node)

    for children in item_to_children.values():
        children.sort(key=lambda ch:ch.position)

    return NavigationNodeWrapper(
        item_to_children[None][0],
        request,
        item_mapping,
        item_to_children,
        )
Exemple #40
0
    def children_with_permission(self, request, permission='view'):
        """
        Return only those children for which the user initiating
        the request has the asked permission.

        :param request:
        :type request: :class:`pyramid.request.Request`
        :param permission: The permission for which you want the allowed
                           children
        :type permission: str
        :result: List of child nodes
        :rtype: list
        """

        return [
            c for c in self.children if has_permission(permission, c, request)
        ]
Exemple #41
0
def nodes_tree(request, context=None, permission="view"):
    item_mapping = {}
    item_to_children = defaultdict(lambda: [])
    for node in DBSession.query(Content).with_polymorphic(Content):
        item_mapping[node.id] = node
        if has_permission("view", node, request):
            item_to_children[node.parent_id].append(node)

    for children in item_to_children.values():
        children.sort(key=lambda ch: ch.position)

    if context is None:
        node = item_to_children[None][0]
    else:
        node = context

    return NodesTree(node, request, item_mapping, item_to_children, permission)
Exemple #42
0
def default_search_content(search_term, request=None):
    searchstring = u"%%%s%%" % search_term
    results = DBSession.query(Content).filter(
        or_(Content.name.like(searchstring), Content.title.like(searchstring), Content.description.like(searchstring))
    )
    result_dict = []
    for result in results.all():
        if has_permission("view", result, request):
            result_dict.append(
                dict(
                    name=result.name,
                    title=result.title,
                    description=result.description,
                    path=request.resource_path(result),
                )
            )
    return result_dict
Exemple #43
0
    def upcoming_events(self):
        """ List events in the future.

        :result: List of events.
        :rtype: list of :class:`kotti_calendar.resources.Event`
        """

        now = datetime.datetime.now()

        events = Event.query \
            .filter(Event.parent_id == self.context.id) \
            .filter(or_(Event.start > now, Event.end > now))\
            .order_by(Event.start)\
            .all()

        return [
            event for event in events
            if has_permission('view', event, self.request)
        ]
Exemple #44
0
def default_search_content(search_term, request=None, options=None):
    '''
        Supported options:
            types: array of content types to search for
    '''
    if options is None:
        options = {}

    searchstring = u'%%%s%%' % search_term

    # generic_filter can be applied to all Node (and subclassed) objects
    generic_filter = or_(Content.name.like(searchstring),
                         Content.title.like(searchstring),
                         Content.description.like(searchstring))

    query = DBSession.query(Content).filter(generic_filter)
    if 'types' in options:
        query = query.filter(Content.type.in_(options['types']))

    results = query.order_by(Content.title.asc()).all()

    # specific result contain objects matching additional criteria
    # but must not match the generic criteria (because these objects
    # are already in the generic_results)
    document_results = DBSession.query(Document).filter(
        and_(Document.body.like(searchstring),
             not_(generic_filter)))

    for results_set in [content_with_tags([searchstring]),
                        document_results.all()]:
        [results.append(c) for c in results_set if not c in results]

    result_dicts = []

    for result in results:
        if has_permission('view', result, request):
            result_dicts.append(dict(
                name=result.name,
                title=result.title,
                description=result.description,
                path=request.resource_path(result)))

    return result_dicts
Exemple #45
0
 def view_blog(self):
     settings = blog_settings()
     macros = get_renderer('templates/macros.pt').implementation()
     session = DBSession()
     query = session.query(BlogEntry).filter(\
                 BlogEntry.parent_id == self.context.id).order_by(BlogEntry.date.desc())
     items = query.all()
     items = [item for item in items if has_permission('view', item, self.request)]
     page = self.request.params.get('page', 1)
     if settings['use_batching']:
         items = Batch.fromPagenumber(items,
                       pagesize=settings['pagesize'],
                       pagenumber=int(page))
     return {
         'api': template_api(self.context, self.request),
         'macros': macros,
         'items': items,
         'settings': settings,
         }
Exemple #46
0
    def event_url(self, event):
        """ Return the URL for an event in the calendar view.

        :param event: Event for which the URL is requested.
        :type event: :class:`kotti_calendar.resources.Event`

        :result: URL
        :rtype: str
        """

        url = resource_url(event, self.request)

        if event.link_to_file:
            files = File.query.filter(File.parent_id == event.id)\
                .order_by(File.position).all()
            for f in files:
                if has_permission('view', f, self.request):
                    url = resource_url(f, self.request, '@@attachment-view')
                    break
        return url
Exemple #47
0
    def event_url(self, event):
        """ Return the URL for an event in the calendar view.

        :param event: Event for which the URL is requested.
        :type event: :class:`kotti_calendar.resources.Event`

        :result: URL
        :rtype: str
        """

        url = resource_url(event, self.request)

        if event.link_to_file:
            files = File.query.filter(File.parent_id == event.id)\
                .order_by(File.position).all()
            for f in files:
                if has_permission('view', f, self.request):
                    url = resource_url(f, self.request, '@@attachment-view')
                    break
        return url
Exemple #48
0
    def past_events(self):
        """ List events in the past.

        :result: List of events.
        :rtype: list of :class:`kotti_calendar.resources.Event`
        """
        now = datetime.datetime.now()
        calendar_condition = or_(
            Event.other_calendars.any(Calendar.id == self.context.id),
            Event.parent_id == self.context.id)

        events = Event.query \
            .filter(calendar_condition) \
            .filter(Event.start < now)\
            .order_by(desc(Event.start))\
            .all()

        return [
            event for event in events
            if has_permission('view', event, self.request)
        ]
Exemple #49
0
def nodes_tree(request, context=None, permission='view'):
    item_mapping = {}
    item_to_children = defaultdict(lambda: [])
    for node in DBSession.query(Content).with_polymorphic(Content):
        item_mapping[node.id] = node
        if has_permission('view', node, request):
            item_to_children[node.parent_id].append(node)

    for children in item_to_children.values():
        children.sort(key=lambda ch: ch.position)

    if context is None:
        node = item_to_children[None][0]
    else:
        node = context

    return NodesTree(
        node,
        request,
        item_mapping,
        item_to_children,
        permission,
    )
Exemple #50
0
 def view_blog(self):
     macros = get_renderer('templates/macros.pt').implementation()
     query = DBSession.query(BlogEntry)
     query = query.filter(BlogEntry.parent_id == self.context.id)
     query = query.order_by(BlogEntry.date.desc())
     items = query.all()
     items = [
         item for item in items
         if has_permission('view', item, self.request)
     ]
     page = self.request.params.get('page', 1)
     use_pagination = get_setting('use_pagination')
     if use_pagination:
         items = Batch.fromPagenumber(items,
                                      pagesize=get_setting('pagesize'),
                                      pagenumber=int(page))
     return {
         'api': template_api(self.context, self.request),
         'macros': macros,
         'items': items,
         'use_pagination': use_pagination,
         'link_headline': get_setting('link_headline'),
     }
Exemple #51
0
 def has_permission(self, permission, context=None):
     if context is None:
         context = self.context
     return has_permission(permission, context, self.request)
Exemple #52
0
 def ch(node):
     return [child for child in node.values()
             if child.in_navigation and
             has_permission('view', child, request)]
Exemple #53
0
 def children(self):
     return [NavigationNodeWrapper(
         child, self._request, self._item_mapping, self._item_to_children)
             for child in self._item_to_children[self.id]
             if has_permission('view', child, self._request)]