Esempio n. 1
0
 def test_webhook_handler_admin(self):
     """Test WEBHOOK view works for admin."""
     # Admin
     self.register()
     self.signin()
     self.signout()
     # User
     self.register(name="user", password="******")
     self.signin(email="*****@*****.**", password="******")
     owner = user_repo.get(2)
     self.signout()
     # Access as admin
     self.signin()
     project = ProjectFactory.create(owner=owner)
     url = "/project/%s/webhook" % project.short_name
     res = self.app.get(url)
     assert res.status_code == 200, res.status_code
     assert "Created" in res.data
     assert "Payload" in res.data
     url = "/project/%s/webhook?all=true" % project.short_name
     res = self.app.get(url)
     assert res.status_code == 200, res.status_code
     assert "Created" in res.data
     assert "Payload" in res.data
     url = "/project/%s/webhook?failed=true" % project.short_name
     res = self.app.get(url)
     assert res.status_code == 200, res.status_code
     assert "Created" in res.data
     assert "Payload" in res.data
Esempio n. 2
0
    def test_webhook_handler_failed(self, q):
        """Test WEBHOOK requeing failed works."""
        self.register()
        self.signin()
        user = user_repo.get(1)
        project = ProjectFactory.create(owner=user, webhook='server')
        task = TaskFactory.create(project=project, n_answers=1)
        AnonymousTaskRunFactory.create(project=project, task=task)
        payload = self.payload(project, task)
        wh = Webhook(project_id=project.id,
                     payload=payload,
                     response='error',
                     response_status_code=500)
        webhook_repo.save(wh)
        wh2 = Webhook(project_id=project.id,
                      payload=payload,
                      response='ok',
                      response_status_code=200)
        webhook_repo.save(wh2)
        wh3 = Webhook(project_id=project.id,
                      payload=payload,
                      response='ok',
                      response_status_code=200)
        webhook_repo.save(wh3)

        wh = webhook_repo.get(1)
        url = "/project/%s/webhook?failed=true" % (project.short_name)
        res = self.app.get(url)
        assert res.status_code == 200, res.status_code
        q.assert_called_once_with(webhook, project.webhook, wh.payload, wh.id)
Esempio n. 3
0
    def test_get_inactive_users_returns_jobs(self):
        """Test JOB get inactive users returns a list of jobs."""

        today = datetime.datetime.today()
        old_date = today - datetime.timedelta(days=120)
        date_str = old_date.strftime('%Y-%m-%dT%H:%M:%S.%f')
        one_year = today - datetime.timedelta(days=365)
        one_year_str = one_year.strftime('%Y-%m-%dT%H:%M:%S.%f')
        user = UserFactory.create()
        # 3 months old contribution
        tr = TaskRunFactory.create(finish_time=date_str)
        # 1 year old contribution
        TaskRunFactory.create(finish_time=one_year_str)
        # User with a contribution from a long time ago
        TaskRunFactory.create(finish_time="2010-08-08T18:23:45.714110",
                              user=user)
        # User with a recent contribution
        TaskRunFactory.create(user=user)
        user = user_repo.get(tr.user_id)

        jobs_generator = get_inactive_users_jobs()
        jobs = []
        for job in jobs_generator:
            jobs.append(job)

        msg = "There should be one job."
        print jobs
        assert len(jobs) == 1,  msg
        job = jobs[0]
        args = job['args'][0]
        assert job['queue'] == 'quaterly', job['queue']
        assert len(args['recipients']) == 1
        assert args['recipients'][0] == user.email_addr, args['recipients'][0]
        assert "UNSUBSCRIBE" in args['body']
        assert "Update" in args['html']
Esempio n. 4
0
    def test_child_projects_not_built_from_non_iiif_templates(self):
        """Test that only IIIF projects can be built from parents."""
        self.register()
        user = user_repo.get(1)
        vol = dict(id='123abc', name='My Volume', importer='foo')
        category = CategoryFactory()
        tmpl_fixtures = TemplateFixtures(category)
        select_task = tmpl_fixtures.iiif_select_tmpl
        parent_tmpl = tmpl_fixtures.create(task_tmpl=select_task)
        child_tmpl = tmpl_fixtures.create(task_tmpl=select_task)
        child_tmpl['parent_template_id'] = parent_tmpl['id']

        category.info = dict(presenter='iiif-annotation',
                             volumes=[vol],
                             templates=[parent_tmpl, child_tmpl])
        project_repo.update_category(category)
        parent = ProjectFactory(owner=user,
                                category=category,
                                info=dict(template_id=parent_tmpl['id'],
                                          volume_id=vol['id']))

        endpoint = '/lc/projects/{}/new'.format(category.short_name)
        form_data = dict(name='foo',
                         short_name='bar',
                         template_id=child_tmpl['id'],
                         volume_id=vol['id'])
        res = self.app_post_json(endpoint, data=form_data)
        res_data = json.loads(res.data)
        msg = 'Only IIIF projects can be built from parents.'
        assert_equal(res_data['flash'], msg)
