def test_ongoing_meeting_upcoming_ai(self):
     m = self._fixture()
     security.unrestricted_wf_transition_to(m, 'ongoing')
     security.unrestricted_wf_transition_to(m['ai'], 'upcoming')
     self.assertEqual(principals_allowed_by_permission(m['ai']['d'], security.VIEW), admin | viewer | moderator)
     self.assertEqual(principals_allowed_by_permission(m['ai']['d'], security.EDIT), admin | moderator)
     self.assertEqual(principals_allowed_by_permission(m['ai']['d'], security.DELETE), admin | moderator | owner)
Exemple #2
0
def test_topic_comment_permission(text_topic):
    """Ensure authed users have comment perms before deletion, not after."""
    principals = principals_allowed_by_permission(text_topic, 'comment')
    assert Authenticated in principals

    text_topic.is_deleted = True

    principals = principals_allowed_by_permission(text_topic, 'comment')
    assert Authenticated not in principals
Exemple #3
0
def test_deleted_topic_permissions_removed(topic):
    """Ensure that deleted topics lose all permissions except "view"."""
    topic.is_deleted = True

    assert principals_allowed_by_permission(topic, "view") == {Everyone}

    all_permissions = [
        perm for (_, _, perm) in topic.__acl__() if perm != "view"
    ]
    for permission in all_permissions:
        assert not principals_allowed_by_permission(topic, permission)
 def test_upcoming_meeting_private_ai(self):
     m = self._fixture()
     self.assertEqual(
         principals_allowed_by_permission(m['ai']['d'], security.VIEW),
         admin | moderator)
     self.assertEqual(
         principals_allowed_by_permission(m['ai']['d'], security.EDIT),
         admin | moderator)
     self.assertEqual(
         principals_allowed_by_permission(m['ai']['d'], security.DELETE),
         admin | moderator)
 def test_upcoming_meeting_upcoming_ai(self):
     m = self._fixture()
     security.unrestricted_wf_transition_to(m['ai'], 'upcoming')
     self.assertEqual(
         principals_allowed_by_permission(m['ai']['d'], security.VIEW),
         admin | viewer | moderator)
     self.assertEqual(
         principals_allowed_by_permission(m['ai']['d'], security.EDIT),
         admin | moderator)
     self.assertEqual(
         principals_allowed_by_permission(m['ai']['d'], security.DELETE),
         admin | moderator | owner)
Exemple #6
0
def test_removed_comment_view_permission(comment):
    """Ensure a removed comment can only be viewed by certain users."""
    comment.is_removed = True
    allowed = principals_allowed_by_permission(comment, "view")
    granted = _principals_granted_permission("comment.remove",
                                             comment.topic.group_id)
    assert allowed == granted | {comment.user_id}
Exemple #7
0
def test_deleted_comment_permissions_removed(comment):
    """Ensure that deleted comments lose all of the permissions."""
    comment.is_deleted = True

    all_permissions = [perm for (_, _, perm) in comment.__acl__()]
    for permission in all_permissions:
        assert not principals_allowed_by_permission(comment, permission)
Exemple #8
0
def outstanding_principals(permission, context, request):
    """Returns a list of sets of principals, where the attainment of all of the
    principals in any one of the sets would be sufficient to grant the current
    user (``request.user``) the `permission` in the given `context`."""

    # TODO be able to determine a context based on a route name

    if has_permission(permission, context, request):
        return []

    principals = principals_allowed_by_permission(context, permission)
    if not principals:
        # the permission must not exist at all within this context
        return ['__unattainable__']

    effective = set(effective_principals(request))
    outstanding = []

    for p in principals:
        if p in TRUST_MAP:
            for alternative_principals in TRUST_MAP[p]:
                diff = set(alternative_principals) - effective
                if len(diff) > 0 and 'auth:insecure' not in diff:
                    outstanding.append(diff)
        else:
            outstanding.append(set([p]))

    return outstanding
