Example #1
0
def check_reply_subscriptions(event):
    request = event.request
    user_uri = 'acct:{}@{}'.format(event.user.username, request.domain)
    res = Subscriptions.get_templates_for_uri_and_type(user_uri,
                                                       types.REPLY_TYPE)
    if not len(res):
        create_subscription(event.request, user_uri, True)
Example #2
0
File: views.py Project: hylhero/h
def _update_subscription_data(request, subscription):
    """
    Update the subscriptions in the database from form data.

    Using data from the passed subscription struct, find a subscription in the
    database, and update it (if it belongs to the current logged-in user).
    """
    sub = Subscriptions.get_by_id(subscription['id'])
    if sub is None:
        return {
            'errors': {'subscriptions': _('Subscription not found')},
        }

    # If we're trying to update a subscription for anyone other than
    # the currently logged-in user, bail fast.
    #
    # The error message is deliberately identical to the one above, so
    # as not to leak any information about who which subscription ids
    # belong to.
    if sub.uri != request.authenticated_userid:
        return {
            'errors': {'subscriptions': _('Subscription not found')},
        }

    sub.active = subscription.get('active', True)

    request.session.flash(_('Changes saved!'), 'success')
Example #3
0
File: views.py Project: hylhero/h
 def unsubscribe(self):
     request = self.request
     subscription_id = request.GET['subscription_id']
     subscription = Subscriptions.get_by_id(subscription_id)
     if subscription:
         subscription.active = False
         return {}
     return {}
Example #4
0
 def profile(self):
     request = self.request
     user_id = request.authenticated_userid
     subscriptions = Subscriptions.get_subscriptions_for_uri(
         request,
         user_id
     )
     return {'model': {'subscriptions': subscriptions}}
Example #5
0
 def unsubscribe(self):
     request = self.request
     subscription_id = request.GET['subscription_id']
     subscription = Subscriptions.get_by_id(subscription_id)
     if subscription:
         if request.authenticated_userid != subscription.uri:
             raise httpexceptions.HTTPUnauthorized()
         subscription.active = False
         return {}
     return {}
Example #6
0
File: views.py Project: bradparks/h
 def profile(self):
     request = self.request
     model = {}
     userid = request.authenticated_userid
     if request.registry.feature('notification'):
         model['subscriptions'] = Subscriptions.get_subscriptions_for_uri(
             request,
             userid
         )
     return {'model': model}
Example #7
0
 def profile(self):
     request = self.request
     userid = request.authenticated_userid
     model = {}
     if userid:
         model["email"] = self.User.get_by_id(request, userid).email
     if request.registry.feature('notification'):
         model['subscriptions'] = Subscriptions.get_subscriptions_for_uri(
             request,
             userid
         )
     return {'model': model}
Example #8
0
def unsubscribe(request):
    token = request.matchdict['token']
    payload = request.registry.notification_serializer.loads(token)

    subscriptions = Subscriptions.get_templates_for_uri_and_type(
        payload['uri'], payload['type'])

    for s in subscriptions:
        if s.active:
            s.active = False
            request.db.add(s)

    return {}
Example #9
0
def generate_notifications(request, annotation, action):
    # Only send notifications when new annotations are created
    if action != 'create':
        return

    # If the annotation doesn't have a parent, we can't find its parent, or we
    # have no idea who the author of the parent is, then we can't send a
    # notification email.
    parent_id = annotation.parent_id
    if parent_id is None:
        return
    parent = storage.fetch_annotation(request, parent_id)
    if parent is None or 'user' not in parent:
        return

    # We don't send replies to the author of the parent unless they're going to
    # be able to read it. That means there must be some overlap between the set
    # of effective principals of the parent's author, and the read permissions
    # of the reply.
    child_read_permissions = annotation.get('permissions', {}).get('read', [])
    parent_principals = auth.effective_principals(parent['user'], request)
    read_principals = translate_annotation_principals(child_read_permissions)
    if not set(parent_principals).intersection(read_principals):
        return

    # Store the parent values as additional data
    data = {
        'parent': parent
    }

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

        # Validate annotation
        if check_conditions(annotation, data):
            try:
                subject, text, html, recipients = render_reply_notification(
                    request,
                    annotation,
                    parent)
                yield 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)
Example #10
0
def unsubscribe(request):
    token = request.matchdict['token']
    payload = request.registry.notification_serializer.loads(token)

    subscriptions = Subscriptions.get_templates_for_uri_and_type(
        payload['uri'],
        payload['type'])

    for s in subscriptions:
        if s.active:
            s.active = False
            request.db.add(s)

    return {}