Esempio n. 5
0
 def test_webhook_handler_admin(self):
     """Test WEBHOOK view works for admin."""
     # Admin
     self.register()
     self.signout()
     # User
     self.register(name="user", password="******")
     owner = user_repo.get(2)
     self.signout()
     # Access as admin
     self.signin()
     project = ProjectFactory.create(owner=owner)
     url = "/project/%s/webhook" % project.short_name
     res = self.app.get(url)
     assert res.status_code == 200, res.status_code
     assert "Created" in res.data
     assert "Payload" in res.data
     url = "/project/%s/webhook?all=true" % project.short_name
     res = self.app.get(url)
     assert res.status_code == 200, res.status_code
     assert "Created" in res.data
     assert "Payload" in res.data
     url = "/project/%s/webhook?failed=true" % project.short_name
     res = self.app.get(url)
     assert res.status_code == 200, res.status_code
     assert "Created" in res.data
     assert "Payload" in res.data
Esempio n. 6
0
 def test_webhook_handler_all(self, q):
     """Test WEBHOOK requeing all works."""
     self.register()
     self.signin()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user, webhook='server')
     task = TaskFactory.create(project=project, n_answers=1)
     AnonymousTaskRunFactory.create(project=project, task=task)
     payload = self.payload(project, task)
     wh1 = Webhook(project_id=project.id,
                   payload=payload,
                   response='error',
                   response_status_code=500)
     webhook_repo.save(wh1)
     wh2 = Webhook(project_id=project.id,
                   payload=payload,
                   response='ok',
                   response_status_code=200)
     webhook_repo.save(wh2)
     wh3 = Webhook(project_id=project.id,
                   payload=payload,
                   response='ok',
                   response_status_code=200)
     webhook_repo.save(wh3)
     whs = webhook_repo.filter_by(project_id=project.id)
     url = "/project/%s/webhook?all=true" % (project.short_name)
     res = self.app.get(url)
     assert res.status_code == 200, res.status_code
     calls = []
     for w in whs:
         calls.append(call(webhook, project.webhook, w.payload, w.id))
     q.assert_has_calls(calls)
Esempio n. 7
0
    def test_send_mail_creates_message_mailchimp_error(self, mailchimp, Message, mail):
        with patch.dict(self.flask_app.config, {'MAILCHIMP_API_KEY': 'k-3',
                                                'MAILCHIMP_LIST_ID': 1}):
            user = UserFactory.create()
            user_id = user.id
            brand = 'PYBOSSA'
            subject = '[%s]: Your account has been deleted' % brand
            body = """Hi,\n Your account and personal data has been deleted from %s.""" % brand
            body += '\nWe could not delete your Mailchimp account, please contact us to fix this issue.'

            admin_addr = '*****@*****.**'
            recipients = [user.email_addr] + current_app.config.get('ADMINS', [])
            mail_dict = dict(recipients=recipients,
                             subject=subject,
                             body=body,
                             bcc=[admin_addr])

            user_old = user.dictize()
            delete_account(user.id, '*****@*****.**')
            Message.assert_called_once_with(**mail_dict)
            mail.send.assert_called_once_with(Message())
            user_new = user_repo.get(user_id)
            assert user_new.name != user_old['name']
            assert user_new.fullname != user_old['fullname']
            assert user_new.email_addr != user_old['email_addr']
            assert not user_new.info
            assert not user_new.user_pref
Esempio n. 8
0
    def test_send_mail_creates_message_mailchimp_ok(self, mailchimp, Message,
                                                    mail):
        with patch.dict(self.flask_app.config, {
                'MAILCHIMP_API_KEY': 'k-3',
                'MAILCHIMP_LIST_ID': 1
        }):
            user = UserFactory.create()
            user_id = user.id
            brand = 'PYBOSSA'
            subject = '[%s]: Your account has been deleted' % brand
            body = """Hi,\nYour account and personal data has been deleted from %s.""" % brand

            recipients = [user.email_addr, '*****@*****.**']
            mail_dict = dict(recipients=recipients, subject=subject, body=body)

            mailchimp.side_effect = [
                FakeResponse(text=json.dumps(dict(status=204)),
                             json=lambda: '',
                             status_code=204)
            ]
            delete_account(user.id)
            Message.assert_called_once_with(**mail_dict)
            mail.send.assert_called_once_with(Message())
            user = user_repo.get(user_id)
            assert user is None