Exemple #9
0
def get_recepients(context, permission="state_change"):
    """
    Get a list of principals that have the permission in context and a email.

    :param context: Object for that the permission is needed.
    :type context: :class:`kotti.resources.Node`

    :param permission:
    :type permission: str

    :result: List of principals.
    :rtype: set
    """

    principal_db = get_principals()

    recepients = []
    for p in principals_allowed_by_permission(context, permission):
        # set(['role:owner', 'role:editor'])
        for principal in principal_db.search(groups=u'*%s*' % p).all():
            recepients.append(principal)
        for principal in map_principals_with_local_roles(context):
            # [
            #   (
            #       <Principal u'disko'>,
            #       (
            #           [u'role:owner', u'group:admins', u'role:admin'],
            #           [u'role:owner', u'group:admins', u'role:admin']))]
            if p in principal[1][0] or p in principal[1][1]:
                recepients.append(principal[0])

    return set([r for r in recepients if r.email])
Exemple #10
0
def allowed(context, request):
    from pyramid.security import principals_allowed_by_permission
    permission = request.params.get('permission', 'view')
    return {
        'has_permission': bool(request.has_permission(permission, context)),
        'principals_allowed_by_permission': principals_allowed_by_permission(context, permission),
    }
Exemple #11
0
def outstanding_principals(permission, context, request):
    """Returns a list of sets of principals, where the attainment of all of the
    principals in any one of the sets would be sufficient to grant the current
    user (``request.user``) the `permission` in the given `context`."""

    # TODO be able to determine a context based on a route name

    if has_permission(permission, context, request):
        return []

    principals = principals_allowed_by_permission(context, permission)
    if not principals:
        # the permission must not exist at all within this context
        return ['__unattainable__']

    effective = set(effective_principals(request))
    outstanding = []

    for p in principals:
        if p in TRUST_MAP:
            for alternative_principals in TRUST_MAP[p]:
                diff = set(alternative_principals) - effective
                if len(diff) > 0 and 'auth:insecure' not in diff:
                    outstanding.append(diff)
        else:
            outstanding.append(set([p]))

    return outstanding
Exemple #12
0
def test_banned_user_no_message_permission():
    """Ensure nobody can message a banned user."""
    banned_user = User("Banned_User", "password")
    banned_user.is_banned = True

    principals = principals_allowed_by_permission(banned_user, "message")
    assert not principals
Exemple #13
0
def test_deleted_user_no_message_permission():
    """Ensure nobody can message a deleted user."""
    deleted_user = User("Deleted_User", "password")
    deleted_user.is_deleted = True

    principals = principals_allowed_by_permission(deleted_user, "message")
    assert not principals
Exemple #14
0
def get_allowed_to_view(object, default):
    principals = principals_allowed_by_permission(object, 'view')
    if not principals:
        # An empty value tells the catalog to match anything, whereas when
        # there are no principals with permission to view we want for there
        # to be no matches.
        principals = ['NO ONE no way NO HOW',]
    return principals
Exemple #15
0
def get_allowed_to_view(object, default):
    principals = principals_allowed_by_permission(object, 'view')
    if not principals:
        # An empty value tells the catalog to match anything, whereas when
        # there are no principals with permission to view we want for there
        # to be no matches.
        principals = ['NO ONE no way NO HOW',]
    return principals
Exemple #16
0
def test_comment_reply_locked_thread_permission(comment):
    """Ensure that only users with lock permission can reply in locked threads."""
    comment.topic.is_locked = True

    allowed = principals_allowed_by_permission(comment, "reply")
    granted = _principals_granted_permission("topic.lock",
                                             comment.topic.group_id)
    assert allowed == granted
