Beispiel #1
0
    def _send_with_data(self, url, method='post', output='json', **kwargs):
        mapper = kwargs.get('mapper')
        if mapper:
            del kwargs['mapper']

        files = kwargs.get('files')
        data = kwargs.get('data')

        func = getattr(self.session, method.lower())

        req = None

        headers = {}
        if data:
            headers = {'content-type': 'application/json'}
            req = func(url, headers=headers, **kwargs)
        elif files:
            req = func(url, **kwargs)
        if 200 <= req.status_code < 300:
            if output is None:
                return req
            rv = getattr(req, output)
            if mapper:
                return mapper(escape_html(rv))
            elif callable(rv):
                return escape_html(rv())
            return rv
        else:
            self.handle_error(req)
Beispiel #2
0
    def _send_with_data(self, url, method='post', output='json', **kwargs):
        mapper = kwargs.get('mapper')
        if mapper:
            del kwargs['mapper']

        files = kwargs.get('files')
        data = kwargs.get('data')

        func = getattr(self.session, method.lower())

        req = None

        headers = {}
        if data:
            headers = {'content-type': 'application/json'}
            req = func(url, headers=headers, **kwargs)
        elif files:
            req = func(url, **kwargs)
        if 200 <= req.status_code < 300:
            if output is None:
                return req
            rv = getattr(req, output)
            if mapper:
                return mapper(escape_html(rv))
            elif callable(rv):
                return escape_html(rv())
            return rv
        else:
            self.handle_error(req)
Beispiel #3
0
def user_choose_mailing_lists(auth, **kwargs):
    """ Update mailing list subscription on user model and in mailchimp

        Example input:
        {
            "Open Science Framework General": true,
            ...
        }

    """
    user = auth.user
    json_data = escape_html(request.get_json())
    if json_data:
        for list_name, subscribe in json_data.items():
            # TO DO: change this to take in any potential non-mailchimp, something like try: update_subscription(), except IndexNotFound: update_mailchimp_subscription()
            if list_name == settings.OSF_HELP_LIST:
                update_osf_help_mails_subscription(user=user, subscribe=subscribe)
            else:
                update_mailchimp_subscription(user, list_name, subscribe)
    else:
        raise HTTPError(http_status.HTTP_400_BAD_REQUEST, data=dict(
            message_long="Must provide a dictionary of the format {'mailing list name': Boolean}")
        )

    user.save()
    all_mailing_lists = {}
    all_mailing_lists.update(user.mailchimp_mailing_lists)
    all_mailing_lists.update(user.osf_mailing_lists)
    return {'message': 'Successfully updated mailing lists', 'result': all_mailing_lists}, 200
Beispiel #4
0
    def update(self, revision, data, user=None):
        """Figshare does not support versioning.
        Always pass revision as None to avoid conflict.
        """
        self.name = data['name']
        self.materialized_path = data['materialized']
        self.save()

        version = FileVersion(identifier=None)
        version.update_metadata(data, save=False)

        # Draft files are not renderable
        if data['extra']['status'] == 'drafts':
            return (version, u'''
            <style>
            .file-download{{display: none;}}
            .file-share{{display: none;}}
            </style>
            <div class="alert alert-info" role="alert">
            The file "{name}" is still a draft on figshare. <br>
            To view it  on the OSF <a href="http://figshare.com/faqs">publish</a> it on figshare.
            </div>
            '''.format(name=escape_html(self.name)))

        return version
Beispiel #5
0
def user_choose_mailing_lists(auth, **kwargs):
    """ Update mailing list subscription on user model and in mailchimp

        Example input:
        {
            "Open Science Framework General": true,
            ...
        }

    """
    user = auth.user
    json_data = escape_html(request.get_json())
    if json_data:
        for list_name, subscribe in json_data.items():
            update_subscription(user, list_name, subscribe)
    else:
        raise HTTPError(
            http.BAD_REQUEST,
            data=dict(
                message_long=
                "Must provide a dictionary of the format {'mailing list name': Boolean}"
            ))

    user.save()
    return {
        'message': 'Successfully updated mailing lists',
        'result': user.mailing_lists
    }, 200