Esempio n. 9
0
    def test_get_inactive_users_returns_jobs(self):
        """Test JOB get inactive users returns a list of jobs."""

        today = datetime.datetime.today()
        old_date = today - datetime.timedelta(days=120)
        date_str = old_date.strftime('%Y-%m-%dT%H:%M:%S.%f')
        one_year = today - datetime.timedelta(days=365)
        one_year_str = one_year.strftime('%Y-%m-%dT%H:%M:%S.%f')
        user = UserFactory.create()
        # 3 months old contribution
        tr = TaskRunFactory.create(finish_time=date_str)
        # 1 year old contribution
        TaskRunFactory.create(finish_time=one_year_str)
        # User with a contribution from a long time ago
        TaskRunFactory.create(finish_time="2010-08-08T18:23:45.714110",
                              user=user)
        # User with a recent contribution
        TaskRunFactory.create(user=user)
        user = user_repo.get(tr.user_id)

        jobs_generator = get_inactive_users_jobs()
        jobs = []
        for job in jobs_generator:
            jobs.append(job)

        msg = "There should be one job."
        print jobs
        assert len(jobs) == 1, msg
        job = jobs[0]
        args = job['args'][0]
        assert job['queue'] == 'quaterly', job['queue']
        assert len(args['recipients']) == 1
        assert args['recipients'][0] == user.email_addr, args['recipients'][0]
        assert "UNSUBSCRIBE" in args['body']
        assert "Update" in args['html']
Esempio n. 10
0
def projects(name):
    """
    List user's project list.

    Returns a Jinja2 template with the list of projects of the user.

    """
    user = user_repo.get_by_name(name)
    if not user:
        return abort(404)
    if current_user.name != name:
        return abort(403)

    user = user_repo.get(current_user.id)
    args = get_project_browse_args(request.args)
    projects_published, projects_draft = _get_user_projects(user.id, args)

    sort_options = {
        "columns": {
            "entries": columns,
            "id": "project-column-selection",
            "current_selection": args["column"]
        },
        "directions": {
            "entries": directions,
            "id": "project-dir-selection",
            "current_selection": args["order"]
        }
    }

    return render_template('account/projects.html',
                           title=gettext("Projects"),
                           projects_published=projects_published,
                           projects_draft=projects_draft,
                           sort_options=sort_options)
Esempio n. 11
0
def newsletter_subscribe():
    """
    Register method for subscribing user to PyBossa newsletter.

    Returns a Jinja2 template

    """
    # Save that we've prompted the user to sign up in the newsletter
    if newsletter.is_initialized() and current_user.is_authenticated():
        next_url = request.args.get('next') or url_for('home.home')
        user = user_repo.get(current_user.id)
        if current_user.newsletter_prompted is False:
            user.newsletter_prompted = True
            user_repo.update(user)
        if request.args.get('subscribe') == 'True':
            newsletter.subscribe_user(user)
            flash("You are subscribed to our newsletter!")
            return redirect(next_url)
        elif request.args.get('subscribe') == 'False':
            return redirect(next_url)
        else:
            return render_template('account/newsletter.html',
                                   title=gettext("Subscribe to our Newsletter"),
                                   next=next_url)
    else:
        return abort(404)
Esempio n. 12
0
def delete_account(user_id, admin_addr, **kwargs):
    """Delete user account from the system."""
    from pybossa.core import (user_repo, uploader)
    user = user_repo.get(user_id)

    container = "user_%s" % user.id
    if user.info.get('avatar'):
        uploader.delete_file(user.info['avatar'], container)

    email = user.email_addr
    if current_app.config.get('MAILCHIMP_API_KEY'):
        from pybossa.core import newsletter
        newsletter.init_app(current_app)
        mailchimp_deleted = newsletter.delete_user(email)
    else:
        mailchimp_deleted = True
    brand = current_app.config.get('BRAND')
    user_repo.delete_data(user)
    subject = '[%s]: Your account has been deleted' % brand
    body = """Hi,\n Your account and personal data has been deleted from %s.""" % brand
    if not mailchimp_deleted:
        body += '\nWe could not delete your Mailchimp account, please contact us to fix this issue.'
    if current_app.config.get('DISQUS_SECRET_KEY'):
        body += '\nDisqus does not provide an API method to delete your account. You will have to do it by hand yourself in the disqus.com site.'
    recipients = [email]
    bcc = [admin_addr]
    mail_dict = dict(recipients=recipients, bcc=bcc, subject=subject, body=body)
    send_mail(mail_dict, mail_all=True)
Esempio n. 13
0
    def test_send_mail_creates_message_mailchimp_disquss(self, mailchimp, Message, mail):
        with patch.dict(self.flask_app.config, {'MAILCHIMP_API_KEY': 'k-3',
                                                'MAILCHIMP_LIST_ID': 1,
                                                'DISQUS_SECRET_KEY': 'key'}):
            user = UserFactory.create()
            user_id = user.id
            brand = 'PYBOSSA'
            subject = '[%s]: Your account has been deleted' % brand
            body = """Hi,\n Your account and personal data has been deleted from %s.""" % brand
            body += '\nDisqus does not provide an API method to delete your account. You will have to do it by hand yourself in the disqus.com site.'

            admin_addr = '*****@*****.**'
            recipients = [user.email_addr] + current_app.config.get('ADMINS', [])
            mail_dict = dict(recipients=recipients,
                             subject=subject,
                             body=body,
                             bcc=[admin_addr])

            user_old = user.dictize()
            mailchimp.side_effect = [FakeResponse(text=json.dumps(dict(status=204)),
                                                 json=lambda : '',
                                               status_code=204)]
            delete_account(user.id, admin_addr)
            Message.assert_called_once_with(**mail_dict)
            mail.send.assert_called_once_with(Message())
            user_new = user_repo.get(user_id)
            assert user_new.name != user_old['name']
            assert user_new.fullname != user_old['fullname']
            assert user_new.email_addr != user_old['email_addr']
            assert not user_new.info
            assert not user_new.user_pref