Exemple #17
0
def item_index_data(context, request):
    uuid = str(context.uuid)
    properties = context.upgrade_properties()
    links = context.links(properties)
    unique_keys = context.unique_keys(properties)

    principals_allowed = {}
    for permission in ('view', 'edit', 'audit'):
        p = principals_allowed_by_permission(context, permission)
        if p is Everyone:
            p = [Everyone]
        principals_allowed[permission] = sorted(p)

    path = resource_path(context)
    paths = {path}
    collection = context.collection

    if collection.unique_key in unique_keys:
        paths.update(
            resource_path(collection, key)
            for key in unique_keys[collection.unique_key])

    for base in (collection, request.root):
        for key_name in ('accession', 'alias'):
            if key_name not in unique_keys:
                continue
            paths.add(resource_path(base, uuid))
            paths.update(
                resource_path(base, key)
                for key in unique_keys[key_name])

    path = path + '/'
    embedded = request.embed(path, '@@embedded')
    object = request.embed(path, '@@object')
    audit = request.embed(path, '@@audit')['audit']

    document = {
        'audit': audit,
        'embedded': embedded,
        'embedded_uuids': sorted(request._embedded_uuids),
        'item_type': context.item_type,
        'linked_uuids': sorted(request._linked_uuids),
        'links': links,
        'object': object,
        'paths': sorted(paths),
        'principals_allowed': principals_allowed,
        'properties': properties,
        'propsheets': {
            name: context.propsheets[name]
            for name in context.propsheets.keys() if name != ''
        },
        'tid': context.tid,
        'unique_keys': unique_keys,
        'uuid': uuid,
    }

    return document
Exemple #18
0
def get_allowed_to_view(object, default):
    """ Return a list of all roles allowed to view this object. """
    principals = principals_allowed_by_permission(object, VIEW)
    if not principals:
        # An empty value tells the catalog to match anything, whereas when
        # there are no principals with permission to view we want for there
        # to be no matches.
        principals = [NEVER_EVER_PRINCIPAL,]
    return principals
def allowed(context, request):
    from pyramid.security import principals_allowed_by_permission
    permission = request.params.get('permission', 'view')
    return {
        'has_permission':
        bool(request.has_permission(permission, context)),
        'principals_allowed_by_permission':
        principals_allowed_by_permission(context, permission),
    }
Exemple #20
0
def item_index_data(context, request):
    uuid = str(context.uuid)
    properties = context.upgrade_properties()
    links = context.links(properties)
    unique_keys = context.unique_keys(properties)

    principals_allowed = {}
    for permission in ('view', 'edit', 'audit'):
        p = principals_allowed_by_permission(context, permission)
        if p is Everyone:
            p = [Everyone]
        principals_allowed[permission] = sorted(p)

    path = resource_path(context)
    paths = {path}
    collection = context.collection

    if collection.unique_key in unique_keys:
        paths.update(
            resource_path(collection, key)
            for key in unique_keys[collection.unique_key])

    for base in (collection, request.root):
        for key_name in ('accession', 'alias'):
            if key_name not in unique_keys:
                continue
            paths.add(resource_path(base, uuid))
            paths.update(
                resource_path(base, key) for key in unique_keys[key_name])

    path = path + '/'
    embedded = request.embed(path, '@@embedded')
    object = request.embed(path, '@@object')
    audit = request.embed(path, '@@audit')['audit']

    document = {
        'audit': audit,
        'embedded': embedded,
        'embedded_uuids': sorted(request._embedded_uuids),
        'item_type': context.item_type,
        'linked_uuids': sorted(request._linked_uuids),
        'links': links,
        'object': object,
        'paths': sorted(paths),
        'principals_allowed': principals_allowed,
        'properties': properties,
        'propsheets': {
            name: context.propsheets[name]
            for name in context.propsheets.keys() if name != ''
        },
        'tid': context.tid,
        'unique_keys': unique_keys,
        'uuid': uuid,
    }

    return document
Exemple #21
0
def authorize(request, annotation, action, user=None):
    annotation = wrap_annotation(request, annotation)
    allowed = security.principals_allowed_by_permission(annotation, action)

    if user is None:
        principals = request.effective_principals
    else:
        principals = [security.Everyone, security.Authenticated, user.id]

    return set(allowed) & set(principals) != set()
Exemple #22
0
def get_allowed_to_view(obj, default):
    """ Useful as a KeywordIndex discriminator.  Looks up the principals
    allowed by the ``view`` permission against the object and indexes them if
    any are found."""
    principals = principals_allowed_by_permission(obj, 'view')
    if not principals:
        # An empty value tells the catalog to match anything, whereas when
        # there are no principals with permission to view we want for there
        # to be no matches.
        principals = [NoWay()]
    return principals