Example #11
0
File: views.py Project: stuk88/h
    def profile(self):
        """
        Return a serialisation of the user's profile.

        For use by the frontend. Includes current email and subscriptions data.
        """
        request = self.request
        userid = request.authenticated_userid
        model = {}
        if userid:
            model["email"] = User.get_by_id(request, userid).email
        if request.feature("notification"):
            model["subscriptions"] = Subscriptions.get_subscriptions_for_uri(userid)
        return {"model": model}
Example #12
0
def generate_notifications(request, annotation, action):
    # Only send notifications when new annotations are created
    if action != 'create':
        return

    # If the annotation doesn't have a parent, we can't find its parent, or we
    # have no idea who the author of the parent is, then we can't send a
    # notification email.
    parent_id = annotation.parent_id
    if parent_id is None:
        return
    parent = storage.fetch_annotation(request, parent_id)
    if parent is None or 'user' not in parent:
        return

    # We don't send replies to the author of the parent unless they're going to
    # be able to read it. That means there must be some overlap between the set
    # of effective principals of the parent's author, and the read permissions
    # of the reply.
    child_read_permissions = annotation.get('permissions', {}).get('read', [])
    parent_principals = auth.effective_principals(parent['user'], request)
    read_principals = translate_annotation_principals(child_read_permissions)
    if not set(parent_principals).intersection(read_principals):
        return

    # Store the parent values as additional data
    data = {
        'parent': parent
    }

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

        # Validate annotation
        if check_conditions(annotation, data):
            try:
                subject, text, html, recipients = render_reply_notification(
                    request,
                    annotation,
                    parent)
                yield 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)
Example #13
0
File: views.py Project: ningyifan/h
def unsubscribe(request):
    if not request.feature("notification"):
        raise exc.HTTPNotFound()

    token = request.matchdict["token"]
    payload = request.registry.notification_serializer.loads(token)

    subscriptions = Subscriptions.get_templates_for_uri_and_type(payload["uri"], payload["type"])

    for s in subscriptions:
        if s.active:
            s.active = False
            request.db.add(s)

    return {}
Example #14
0
File: views.py Project: ningyifan/h
    def profile(self):
        """
        Return a serialisation of the user's profile.

        For use by the frontend. Includes current email and subscriptions data.
        """
        request = self.request
        userid = request.authenticated_userid
        model = {}
        if userid:
            model["email"] = User.get_by_userid(request.domain, userid).email
        if request.feature('notification'):
            model['subscriptions'] = Subscriptions.get_subscriptions_for_uri(
                userid)
        return {'model': model}
Example #15
0
    def edit_profile(self):
        try:
            appstruct = _validate_edit_profile_request(self.request)
        except _InvalidEditProfileRequestError as err:
            return dict(errors=err.errors)

        username = appstruct['username']
        pwd = appstruct['pwd']
        subscriptions = appstruct['subscriptions']

        if subscriptions:
            # Update the subscriptions table
            subs = json.loads(subscriptions)
            if username == subs['uri']:
                s = Subscriptions.get_by_id(self.request, subs['id'])
                if s:
                    s.active = subs['active']
                    self.db.add(s)
                    return {}
                else:
                    return dict(
                        errors=[
                            {'subscriptions': _('Non existing subscription')}
                        ],
                        code=404
                    )
            else:
                return dict(
                    errors=[{'username': _('Invalid username')}], code=400
                )

        # Password check
        user = self.User.get_user(self.request, username, pwd)
        if user:
            self.request.context = user
            response = super(ProfileController, self).edit_profile()

            # Add the user's email into the model dict that eventually gets
            # returned to the browser. This is needed so that the edit profile
            # forms can show the value of the user's current email.
            if self.request.authenticated_userid:
                user = h.accounts.models.User.get_by_id(
                    self.request, self.request.authenticated_userid)
                response.json = {"model": {"email": user.email}}

            return response
        else:
            return dict(errors=[{'pwd': _('Invalid password')}], code=401)