Beispiel #6
0
 def renderable_error(self):
     return u'''
     <div class="alert alert-info" role="alert">
     The file "{name}" is still a draft on figshare. <br>
     To view it  on the OSF <a href="http://figshare.com/faqs">publish</a> it on figshare.
     </div>
     '''.format(name=escape_html(self.file_guid.name))
Beispiel #7
0
def user_choose_mailing_lists(auth, **kwargs):
    """ Update mailing list subscription on user model and in mailchimp

        Example input:
        {
            "Open Science Framework General": true,
            ...
        }

    """
    user = auth.user
    json_data = escape_html(request.get_json())
    if json_data:
        for list_name, subscribe in json_data.items():
            # TO DO: change this to take in any potential non-mailchimp, something like try: update_subscription(), except IndexNotFound: update_mailchimp_subscription()
            if list_name == settings.OSF_HELP_LIST:
                update_osf_help_mails_subscription(user=user, subscribe=subscribe)
            else:
                update_mailchimp_subscription(user, list_name, subscribe)
    else:
        raise HTTPError(
            http.BAD_REQUEST,
            data=dict(message_long="Must provide a dictionary of the format {'mailing list name': Boolean}"),
        )

    user.save()
    all_mailing_lists = {}
    all_mailing_lists.update(user.mailchimp_mailing_lists)
    all_mailing_lists.update(user.osf_mailing_lists)
    return {"message": "Successfully updated mailing lists", "result": all_mailing_lists}, 200
Beispiel #8
0
    def update(self, revision, data, user=None):
        """Figshare does not support versioning.
        Always pass revision as None to avoid conflict.
        """
        self.name = data['name']
        self.materialized_path = data['materialized']
        self.save()

        version = FileVersion(identifier=None)
        version.update_metadata(data, save=False)

        # Draft files are not renderable
        if data['extra']['status'] == 'drafts':
            return (version, u'''
            <style>
            .file-download{{display: none;}}
            .file-share{{display: none;}}
            </style>
            <div class="alert alert-info" role="alert">
            The file "{name}" is still a draft on figshare. <br>
            To view it  on the OSF <a href="http://figshare.com/faqs">publish</a> it on figshare.
            </div>
            '''.format(name=escape_html(self.name)))

        return version
Beispiel #9
0
 def renderable_error(self):
     return u'''
     <div class="alert alert-info" role="alert">
     The file "{name}" is still a draft on figshare. <br>
     To view it  on the OSF <a href="http://figshare.com/faqs">publish</a> it on figshare.
     </div>
     '''.format(name=escape_html(self.file_guid.name))
Beispiel #10
0
def unserialize_names(**kwargs):
    user = kwargs['auth'].user
    json_data = escape_html(request.get_json())
    user.fullname = json_data.get('full')
    user.given_name = json_data.get('given')
    user.middle_names = json_data.get('middle')
    user.family_name = json_data.get('family')
    user.suffix = json_data.get('suffix')
    user.save()
Beispiel #11
0
def unserialize_names(**kwargs):
    user = kwargs["auth"].user
    json_data = escape_html(request.get_json())
    # json get can return None, use `or` here to ensure we always strip a string
    user.fullname = (json_data.get("full") or "").strip()
    user.given_name = (json_data.get("given") or "").strip()
    user.middle_names = (json_data.get("middle") or "").strip()
    user.family_name = (json_data.get("family") or "").strip()
    user.suffix = (json_data.get("suffix") or "").strip()
    user.save()
Beispiel #12
0
def unserialize_names(**kwargs):
    user = kwargs['auth'].user
    json_data = escape_html(request.get_json())
    # json get can return None, use `or` here to ensure we always strip a string
    user.fullname = (json_data.get('full') or '').strip()
    user.given_name = (json_data.get('given') or '').strip()
    user.middle_names = (json_data.get('middle') or '').strip()
    user.family_name = (json_data.get('family') or '').strip()
    user.suffix = (json_data.get('suffix') or '').strip()
    user.save()