def get_allowed_to_view(obj, default):
    """ Useful as a KeywordIndex discriminator.  Looks up the principals
    allowed by the ``view`` permission against the object and indexes them if
    any are found."""
    principals = principals_allowed_by_permission(obj, 'view')
    if not principals:
        # An empty value tells the catalog to match anything, whereas when
        # there are no principals with permission to view we want for there
        # to be no matches.
        principals = [NoWay()]
    return principals
Exemple #24
0
def get_allowed_to_view(obj, default):
    """ Return a list of all roles allowed to view this object. """
    principals = principals_allowed_by_permission(obj, VIEW)
    if not principals:
        # An empty value tells the catalog to match anything, whereas when
        # there are no principals with permission to view we want for there
        # to be no matches.
        principals = [
            NEVER_EVER_PRINCIPAL,
        ]
    return principals
Exemple #25
0
def _generate_annotation_event(message, socket, annotation, user_nipsad,
                               group_service, formatters):
    """
    Get message about annotation event `message` to be sent to `socket`.

    Inspects the embedded annotation event and decides whether or not the
    passed socket should receive notification of the event.

    Returns None if the socket should not receive any message about this
    annotation event, otherwise a dict containing information about the event.
    """
    action = message["action"]

    if action == "read":
        return None

    if message["src_client_id"] == socket.client_id:
        return None

    # Don't sent annotations from NIPSA'd users to anyone other than that
    # user.
    if user_nipsad and socket.authenticated_userid != annotation.userid:
        return None

    # The `prepare` function sets the active registry which is an implicit
    # dependency of some of the authorization logic used to look up annotation
    # and group permissions.
    with pyramid.scripting.prepare(registry=socket.registry):
        notification = {
            "type": "annotation-notification",
            "options": {
                "action": action
            },
        }

        base_url = socket.registry.settings.get("h.app_url",
                                                "http://localhost:5000")
        links_service = LinksService(base_url, socket.registry)
        resource = AnnotationContext(annotation, group_service, links_service)

        # Check whether client is authorized to read this annotation.
        read_principals = principals_allowed_by_permission(resource, "read")
        if not set(read_principals).intersection(socket.effective_principals):
            return None

        serialized = presenters.AnnotationJSONPresenter(
            resource, formatters=formatters).asdict()

        notification["payload"] = [serialized]
        if action == "delete":
            notification["payload"] = [{"id": annotation.id}]
        return notification
Exemple #26
0
def item_index_data(context, request):
    uuid = str(context.uuid)
    properties = context.upgrade_properties()
    links = context.links(properties)
    unique_keys = context.unique_keys(properties)

    principals_allowed = {}
    for permission in ("view", "edit", "audit"):
        p = principals_allowed_by_permission(context, permission)
        if p is Everyone:
            p = [Everyone]
        principals_allowed[permission] = sorted(p)

    path = resource_path(context)
    paths = {path}
    collection = context.collection

    if collection.unique_key in unique_keys:
        paths.update(resource_path(collection, key) for key in unique_keys[collection.unique_key])

    for base in (collection, request.root):
        for key_name in ("accession", "alias"):
            if key_name not in unique_keys:
                continue
            paths.add(resource_path(base, uuid))
            paths.update(resource_path(base, key) for key in unique_keys[key_name])

    path = path + "/"
    embedded = request.embed(path, "@@embedded")
    object = request.embed(path, "@@object")
    audit = request.embed(path, "@@audit")["audit"]

    document = {
        "audit": audit,
        "embedded": embedded,
        "embedded_uuids": sorted(request._embedded_uuids),
        "item_type": context.type_info.item_type,
        "linked_uuids": sorted(request._linked_uuids),
        "links": links,
        "object": object,
        "paths": sorted(paths),
        "principals_allowed": principals_allowed,
        "properties": properties,
        "propsheets": {name: context.propsheets[name] for name in context.propsheets.keys() if name != ""},
        "tid": context.tid,
        "unique_keys": unique_keys,
        "uuid": uuid,
    }

    return document