Esempio n. 14
0
def confirm_email():
    """Send email to confirm user email."""
    acc_conf_dis = current_app.config.get('ACCOUNT_CONFIRMATION_DISABLED')
    if acc_conf_dis:
        return abort(404)
    if current_user.valid_email is False:
        user = user_repo.get(current_user.id)
        account = dict(fullname=current_user.fullname,
                       name=current_user.name,
                       email_addr=current_user.email_addr)
        confirm_url = get_email_confirmation_url(account)
        subject = ('Verify your email in %s' % current_app.config.get('BRAND'))
        msg = dict(subject=subject,
                   recipients=[current_user.email_addr],
                   body=render_template('/account/email/validate_email.md',
                                        user=account,
                                        confirm_url=confirm_url))
        msg['html'] = render_template('/account/email/validate_email.html',
                                      user=account,
                                      confirm_url=confirm_url)
        mail_queue.enqueue(send_mail, msg)
        msg = gettext("An e-mail has been sent to \
                       validate your e-mail address.")
        flash(msg, 'info')
        user.confirmation_email_sent = True
        user_repo.update(user)
    return redirect_content_type(url_for('.profile', name=current_user.name))
Esempio n. 15
0
def add_subadmin(user_id=None):
    """Add subadmin flag for user_id."""
    try:
        if user_id:
            user = user_repo.get(user_id)
            if not user:
                return format_error('User not found', 404)

            if not user.enabled:
                markup = Markup('<strong>{}</strong> {} <strong>{}</strong>')
                flash(
                    markup.format(gettext('User account '), user.fullname,
                                  gettext(' is disabled')))
                return redirect(url_for(".subadminusers"))

            if not can_have_super_user_access(user):
                markup = Markup('<strong>{} {}</strong> {} {}')
                flash(
                    markup.format(gettext('Denied subadmin privileges to'),
                                  user.fullname, user.email_addr,
                                  'disqualify for subadmin access.'))
                return redirect_content_type(url_for(".subadminusers"))

            ensure_authorized_to('update', user)
            user.subadmin = True
            user_repo.update(user)
            msg = generate_invitation_email_for_admins_subadmins(
                user, "Subadmin")
            if msg:
                mail_queue.enqueue(send_mail, msg)
            return redirect(url_for(".subadminusers"))

    except Exception as e:  # pragma: no cover
        current_app.logger.error(e)
        return abort(500)
Esempio n. 16
0
def newsletter_subscribe():
    """
    Register method for subscribing user to PYBOSSA newsletter.

    Returns a Jinja2 template

    """
    # Save that we've prompted the user to sign up in the newsletter
    if newsletter.is_initialized() and current_user.is_authenticated():
        next_url = request.args.get('next') or url_for('home.home')
        user = user_repo.get(current_user.id)
        if current_user.newsletter_prompted is False:
            user.newsletter_prompted = True
            user_repo.update(user)
        if request.args.get('subscribe') == 'True':
            newsletter.subscribe_user(user)
            flash("You are subscribed to our newsletter!", 'success')
            return redirect_content_type(next_url)
        elif request.args.get('subscribe') == 'False':
            return redirect_content_type(next_url)
        else:
            response = dict(template='account/newsletter.html',
                            title=gettext("Subscribe to our Newsletter"),
                            next=next_url)
            return handle_content_type(response)
    else:
        return abort(404)
Esempio n. 17
0
def newsletter_subscribe():
    """
    Register method for subscribing user to PyBossa newsletter.

    Returns a Jinja2 template

    """
    # Save that we've prompted the user to sign up in the newsletter
    if newsletter.app and current_user.is_authenticated():
        next_url = request.args.get('next') or url_for('home.home')
        user = user_repo.get(current_user.id)
        if current_user.newsletter_prompted is False:
            user.newsletter_prompted = True
            user_repo.update(user)
        if request.args.get('subscribe') == 'True':
            newsletter.subscribe_user(user)
            flash("You are subscribed to our newsletter!")
            return redirect(next_url)
        elif request.args.get('subscribe') == 'False':
            return redirect(next_url)
        else:
            return render_template(
                'account/newsletter.html',
                title=gettext("Subscribe to our Newsletter"),
                next=next_url)
    else:
        return abort(404)