Beispiel #13
0
def unserialize_names(**kwargs):
    user = kwargs['auth'].user
    json_data = escape_html(request.get_json())
    # json get can return None, use `or` here to ensure we always strip a string
    user.fullname = (json_data.get('full') or '').strip()
    user.given_name = (json_data.get('given') or '').strip()
    user.middle_names = (json_data.get('middle') or '').strip()
    user.family_name = (json_data.get('family') or '').strip()
    user.suffix = (json_data.get('suffix') or '').strip()
    user.save()
Beispiel #14
0
def unserialize_contents(field, func, auth):
    user = auth.user
    json_data = escape_html(request.get_json())
    setattr(
        user,
        field,
        [
            func(content)
            for content in json_data.get('contents', [])
        ]
    )
    user.save()
Beispiel #15
0
def unserialize_contents(field, func, auth):
    user = auth.user
    json_data = escape_html(request.get_json())
    contents = [func(content) for content in json_data.get('contents', [])]
    setattr(user, field, contents)
    user.save()

    if contents:
        saved_fields = {field: contents}
        request_headers = string_type_request_headers(request)
        user.check_spam(saved_fields=saved_fields,
                        request_headers=request_headers)
Beispiel #16
0
def unserialize_contents(field, func, auth):
    user = auth.user
    json_data = escape_html(request.get_json())
    setattr(
        user,
        field,
        [
            func(content)
            for content in json_data.get('contents', [])
        ]
    )
    user.save()
Beispiel #17
0
def unserialize_social(auth, **kwargs):

    verify_user_match(auth, **kwargs)

    user = auth.user
    json_data = escape_html(request.get_json())

    for soc in user.SOCIAL_FIELDS.keys():
        user.social[soc] = json_data.get(soc)

    try:
        user.save()
    except ValidationError as exc:
        raise HTTPError(http.BAD_REQUEST, data=dict(message_long=exc.args[0]))
Beispiel #18
0
def unserialize_social(auth, **kwargs):

    verify_user_match(auth, **kwargs)

    user = auth.user
    json_data = escape_html(request.get_json())

    for soc in user.SOCIAL_FIELDS.keys():
        user.social[soc] = json_data.get(soc)

    try:
        user.save()
    except ValidationError as exc:
        raise HTTPError(http.BAD_REQUEST, data=dict(message_long=exc.args[0]))
Beispiel #19
0
def create_badge(*args, **kwargs):
    badge_data = request.json
    awarder = kwargs['user_addon']

    if (not badge_data or not badge_data.get('badgeName') or
            not badge_data.get('description') or
            not badge_data.get('imageurl') or
            not badge_data.get('criteria')):

        raise HTTPError(http.BAD_REQUEST)
    try:
        id = Badge.create(awarder, escape_html(badge_data))._id
        return {'badgeid': id}, http.CREATED
    except IOError:
        raise HTTPError(http.BAD_REQUEST)
Beispiel #20
0
    def _send(self, url, method='get', output='json', cache=True, **kwargs):
        func = getattr(self.session, method.lower())

        # Send request
        req = func(url, **kwargs)

        # Get return value
        rv = None
        if 200 <= req.status_code < 300:
            if output is None:
                rv = req
            else:
                rv = getattr(req, output)
                if callable(rv):
                    rv = rv()
            return escape_html(rv)
        else:
            self.last_error = req.status_code
            return False
Beispiel #21
0
    def _send(self, url, method='get', output='json', cache=True, **kwargs):
        func = getattr(self.session, method.lower())

        # Send request
        req = func(url, **kwargs)

        # Get return value
        rv = None
        if 200 <= req.status_code < 300:
            if output is None:
                rv = req
            else:
                rv = getattr(req, output)
                if callable(rv):
                    rv = rv()
            return escape_html(rv)
        else:
            self.last_error = req.status_code
            return False
Beispiel #22
0
def unserialize_social(auth, **kwargs):

    verify_user_match(auth, **kwargs)

    user = auth.user
    json_data = escape_html(request.get_json())

    user.social['personal'] = json_data.get('personal')
    user.social['orcid'] = json_data.get('orcid')
    user.social['researcherId'] = json_data.get('researcherId')
    user.social['twitter'] = json_data.get('twitter')
    user.social['github'] = json_data.get('github')
    user.social['scholar'] = json_data.get('scholar')
    user.social['impactStory'] = json_data.get('impactStory')
    user.social['linkedIn'] = json_data.get('linkedIn')

    try:
        user.save()
    except ValidationError:
        raise HTTPError(http.BAD_REQUEST)