Exemple #27
0
def authorize(request, annotation, action, user=None):
    annotation = wrap_annotation(request, annotation)
    allowed = security.principals_allowed_by_permission(annotation, action)

    if user is None:
        principals = request.session.get('personas', [])
    else:
        principals = [user.id]

    if len(principals):
        principals.append(security.Authenticated)

    principals.append(security.Everyone)

    return set(allowed) & set(principals) != set()
Exemple #28
0
Fichier : api.py Projet : ercchy/h
def authorize(request, annotation, action, user=None):
    annotation = wrap_annotation(request, annotation)
    allowed = security.principals_allowed_by_permission(annotation, action)

    if user is None:
        principals = request.session.get('personas', [])
    else:
        principals = [user.id]

    if len(principals):
        principals.append(security.Authenticated)

    principals.append(security.Everyone)

    return set(allowed) & set(principals) != set()
Exemple #29
0
def calc_principals(context):
    principals_allowed = {}
    for permission in ('view', 'edit', 'audit'):
        principals = principals_allowed_by_permission(context, permission)
        if principals is Everyone:
            principals = [Everyone]
        elif Everyone in principals:
            principals = [Everyone]
        elif Authenticated in principals:
            principals = [Authenticated]
        # Filter our roles
        principals_allowed[permission] = [
            p for p in sorted(principals) if not p.startswith('role.')
        ]
    return principals_allowed
Exemple #30
0
def handle_annotation_event(message, sockets, request, session):
    id_ = message["annotation_id"]
    annotation = storage.fetch_annotation(session, id_)

    if annotation is None:
        log.warning("received annotation event for missing annotation: %s",
                    id_)
        return

    # Find connected clients which are interested in this annotation.
    matching_sockets = SocketFilter.matching(sockets, annotation, session)

    try:
        # Check to see if the generator has any items
        first_socket = next(matching_sockets)
    except StopIteration:
        # Nothing matched
        return

    # Create a generator which has the first socket back again
    matching_sockets = chain(  # pylint: disable=redefined-variable-type
        (first_socket, ), matching_sockets)

    resource = AnnotationNotificationContext(
        annotation,
        group_service=request.find_service(IGroupService),
        links_service=request.find_service(name="links"),
    )
    read_principals = principals_allowed_by_permission(resource, "read")
    reply = _generate_annotation_event(session, request, message, resource)

    annotator_nipsad = request.find_service(name="nipsa").is_flagged(
        annotation.userid)

    for socket in matching_sockets:
        # Don't send notifications back to the person who sent them
        if message["src_client_id"] == socket.client_id:
            continue

        # Only send NIPSA'd annotations to the author
        if annotator_nipsad and socket.authenticated_userid != annotation.userid:
            continue

        # Check whether client is authorized to read this annotation.
        if not set(read_principals).intersection(socket.effective_principals):
            continue

        socket.send_json(reply)
Exemple #31
0
def _getInfo(profile, content):
    community = context = find_community(content)
    if context is None:
        # try for content inside a profile
        context = find_interface(content, IProfile)
    if context is None:
        context_name = context_url = None
    else:
        context_name = context.title
        context_url = resource_path(context)
    tagger = find_tags(content)
    if tagger is not None:
        cloud = list(tagger.getCloud(items=(content.docid,)))
        tag_counts = sorted(cloud, key=lambda x: x[1], reverse=True)[:3]
        tags = [x[0] for x in tag_counts]
    else:
        tags = ()
    content_type = get_content_type(content)
    desc = getattr(content, "description", "")
    short = len(desc) > 80 and "%s..." % desc[:80] or desc
    if IPosts.providedBy(content):
        comment_count = len(content.get("comments", ()))
    else:
        comment_count = False
    content_creator = profile.__name__
    if IComment.providedBy(content):
        # my content filter needs to know if a comment was made inside my post
        content_creator = content.__parent__.__parent__.creator
    return {
        "content_type": content_type.getTaggedValue("name"),
        "userid": profile.__name__,
        "context_name": context_name,
        "context_url": context_url,
        "content_creator": content_creator,
        "url": resource_path(content),
        "title": content.title,
        "description": desc,
        "short_description": short,
        "allowed": principals_allowed_by_permission(content, "view"),
        "comment_count": comment_count,
        "tags": tags,  # XXX
        "author": profile.title,
        "profile_url": "/profiles/%s" % profile.__name__,
        "thumbnail": "/profiles/%s/profile_thumbnail" % profile.__name__,
        "timestamp": _NOW(),
    }