Esempio n. 18
0
 def test_webhook_handler_all(self, q):
     """Test WEBHOOK requeing all works."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user, webhook='server')
     task = TaskFactory.create(project=project, n_answers=1)
     AnonymousTaskRunFactory.create(project=project, task=task)
     payload = self.payload(project, task)
     wh1 = Webhook(project_id=project.id, payload=payload,
                  response='error', response_status_code=500)
     webhook_repo.save(wh1)
     wh2 = Webhook(project_id=project.id, payload=payload,
                   response='ok', response_status_code=200)
     webhook_repo.save(wh2)
     wh3 = Webhook(project_id=project.id, payload=payload,
                   response='ok', response_status_code=200)
     webhook_repo.save(wh3)
     whs = webhook_repo.filter_by(project_id=project.id)
     url = "/project/%s/webhook?all=true" % (project.short_name)
     res = self.app.get(url)
     assert res.status_code == 200, res.status_code
     calls = []
     for w in whs:
         calls.append(call(webhook, project.webhook,
                           w.payload, w.id, True))
     q.assert_has_calls(calls)
Esempio n. 19
0
    def test_send_mail_creates_message_mailchimp_disquss(
            self, mailchimp, Message, mail):
        with patch.dict(
                self.flask_app.config, {
                    'MAILCHIMP_API_KEY': 'k-3',
                    'MAILCHIMP_LIST_ID': 1,
                    'DISQUS_SECRET_KEY': 'key'
                }):
            user = UserFactory.create()
            user_id = user.id
            brand = 'PYBOSSA'
            subject = '[%s]: Your account has been deleted' % brand
            body = """Hi,\n Your account and personal data has been deleted from the %s.""" % brand
            body += '\nDisqus does not provide an API method to delete your account. You will have to do it by hand yourself in the disqus.com site.'

            recipients = [user.email_addr, '*****@*****.**']
            mail_dict = dict(recipients=recipients, subject=subject, body=body)

            mailchimp.side_effect = [
                FakeResponse(text=json.dumps(dict(status=204)),
                             json=lambda: '',
                             status_code=204)
            ]
            delete_account(user.id)
            Message.assert_called_once_with(**mail_dict)
            mail.send.assert_called_once_with(Message())
            user = user_repo.get(user_id)
            assert user is None
Esempio n. 20
0
 def test_project_report_delete_existing_report(self, mock_zip_exists):
     """Test project report is generated with deleting existing report zip"""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export?type=project&format=csv' % project.short_name
     res = self.app.get(url, follow_redirects=True)
Esempio n. 21
0
 def test_project_report_delete_existing_report(self, mock_zip_exists):
     """Test project report is generated with deleting existing report zip"""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export?type=project&format=csv' % project.short_name
     res = self.app.get(url, follow_redirects=True)
Esempio n. 22
0
 def test_admin_owner_can_access_project_report(self):
     """Test admin can access project report"""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 200, res.data
Esempio n. 23
0
 def test_project_report_no_zip_without_uploader(self, mock_no_up):
     """Test project report does not returns zip with no uploader instance """
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export?type=project&format=csv' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 500, res.data
Esempio n. 24
0
 def test_admin_owner_can_access_project_report_with_params(self):
     """Test project report works when accessed with correct params"""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export?type=project&format=csv' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 200, res.data
Esempio n. 25
0
 def test_project_report_with_bad_params_results_404(self):
     """Test project report accessed with incorrect params returns 404"""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export?badparam=badval' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 404, res.data
Esempio n. 26
0
 def test_project_report_with_bad_format_results_415(self):
     """Test project report accessed with bad format returns 415"""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export?type=project&format=badfmt' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 415, res.data
Esempio n. 27
0
 def test_project_report_no_zip_without_uploader(self, mock_no_up):
     """Test project report does not returns zip with no uploader instance """
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export?type=project&format=csv' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 500, res.data
Esempio n. 28
0
 def test_admin_owner_can_access_project_report_with_params(self):
     """Test project report works when accessed with correct params"""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export?type=project&format=csv' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 200, res.data
Esempio n. 29
0
 def test_admin_owner_can_access_project_report(self):
     """Test admin can access project report"""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 200, res.data
Esempio n. 30
0
 def test_project_report_with_bad_format_results_415(self):
     """Test project report accessed with bad format returns 415"""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export?type=project&format=badfmt' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 415, res.data
Esempio n. 31
0
 def test_project_report_with_bad_params_results_404(self):
     """Test project report accessed with incorrect params returns 404"""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export?badparam=badval' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 404, res.data
Esempio n. 32
0
 def test_project_report_with_bad_type_results_404(self):
     """Test project report accessed with bad type returns 404"""
     self.register()
     self.signin()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export?type=badtype&format=csv' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 404, res.data
Esempio n. 33
0
 def test_project_report_delete_existing_report(self, mock_os_remove):
     """Test project report is generated with deleting existing report zip"""
     self.register()
     self.signin()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = '/project/%s/projectreport/export' % project.short_name
     res = self.app.post(url)
     assert mock_os_remove.called
Esempio n. 34
0
def wallet(name):
    user = user_repo.get_by_name(name)
    if not user:
        return abort(404)
    if current_user.name != name:
        return abort(403)

    user = user_repo.get(current_user.id)
    response = dict(template='account/wallet.html', title=gettext("Wallet"))
    return handle_content_type(response)
Esempio n. 35
0
 def test_webhook_handler_auth(self):
     """Test WEBHOOK view works for authenticated not owner."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     self.signout()
     res = self.register(name="juan")
     url = "/project/%s/webhook" % project.short_name
     res = self.app.get(url)
     assert res.status_code == 403, res.status_code