Beispiel #23
0
def meeting_hook():

    # Fail if not from Mailgun
    check_mailgun_headers()

    form = escape_html(request.form.to_dict())
    meeting, category = parse_mailgun_receiver(form)

    conf = Conference.find(Q('endpoint', 'iexact', meeting))
    if conf.count():
        conf = conf[0]
    else:
        raise HTTPError(http.NOT_FOUND)

    # Fail if not found or inactive
    # Note: Throw 406 to disable Mailgun retries
    try:
        if not conf.active:
            logger.error('Conference {0} is not active'.format(conf.endpoint))
            raise HTTPError(http.NOT_ACCEPTABLE)
    except KeyError:
        # TODO: Can this ever be reached?
        raise HTTPError(http.NOT_ACCEPTABLE)

    name, address = get_mailgun_from()

    # Add poster
    add_poster_by_email(
        conf=conf,
        recipient=form['recipient'],
        address=address,
        fullname=name,
        subject=get_mailgun_subject(form),
        message=form['stripped-text'],
        attachments=get_mailgun_attachments(),
        tags=[meeting],
        system_tags=[meeting],
        is_spam=check_mailgun_spam(),
    )
Beispiel #24
0
def user_choose_mailing_lists(auth, **kwargs):
    """ Update mailing list subscription on user model and in mailchimp

        Example input:
        {
            "Open Science Framework General": true,
            ...
        }

    """
    user = auth.user
    json_data = escape_html(request.get_json())
    if json_data:
        for list_name, subscribe in json_data.items():
            update_subscription(user, list_name, subscribe)
    else:
        raise HTTPError(http.BAD_REQUEST, data=dict(
            message_long="Must provide a dictionary of the format {'mailing list name': Boolean}")
        )

    user.save()
    return {'message': 'Successfully updated mailing lists', 'result': user.mailing_lists}, 200
Beispiel #25
0
def meeting_hook():

    # Fail if not from Mailgun
    check_mailgun_headers()

    form = escape_html(request.form.to_dict())
    meeting, category = parse_mailgun_receiver(form)

    conf = Conference.find(Q('endpoint', 'iexact', meeting))
    if conf.count():
        conf = conf[0]
    else:
        raise HTTPError(http.NOT_FOUND)

    # Fail if not found or inactive
    # Note: Throw 406 to disable Mailgun retries
    try:
        if not conf.active:
            raise HTTPError(http.NOT_ACCEPTABLE)
    except KeyError:
        raise HTTPError(http.NOT_ACCEPTABLE)

    name, address = get_mailgun_from()

    # Add poster
    add_poster_by_email(
        conf=conf,
        recipient=form['recipient'],
        address=address,
        fullname=name,
        subject=get_mailgun_subject(form),
        message=form['stripped-text'],
        attachments=get_mailgun_attachments(),
        tags=[meeting],
        system_tags=[meeting],
        is_spam=check_mailgun_spam(),
    )
Beispiel #26
0
 def renderable_error(self):
     return '''
     <div class="alert alert-info" role="alert">
     The file "{name}" is too large to be retrieved from Github for rendering.
     </div>
     '''.format(name=escape_html(self.file_guid.name))
Beispiel #27
0
def user_choose_addons(**kwargs):
    auth = kwargs["auth"]
    json_data = escape_html(request.get_json())
    auth.user.config_addons(json_data, auth)
Beispiel #28
0
 def renderable_error(self):
     return '''
     <div class="alert alert-info" role="alert">
     The file "{name}" is too large to be retrieved from Github for rendering.
     </div>
     '''.format(name=escape_html(self.file_guid.name))
Beispiel #29
0
def user_choose_addons(**kwargs):
    auth = kwargs['auth']
    json_data = escape_html(request.get_json())
    auth.user.config_addons(json_data, auth)