Exemple #32
0
def _getInfo(profile, content):
    community = context = find_community(content)
    if context is None:
        # try for content inside a profile
        context = find_interface(content, IProfile)
    if context is None:
        context_name = context_url = None
    else:
        context_name = context.title
        context_url = resource_path(context)
    tagger = find_tags(content)
    if tagger is not None:
        cloud = list(tagger.getCloud(items=(content.docid,)))
        tag_counts = sorted(cloud, key=lambda x: x[1], reverse=True)[:3]
        tags = [x[0] for x in tag_counts]
    else:
        tags = ()
    content_type = get_content_type(content)
    desc = getattr(content, 'description', '')
    short = len(desc) > 256 and '%s...' % desc[:256] or desc
    if IPosts.providedBy(content):
        comment_count = len(content.get('comments', ()))
    else:
        comment_count = False
    content_creator = profile.__name__
    if IComment.providedBy(content):
        # my content filter needs to know if a comment was made inside my post
        content_creator = content.__parent__.__parent__.creator
    return {'content_type': content_type.getTaggedValue('name'),
            'userid': profile.__name__,
            'context_name': context_name,
            'context_url': context_url,
            'content_creator': content_creator,
            'url': resource_path(content),
            'title': content.title,
            'description': desc,
            'short_description': short,
            'allowed':
                principals_allowed_by_permission(content, 'view'),
            'comment_count': comment_count,
            'tags': tags,                 #XXX
            'author': profile.title,
            'profile_url': '/profiles/%s' % profile.__name__,
            'thumbnail': '/profiles/%s/profile_thumbnail' % profile.__name__,
            'timestamp': _NOW(),
           }
Exemple #33
0
def send_notifications(event):
    # Extract data
    action = event.action
    request = event.request
    annotation = event.annotation

    # And for them we need only the creation action
    if action != 'create':
        return

    # Check for authorization. Send notification only for public annotation
    # XXX: This will be changed and fine grained when
    # user groups will be introduced
    if Everyone not in principals_allowed_by_permission(annotation, 'read'):
        return

    # Store the parent values as additional data
    data = {
        'parent': parent_values(annotation)
    }

    subscriptions = Subscriptions.get_active_subscriptions_for_a_type(
        request,
        types.REPLY_TYPE
    )
    for subscription in subscriptions:
        data['subscription'] = subscription.__json__(request)

        # Validate annotation
        if check_conditions(annotation, data):
            try:
                # Render e-mail parts
                tmap = create_template_map(request, annotation, data)
                text = render(TXT_TEMPLATE, tmap, request).strip()
                html = render(HTML_TEMPLATE, tmap, request).strip()
                subject = render(SUBJECT_TEMPLATE, tmap, request).strip()
                recipients = get_recipients(request, data)
                send_email(request, subject, text, html, recipients)
            # ToDo: proper exception handling here
            except TemplateRenderException:
                log.exception('Failed to render subscription'
                              ' template %s', subscription)
            except:
                log.exception('Unknown error when trying to render'
                              ' subscription template %s', subscription)