Example #16
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)
Example #17
0
def generate_notifications(request, annotation, action):
    # Only send notifications when new annotations are created
    if action != 'create':
        return

    # If the annotation doesn't have a parent, we can't find its parent, or we
    # have no idea who the author of the parent is, then we can't send a
    # notification email.
    parent_id = annotation.parent_id
    if parent_id is None:
        return
    parent = storage.fetch_annotation(request, parent_id)
    if parent is None or not annotation.userid:
        return

    # Don't send reply notifications to the author of the parent annotation if
    # the author doesn't have permission to read the reply.
    if not auth.has_permission(request, annotation, parent.userid, 'read'):
        return

    # Store the parent values as additional data
    data = {
        'parent': parent
    }

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

        # Validate annotation
        if check_conditions(annotation, data):
            try:
                subject, text, html, recipients = render_reply_notification(
                    request,
                    annotation,
                    parent)
                yield 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)
Example #18
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)
Example #19
0
def generate_notifications(request, annotation, action):
    # Only send notifications when new annotations are created
    if action != 'create':
        return

    # If the annotation doesn't have a parent, we can't find its parent, or we
    # have no idea who the author of the parent is, then we can't send a
    # notification email.
    parent_id = annotation.parent_id
    if parent_id is None:
        return
    parent = storage.fetch_annotation(request, parent_id)
    if parent is None or not annotation.userid:
        return

    # Don't send reply notifications to the author of the parent annotation if
    # the author doesn't have permission to read the reply.
    if not auth.has_permission(request, annotation, parent.userid, 'read'):
        return

    # Store the parent values as additional data
    data = {'parent': parent}

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

        # Validate annotation
        if check_conditions(annotation, data):
            try:
                subject, text, html, recipients = render_reply_notification(
                    request, annotation, parent)
                yield 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)
Example #20
0
File: views.py Project: bradparks/h
    def edit_profile(self):
        request = self.request
        schema = schemas.EditProfileSchema().bind(request=request)
        form = deform.Form(schema)

        try:
            appstruct = form.validate(request.POST.items())
        except deform.ValidationFailure as e:
            return dict(errors=e.error.children)

        username = appstruct['username']
        pwd = appstruct['pwd']
        subscriptions = appstruct['subscriptions']

        if subscriptions:
            # Update the subscriptions table
            subs = json.loads(subscriptions)
            if username == subs['uri']:
                s = Subscriptions.get_by_id(request, subs['id'])
                if s:
                    s.active = subs['active']
                    self.db.add(s)
                    return {}
                else:
                    return dict(
                        errors=[
                            {'subscriptions': _('Non existing subscription')}
                        ],
                        code=404
                    )
            else:
                return dict(
                    errors=[{'username': _('Invalid username')}], code=400
                )

        # Password check
        user = self.User.get_user(request, username, pwd)
        if user:
            request.context = user
            return super(ProfileController, self).edit_profile()
        else:
            return dict(errors=[{'pwd': _('Invalid password')}], code=401)
Example #21
0
    def edit_profile(self):
        request = self.request
        schema = schemas.EditProfileSchema().bind(request=request)
        form = deform.Form(schema)

        try:
            appstruct = form.validate(request.POST.items())
        except deform.ValidationFailure as e:
            return dict(errors=e.error.children)

        username = appstruct['username']
        pwd = appstruct['pwd']
        subscriptions = appstruct['subscriptions']

        if subscriptions:
            # Update the subscriptions table
            subs = json.loads(subscriptions)
            if username == subs['uri']:
                s = Subscriptions.get_by_id(request, subs['id'])
                if s:
                    s.active = subs['active']
                    self.db.add(s)
                    return {}
                else:
                    return dict(errors=[{
                        'subscriptions':
                        _('Non existing subscription')
                    }],
                                code=404)
            else:
                return dict(errors=[{
                    'username': _('Invalid username')
                }],
                            code=400)

        # Password check
        user = self.User.get_user(request, username, pwd)
        if user:
            request.context = user
            return super(ProfileController, self).edit_profile()
        else:
            return dict(errors=[{'pwd': _('Invalid password')}], code=401)
Example #22
0
def create_subscription(request, uri, active):
    subs = Subscriptions(uri=uri, type='reply', active=active)

    request.db.add(subs)
    request.db.flush()
Example #23
0
def create_subscription(request, uri, active):
    session = get_session(request)
    subs = Subscriptions(uri=uri, type=types.REPLY_TYPE, active=active)

    session.add(subs)
    session.flush()
Example #24
0
def create_subscription(request, uri, active):
    subs = Subscriptions(uri=uri, type=types.REPLY_TYPE, active=active)

    request.db.add(subs)
    request.db.flush()