Esempio n. 36
0
 def test_stream_uri_private_owner(self, mock_response, mock_sse):
     """Test stream URI private owner works."""
     mock_sse.return_value = self.fake_sse_response
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     private_uri = '/project/%s/privatestream' % project.short_name
     self.app.get(private_uri, follow_redirects=True)
     assert mock_sse.called
     assert mock_sse.called_once_with(project.short_name, 'private')
Esempio n. 37
0
 def test_get_non_contrib_users_jobs_with_users(self):
     """Test JOB get with users returns empty list."""
     TaskRunFactory.create()
     user = user_repo.get(1)
     jobs = get_non_contributors_users_jobs()
     msg = "There should not be any job."
     assert len(jobs) == 1, msg
     job = jobs[0]
     args = job['args'][0]
     assert args['recipients'][0] == user.email_addr, args['recipients'][1]
Esempio n. 38
0
 def test_stream_uri_private_owner_404(self):
     """Test stream URI private return 404 when SSE disabled
     for owner works."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     private_uri = '/project/%s/privatestream' % project.short_name
     with patch.dict(self.flask_app.config, {'SSE': False}):
         res = self.app.get(private_uri, follow_redirects=True)
         assert res.status_code == 404
Esempio n. 39
0
 def test_webhook_handler_owner(self):
     """Test WEBHOOK view works for owner."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = "/project/%s/webhook" % project.short_name
     res = self.app.get(url)
     assert res.status_code == 200, res.status_code
     assert "Created" in res.data
     assert "Payload" in res.data
Esempio n. 40
0
 def test_stream_uri_private_auth(self):
     """Test stream URI private auth but not owner works."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     self.signout()
     self.register(fullname='Juan', name='juan', password='******')
     private_uri = '/project/%s/privatestream' % project.short_name
     res = self.app.get(private_uri, follow_redirects=True)
     assert res.status_code == 403, res.data
Esempio n. 41
0
 def test_stream_uri_private_auth(self):
     """Test stream URI private auth but not owner works."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     self.signout()
     self.register(fullname='Juan', name='juan', password='******')
     private_uri = '/project/%s/privatestream' % project.short_name
     res = self.app.get(private_uri, follow_redirects=True)
     assert res.status_code == 403, res.data
Esempio n. 42
0
 def test_webhook_handler_owner(self):
     """Test WEBHOOK view works for owner."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     url = "/project/%s/webhook" % project.short_name
     res = self.app.get(url)
     assert res.status_code == 200, res.status_code
     assert "Created" in res.data
     assert "Payload" in res.data
Esempio n. 43
0
 def test_webhook_handler_auth(self):
     """Test WEBHOOK view works for authenticated not owner."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     self.signout()
     res = self.register(name="juan")
     url = "/project/%s/webhook" % project.short_name
     res = self.app.get(url)
     assert res.status_code == 403, res.status_code