Exemple #34
0
def domain_notification(event):
    if event.action != 'create':
        return
    try:
        annotation = event.annotation
        request = event.request

        # Check for authorization. Send notification only for public annotation
        # XXX: This will be changed and fine grained when
        # user groups will be introduced
        allowed = principals_allowed_by_permission(annotation, 'read')
        if Everyone not in allowed:
            return

        uri = annotation['uri']
        # TODO: Fetching the page should be done via a webproxy
        r = requests.get(uri)
        emails = get_document_owners(r.text)

        # Now send the notifications
        url_struct = urlparse(annotation['uri'])
        domain = url_struct.hostname or url_struct.path
        domain = re.sub(r'^www.', '', domain)

        for email in emails:
            # Domain matching
            mail_domain = email.split('@')[-1]
            if mail_domain == domain:
                try:
                    # Render e-mail parts
                    tmap = create_template_map(request, annotation)
                    text = render(TXT_TEMPLATE, tmap, request).strip()
                    html = render(HTML_TEMPLATE, tmap, request).strip()
                    subject = render(SUBJECT_TEMPLATE, tmap, request).strip()
                    send_email(request, subject, text, html, [email])

                # ToDo: proper exception handling here
                except TemplateRenderException:
                    log.exception('Failed to render domain-mailer template')
                except:
                    log.exception(
                        'Unknown error when trying to render'
                        'domain-mailer template')
    except:
        log.exception('Problem with domain notification')
Exemple #35
0
def send_notifications(event):
    # Extract data
    action = event.action
    request = event.request
    annotation = event.annotation

    # And for them we need only the creation action
    if action != 'create':
        return

    # Check for authorization. Send notification only for public annotation
    # XXX: This will be changed and fine grained when
    # user groups will be introduced
    if Everyone not in principals_allowed_by_permission(annotation, 'read'):
        return

    # Store the parent values as additional data
    data = {'parent': parent_values(annotation)}

    subscriptions = Subscriptions.get_active_subscriptions_for_a_type(
        request, types.REPLY_TYPE)
    for subscription in subscriptions:
        data['subscription'] = subscription.__json__(request)

        # Validate annotation
        if check_conditions(annotation, data):
            try:
                # Render e-mail parts
                tmap = create_template_map(request, annotation, data)
                text = render(TXT_TEMPLATE, tmap, request).strip()
                html = render(HTML_TEMPLATE, tmap, request).strip()
                subject = render(SUBJECT_TEMPLATE, tmap, request).strip()
                recipients = get_recipients(request, data)
                send_email(request, subject, text, html, recipients)
            # ToDo: proper exception handling here
            except TemplateRenderException:
                log.exception('Failed to render subscription'
                              ' template %s', subscription)
            except:
                log.exception(
                    'Unknown error when trying to render'
                    ' subscription template %s', subscription)
Exemple #36
0
    def __call__(self, resource, default):
        permissions = self.permissions

        if permissions is None:
            registry = get_current_registry() # XXX lame
            permissions = get_all_permissions(registry)

        values = []

        for permission in permissions:
            principals = principals_allowed_by_permission(resource, permission)
            values.extend([(principal, permission) for principal in principals])

        if not values:
            # An empty value tells the catalog to match anything, whereas
            # when there are no principals with permission to view we
            # want for there to be no matches.
            values = [(NoWay, NoWay)]
            
        return values
    def __call__(self, resource, default):
        permissions = self.permissions

        if permissions is None:
            registry = get_current_registry()  # XXX lame
            permissions = get_all_permissions(registry)

        values = []

        for permission in permissions:
            principal_ids = principals_allowed_by_permission(
                resource, permission)
            for principal_id in principal_ids:
                principal_repr = get_principal_repr(principal_id)
                values.append((principal_repr, permission))

        if not values:
            return default

        return values
Exemple #38
0
    def permissions(self):
        """
        Return a permissions dict for the given annotation.

        Converts our simple internal annotation storage format into the legacy
        complex permissions dict format that is still used in some places.

        """
        read = self.annotation.userid
        if self.annotation.shared:
            read = 'group:{}'.format(self.annotation.groupid)

            principals = security.principals_allowed_by_permission(
                    self.annotation_resource, 'read')
            if security.Everyone in principals:
                read = 'group:__world__'

        return {'read': [read],
                'admin': [self.annotation.userid],
                'update': [self.annotation.userid],
                'delete': [self.annotation.userid]}
Exemple #39
0
    def __call__(self, wrapper, default):
        content = wrapper.content
        permissions = self.permissions

        if permissions is None:
            registry = get_current_registry()
            permissions = get_all_permissions(registry)

        values = []

        for permission in permissions:
            principals = principals_allowed_by_permission(content, permission)
            values.extend([(principal, permission)
                           for principal in principals])

        if not values:
            # An empty value tells the catalog to match anything, whereas
            # when there are no principals with permission to view we
            # want for there to be no matches.
            values = [(NoWay, NoWay)]

        return values
Exemple #40
0
    def __call__(self, resource, default):
        permissions = self.permissions

        if permissions is None:
            registry = get_current_registry() # XXX lame
            permissions = get_all_permissions(registry)

        values = []

        for permission in permissions:
            principal_ids = principals_allowed_by_permission(
                resource,
                permission
                )
            for principal_id in principal_ids:
                principal_repr = get_principal_repr(principal_id)
                values.append((principal_repr, permission))

        if not values:
            return default
            
        return values
Exemple #41
0
 def test_delete(self):
     obj = self._cut()
     self.assertEqual(principals_allowed_by_permission(obj, security.DELETE), admin)
Exemple #42
0
 def test_delete(self):
     obj = self._cut()
     self.assertEqual(
         principals_allowed_by_permission(obj, security.DELETE), admin)
 def test_upcoming_meeting_private_ai(self):
     m = self._fixture()
     self.assertEqual(principals_allowed_by_permission(m['ai']['d'], security.VIEW), admin | moderator)
     self.assertEqual(principals_allowed_by_permission(m['ai']['d'], security.EDIT), admin | moderator)
     self.assertEqual(principals_allowed_by_permission(m['ai']['d'], security.DELETE), admin | moderator)
Exemple #44
0
 def _group_principals(group):
     if group is None:
         return []
     return principals_allowed_by_permission(group, 'read')
 def test_add_agenda_template(self):
     obj = self._cut()
     self.assertEqual(principals_allowed_by_permission(obj, security.ADD_AGENDA_TEMPLATE), admin)
Exemple #46
0
 def test_view(self):
     obj = self._cut()
     self.assertEqual(principals_allowed_by_permission(obj, security.VIEW),
                      admin | owner)
Exemple #47
0
 def _group_principals(group, principal):
     if group is None:
         return []
     principals = principals_allowed_by_permission(group, principal)
     return principals
Exemple #48
0
 def test_edit(self):
     obj = self._cut()
     self.assertEqual(principals_allowed_by_permission(obj, security.EDIT), admin | owner)
Exemple #49
0
 def test_view(self):
     obj = self._cut()
     self.assertEqual(principals_allowed_by_permission(obj, security.VIEW), admin | owner)
Exemple #50
0
 def test_add_user(self):
     obj = self._cut()
     self.assertEqual(principals_allowed_by_permission(obj, security.ADD_USER), admin)
Exemple #51
0
 def _callFUT(self, *arg):
     from pyramid.security import principals_allowed_by_permission
     return principals_allowed_by_permission(*arg)
Exemple #52
0
 def test_change_password(self):
     obj = self._cut()
     self.assertEqual(
         principals_allowed_by_permission(obj, security.CHANGE_PASSWORD),
         admin | owner)
Exemple #53
0
 def test_manage_server(self):
     obj = self._cut()
     self.assertEqual(principals_allowed_by_permission(obj, security.MANAGE_SERVER), admin)
Exemple #54
0
 def test_edit(self):
     obj = self._cut()
     self.assertEqual(principals_allowed_by_permission(obj, security.EDIT),
                      admin | owner)
Exemple #55
0
 def test_change_password(self):
     obj = self._cut()
     self.assertEqual(principals_allowed_by_permission(obj, security.CHANGE_PASSWORD), admin | owner)
Exemple #56
0
 def test_manage_server(self):
     obj = self._cut()
     self.assertEqual(
         principals_allowed_by_permission(obj, security.MANAGE_SERVER),
         admin)
Exemple #57
0
 def test_delete(self):
     obj = self._cut()
     #Currently, there's no way to delete a user.
     #This has to do with ownership, we need a way to clean it up if we want to remove users.
     self.assertEqual(principals_allowed_by_permission(obj, security.DELETE), set())