Esempio n. 44
0
 def test_stream_uri_private_owner_404(self):
     """Test stream URI private return 404 when SSE disabled
     for owner works."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     private_uri = '/project/%s/privatestream' % project.short_name
     with patch.dict(self.flask_app.config, {'SSE': False}):
         res = self.app.get(private_uri, follow_redirects=True)
         assert res.status_code == 404
Esempio n. 45
0
 def test_stream_uri_private_owner(self, mock_response, mock_sse):
     """Test stream URI private owner works."""
     mock_sse.return_value = self.fake_sse_response
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     private_uri = '/project/%s/privatestream' % project.short_name
     self.app.get(private_uri, follow_redirects=True)
     assert mock_sse.called
     assert mock_sse.called_once_with(project.short_name, 'private')
Esempio n. 46
0
 def test_nonadmin_noncoowner_access_project_report_results_403(self):
     """Test nonadmin noncoowner accessing project report returns 403"""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     self.signout()
     self.register(fullname='Juan', name='juan', password='******')
     self.signin(email="*****@*****.**", password='******')
     url = '/project/%s/projectreport/export' % project.short_name
     res = self.app.get(url, follow_redirects=True)
     assert res.status_code == 403, res.data
Esempio n. 47
0
 def test_newsletter_subscribe(self, newsletter):
     """Test NEWSLETTER view subcribe works."""
     newsletter.is_initialized.return_value = True
     newsletter.ask_user_to_subscribe.return_value = True
     self.register()
     res = self.app.get("/account/newsletter?subscribe=True", follow_redirects=True)
     err_msg = "User should be subscribed"
     user = user_repo.get(1)
     assert "You are subscribed" in res.data, err_msg
     assert newsletter.subscribe_user.called, err_msg
     newsletter.subscribe_user.assert_called_with(user)
Esempio n. 48
0
 def test_newsletter_subscribe_next(self, newsletter):
     """Test NEWSLETTER view subscribe next works."""
     newsletter.app = True
     self.register()
     next_url = '%2Faccount%2Fjohndoe%2Fupdate'
     url ='/account/newsletter?subscribe=True&next=%s' % next_url
     res = self.app.get(url, follow_redirects=True)
     err_msg = "User should be subscribed"
     user = user_repo.get(1)
     assert "You are subscribed" in res.data, err_msg
     assert newsletter.subscribe_user.called, err_msg
     newsletter.subscribe_user.assert_called_with(user)
     assert "Update" in res.data, res.data
Esempio n. 49
0
    def test_get_non_contrib_users_jobs_with_users(self):
        """Test JOB get with users returns empty list."""
        TaskRunFactory.create()
        user = user_repo.get(1)
        jobs_generator = get_non_contributors_users_jobs()
        jobs = []
        for job in jobs_generator:
            jobs.append(job)

        msg = "There should not be any job."
        assert len(jobs) == 1,  msg
        job = jobs[0]
        args = job['args'][0]
        assert args['recipients'][0] == user.email_addr, args['recipients'][1]
Esempio n. 50
0
def _handle_password_update(user, password_form):
    if password_form.validate_on_submit():
        user = user_repo.get(user.id)
        if user.check_password(password_form.current_password.data):
            user.set_password(password_form.new_password.data)
            user_repo.update(user)
            flash(gettext('Yay, you changed your password succesfully!'),
                  'success')
        else:
            msg = gettext("Your current password doesn't match the "
                          "one in our records")
            flash(msg, 'error')
    else:
        flash(gettext('Please correct the errors'), 'error')
Esempio n. 51
0
 def test_webhook_handler_post_oid_404(self):
     """Test WEBHOOK post oid 404 works."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     task = TaskFactory.create(project=project, n_answers=1)
     AnonymousTaskRunFactory.create(project=project, task=task)
     payload = self.payload(project, task)
     webhook = Webhook(project_id=project.id, payload=payload,
                       response='OK', response_status_code=200)
     webhook_repo.save(webhook)
     url = "/project/%s/webhook/%s" % (project.short_name, 9999)
     res = self.app.post(url)
     assert res.status_code == 404, res.status_code
Esempio n. 52
0
def export_userdata(user_id, **kwargs):
    from pybossa.core import user_repo, project_repo, task_repo, result_repo
    from flask import current_app, url_for
    json_exporter = JsonExporter()
    user = user_repo.get(user_id)
    user_data = user.dictize()
    del user_data['passwd_hash']
    projects = project_repo.filter_by(owner_id=user.id)
    projects_data = [project.dictize() for project in projects]
    taskruns = task_repo.filter_task_runs_by(user_id=user.id)
    taskruns_data = [tr.dictize() for tr in taskruns]
    pdf = json_exporter._make_zip(None, '', 'personal_data', user_data, user_id,
                                  'personal_data.zip')
    upf = json_exporter._make_zip(None, '', 'user_projects', projects_data, user_id,
                                  'user_projects.zip')
    ucf = json_exporter._make_zip(None, '', 'user_contributions', taskruns_data, user_id,
                                  'user_contributions.zip')
    upload_method = current_app.config.get('UPLOAD_METHOD')
    if upload_method == 'local':
        upload_method = 'uploads.uploaded_file'

    personal_data_link = url_for(upload_method,
                                 filename="user_%s/%s" % (user_id, pdf))
    personal_projects_link = url_for(upload_method,
                                    filename="user_%s/%s" % (user_id,
                                                             upf))
    personal_contributions_link = url_for(upload_method,
                                          filename="user_%s/%s" % (user_id,
                                                                   ucf))

    body = render_template('/account/email/exportdata.md',
                           user=user.dictize(),
                           personal_data_link=personal_data_link,
                           personal_projects_link=personal_projects_link,
                           personal_contributions_link=personal_contributions_link,
                           config=current_app.config)

    html = render_template('/account/email/exportdata.html',
                           user=user.dictize(),
                           personal_data_link=personal_data_link,
                           personal_projects_link=personal_projects_link,
                           personal_contributions_link=personal_contributions_link,
                           config=current_app.config)
    subject = 'Your personal data'
    mail_dict = dict(recipients=[user.email_addr],
                     subject=subject,
                     body=body,
                     html=html)
    send_mail(mail_dict)
Esempio n. 53
0
    def test_get_inactive_users_returns_jobs_unsubscribed(self):
        """Test JOB get inactive users returns an empty list of jobs."""

        tr = TaskRunFactory.create(finish_time="2010-07-07T17:23:45.714210")
        user = user_repo.get(tr.user_id)
        user.subscribed = False
        user_repo.update(user)

        jobs_generator = get_inactive_users_jobs()
        jobs = []
        for job in jobs_generator:
            jobs.append(job)

        msg = "There should be zero jobs."
        assert len(jobs) == 0,  msg
Esempio n. 54
0
    def test_get_non_contrib_users_returns_unsubscribed_jobs(self):
        """Test JOB get non contrib users returns a list of jobs."""

        TaskRunFactory.create()
        user = user_repo.get(1)
        user.subscribed = False
        user_repo.update(user)

        jobs_generator = get_non_contributors_users_jobs()
        jobs = []
        for job in jobs_generator:
            jobs.append(job)

        msg = "There should be zero jobs."
        assert len(jobs) == 0,  msg
Esempio n. 55
0
 def test_stream_uri_private_admin_404(self):
     """Test stream URI private returns 404 when sse disabled for
     admin but not owner works."""
     with patch.dict(self.flask_app.config, {'SSE': False}):
         self.register()
         self.signout()
         self.register(fullname="name", name="name")
         user = user_repo.get(2)
         project = ProjectFactory.create(owner=user)
         private_uri = '/project/%s/privatestream' % project.short_name
         self.signout()
         # Sign in as admin
         self.signin()
         res = self.app.get(private_uri, follow_redirects=True)
         assert res.status_code == 404
Esempio n. 56
0
def add_admin(user_id=None):
    """Add admin flag for user_id."""
    try:
        if user_id:
            user = user_repo.get(user_id)
            if user:
                ensure_authorized_to('update', user)
                user.admin = True
                user_repo.update(user)
                return redirect(url_for(".users"))
            else:
                msg = "User not found"
                return format_error(msg, 404)
    except Exception as e:  # pragma: no cover
        current_app.logger.error(e)
        return abort(500)
Esempio n. 57
0
 def test_stream_uri_private_admin(self, mock_response, mock_sse):
     """Test stream URI private admin but not owner works."""
     mock_sse.return_value = self.fake_sse_response
     self.register()
     self.signout()
     self.register(fullname="name", name="name")
     user = user_repo.get(2)
     project = ProjectFactory.create(owner=user)
     private_uri = '/project/%s/privatestream' % project.short_name
     self.signout()
     # Sign in as admin
     self.signin()
     res = self.app.get(private_uri, follow_redirects=True)
     assert mock_sse.called
     assert mock_sse.called_once_with(project.short_name, 'private')
     assert res.status_code == 200
     assert res.data == self.fake_sse_response, res.data
Esempio n. 58
0
def get_export_task_jobs():
    """Export tasks to zip"""
    from pybossa.core import db, user_repo
    from pybossa.model.app import App
    apps = db.slave_session.query(App).all()
    # Append all ZIP generation for each app as a task
    jobs = []
    for app_x in apps:
        checkuser = user_repo.get(app_x.owner_id)
        # Check if Pro User, if yes use a shorter schedule
        schedule_hours = 24
        if checkuser.pro:
            schedule_hours = 4
        jobs.append(dict(name = project_export,
                         args = [app_x.id], kwargs={},
                         interval=(schedule_hours * HOUR),
                         timeout = (10 * MINUTE)))
    return jobs
Esempio n. 59
0
    def test_new_user_gets_newsletter_only_once(self, newsletter):
        """Test NEWSLETTER user gets newsletter only once works."""
        newsletter.app = True
        res = self.register()
        dom = BeautifulSoup(res.data)
        user = user_repo.get(1)
        err_msg = "There should be a newsletter page."
        assert dom.find(id='newsletter') is not None, err_msg
        assert dom.find(id='signmeup') is not None, err_msg
        assert dom.find(id='notinterested') is not None, err_msg
        assert user.newsletter_prompted is True, err_msg

        self.signout()
        res = self.signin()
        dom = BeautifulSoup(res.data)
        assert dom.find(id='newsletter') is None, err_msg
        assert dom.find(id='signmeup') is None, err_msg
        assert dom.find(id='notinterested') is None, err_msg
Esempio n. 60
0
 def test_webhook_handler_post_oid(self):
     """Test WEBHOOK post oid works."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     task = TaskFactory.create(project=project, n_answers=1)
     AnonymousTaskRunFactory.create(project=project, task=task)
     payload = self.payload(project, task)
     webhook = Webhook(project_id=project.id, payload=payload,
                       response='OK', response_status_code=200)
     webhook_repo.save(webhook)
     webhook = webhook_repo.get(1)
     url = "/project/%s/webhook/%s" % (project.short_name, webhook.id)
     res = self.app.post(url)
     tmp = json.loads(res.data)
     assert res.status_code == 200, res.status_code
     assert tmp['payload']['project_short_name'] == project.short_name
     assert tmp['payload']['project_id'] == project.id
     assert tmp['payload']['task_id'] == task.id