Esempio n. 1
0
class TestDataverseRestrictions(DataverseAddonTestCase, OsfTestCase):

    def setUp(self):

        super(DataverseAddonTestCase, self).setUp()

        # Nasty contributor who will try to access content that he shouldn't
        # have access to
        self.contrib = AuthUserFactory()
        self.project.add_contributor(self.contrib, auth=Auth(self.user))
        self.project.save()

    @mock.patch('addons.dataverse.views.client.connect_from_settings')
    def test_restricted_set_dataset_not_owner(self, mock_connection):
        mock_connection.return_value = create_mock_connection()

        # Contributor has dataverse auth, but is not the node authorizer
        self.contrib.add_addon('dataverse')
        self.contrib.save()

        url = api_url_for('dataverse_set_config', pid=self.project._primary_key)
        params = {
            'dataverse': {'alias': 'ALIAS1'},
            'dataset': {'doi': 'doi:12.3456/DVN/00002'},
        }
        res = self.app.post_json(url, params, auth=self.contrib.auth,
                                 expect_errors=True)
        assert_equal(res.status_code, http.FORBIDDEN)
    def test_reviewer_can_only_update_comment_fields_draft_registration(
            self, app, project_public, draft_registration_prereg, administer_permission):
        user = AuthUserFactory()
        user.user_permissions.add(administer_permission)
        user.save()

        payload = {
            'data': {
                'id': draft_registration_prereg._id,
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {
                        'q2': {
                            'value': 'Test response'
                        }
                    }
                }
            }
        }

        url = '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration_prereg._id)

        res = app.put_json_api(
            url, payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0][
            'detail'] == 'For your registration your response to the \'Authors\' field is invalid.'
    def test_reviewer_can_update_nested_comment_fields_draft_registration(
            self, app, project_public, draft_registration_prereg, administer_permission):
        user = AuthUserFactory()
        user.user_permissions.add(administer_permission)
        user.save()

        payload = {
            'data': {
                'id': draft_registration_prereg._id,
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {
                        'q7': {
                            'value': {
                                'question': {
                                    'comments': [{'value': 'Add some clarity here.'}]
                                }
                            }
                        }
                    }
                }
            }
        }

        url = '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration_prereg._id)

        res = app.put_json_api(
            url, payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 200
        assert res.json['data']['attributes']['registration_metadata']['q7'][
            'value']['question']['comments'][0]['value'] == 'Add some clarity here.'
Esempio n. 4
0
class TestCreateInstitution(AdminTestCase):
    def setUp(self):
        super(TestCreateInstitution, self).setUp()

        self.user = AuthUserFactory()
        self.change_permission = Permission.objects.get(codename='change_institution')
        self.user.user_permissions.add(self.change_permission)
        self.user.save()

        self.institution = InstitutionFactory()

        self.request = RequestFactory().get('/fake_path')
        self.request.user = self.user
        self.base_view = views.CreateInstitution
        self.view = setup_form_view(self.base_view(), self.request, form=InstitutionForm())

        self.view.kwargs = {'institution_id': self.institution.id}

    def test_get_context_data(self):
        self.view.object = self.institution
        res = self.view.get_context_data()
        nt.assert_is_instance(res, dict)
        nt.assert_is_instance(res['import_form'], ImportFileForm)

    def test_no_permission_raises(self):
        user2 = AuthUserFactory()
        nt.assert_false(user2.has_perm('osf.change_institution'))
        self.request.user = user2

        with nt.assert_raises(PermissionDenied):
            self.base_view.as_view()(self.request)

    def test_get_view(self):
        res = self.view.get(self.request)
        nt.assert_equal(res.status_code, 200)
    def setUp(self):
        super(TestPreprintCitationContentChicago, self).setUp()
        self.admin_contributor = AuthUserFactory()
        self.published_preprint = PreprintFactory(
            title='A Study of Coffee',
            creator=self.admin_contributor)
        self.published_preprint.save()

        self.admin_contributor.given_name = 'Grapes'
        self.admin_contributor.middle_names = ' Coffee Beans '
        self.admin_contributor.family_name = 'McGee'
        self.admin_contributor.save()
        self.published_preprint_url = '/{}preprints/{}/citation/chicago-author-date/'.format(
            API_BASE, self.published_preprint._id)

        self.second_contrib = AuthUserFactory()
        self.second_contrib.given_name = 'Darla'
        self.second_contrib.middle_names = 'Texas Toast'
        self.second_contrib.family_name = 'Jenkins'
        self.second_contrib.suffix = 'Junior'
        self.second_contrib.save()

        self.third_contrib = AuthUserFactory()
        self.third_contrib.given_name = 'Lilith'
        self.third_contrib.middle_names = 'Radar'
        self.third_contrib.family_name = 'Schematics'
        self.third_contrib.save()
Esempio n. 6
0
 def setUp(self):
     super(TestUserSpamListView, self).setUp()
     self.project = ProjectFactory(is_public=True)
     self.user_1 = AuthUserFactory()
     self.user_2 = AuthUserFactory()
     self.project.add_contributor(self.user_1)
     self.project.add_contributor(self.user_2)
     self.project.save()
     self.user_1.save()
     self.user_2.save()
     self.comment_1 = CommentFactory(node=self.project, user=self.user_1)
     self.comment_2 = CommentFactory(node=self.project, user=self.user_1)
     self.comment_3 = CommentFactory(node=self.project, user=self.user_1)
     self.comment_4 = CommentFactory(node=self.project, user=self.user_1)
     self.comment_5 = CommentFactory(node=self.project, user=self.user_2)
     self.comment_6 = CommentFactory(node=self.project, user=self.user_2)
     self.comment_1.report_abuse(user=self.user_2, save=True,
                                 category='spam')
     self.comment_2.report_abuse(user=self.user_2, save=True,
                                 category='spam')
     self.comment_3.report_abuse(user=self.user_2, save=True,
                                 category='spam')
     self.comment_4.report_abuse(user=self.user_2, save=True,
                                 category='spam')
     self.comment_5.report_abuse(user=self.user_1, save=True,
                                 category='spam')
     self.comment_6.report_abuse(user=self.user_1, save=True,
                                 category='spam')
     self.request = RequestFactory().get('/fake_path')
     self.view = UserSpamList()
     self.view = setup_view(self.view, self.request, user_id=self.user_1._id)
    def test_reviewer_cannot_update_nested_value_fields_draft_registration(
            self, app, project_public, draft_registration_prereg, administer_permission):
        user = AuthUserFactory()
        user.user_permissions.add(administer_permission)
        user.save()

        payload = {
            'data': {
                'id': draft_registration_prereg._id,
                'type': 'draft_registrations',
                'attributes': {
                    'registration_metadata': {
                        'q7': {
                            'value': {
                                'question': {
                                    'value': 'This is the answer'
                                }
                            }
                        }
                    }
                }
            }
        }

        url = '/{}nodes/{}/draft_registrations/{}/'.format(
            API_BASE, project_public._id, draft_registration_prereg._id)

        res = app.put_json_api(
            url, payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0][
            'detail'] == 'Additional properties are not allowed (u\'value\' was unexpected)'
    def test_reviewer_can_update_nested_comment_fields_draft_registration(self):
        user = AuthUserFactory()
        user.add_system_tag(PREREG_ADMIN_TAG)
        user.save()

        payload = {
            "data": {
                "id": self.prereg_draft_registration._id,
                "type": "draft_registrations",
                "attributes": {
                    "registration_metadata": {
                        'q7': {
                            'value': {
                                 'question': {
                                    'comments': [{'value': 'Add some clarity here.'}]
                                }
                            }
                        }
                    }
                }
            }
        }

        url = '/{}nodes/{}/draft_registrations/{}/'.format(API_BASE, self.public_project._id, self.prereg_draft_registration._id)

        res = self.app.put_json_api(url, payload, auth=user.auth, expect_errors=True)
        assert_equal(res.status_code, 200)
        assert_equal(res.json['data']['attributes']['registration_metadata']['q7']['value']['question']['comments'][0]['value'], 'Add some clarity here.')
Esempio n. 9
0
    def test_update_wiki_updates_contributor_comments_viewed_timestamp(self):
        contributor = AuthUserFactory()
        project = ProjectFactory(creator=self.user, is_public=True)
        project.add_contributor(contributor)
        project.save()
        wiki_page = WikiFactory(node=project, page_name='test')
        wiki = WikiVersionFactory(wiki_page=wiki_page)
        comment = CommentFactory(node=project, target=Guid.load(wiki_page._id), user=self.user)

        # user views comments -- sets user.comments_viewed_timestamp
        url = project.api_url_for('update_comments_timestamp')
        res = self.app.put_json(url, {
            'page': 'wiki',
            'rootId': wiki_page._id
        }, auth=self.user.auth)
        assert res.status_code == 200
        self.user.reload()
        assert wiki_page._id in self.user.comments_viewed_timestamp

        # contributor views comments -- sets contributor.comments_viewed_timestamp
        res = self.app.put_json(url, {
            'page': 'wiki',
            'rootId': wiki_page._id
        }, auth=contributor.auth)
        contributor.reload()
        assert wiki_page._id in contributor.comments_viewed_timestamp

        # user updates the wiki
        project.update_node_wiki('test', 'Updating wiki', self.auth)
        comment.reload()
        contributor.reload()

        new_version_id = project.get_wiki_version('test')._id
        assert wiki_page._id in contributor.comments_viewed_timestamp
        assert comment.target.referent._id == wiki_page._id
Esempio n. 10
0
class TestPreprintFormView(AdminTestCase):

    def setUp(self):
        super(TestPreprintFormView, self).setUp()
        self.preprint = PreprintFactory()
        self.view = views.PreprintFormView
        self.user = AuthUserFactory()
        self.url = reverse('preprints:search')

    def test_no_user_permissions_raises_error(self):
        request = RequestFactory().get(self.url)
        request.user = self.user
        with nt.assert_raises(PermissionDenied):
            self.view.as_view()(request)

    def test_correct_view_permissions(self):

        view_permission = Permission.objects.get(codename='view_preprintservice')
        self.user.user_permissions.add(view_permission)
        self.user.save()

        request = RequestFactory().get(self.url)
        request.user = self.user

        response = self.view.as_view()(request)
        nt.assert_equal(response.status_code, 200)
    def test_reviewer_cannot_update_nested_value_fields_draft_registration(self):
        user = AuthUserFactory()
        user.add_system_tag(PREREG_ADMIN_TAG)
        user.save()

        payload = {
            "data": {
                "id": self.prereg_draft_registration._id,
                "type": "draft_registrations",
                "attributes": {
                    "registration_metadata": {
                        'q7': {
                            'value': {
                                 'question': {
                                    'value': 'This is the answer'
                                }
                            }
                        }
                    }
                }
            }
        }

        url = '/{}nodes/{}/draft_registrations/{}/'.format(API_BASE, self.public_project._id, self.prereg_draft_registration._id)

        res = self.app.put_json_api(url, payload, auth=user.auth, expect_errors=True)
        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'], "Additional properties are not allowed (u'value' was unexpected)")
Esempio n. 12
0
    def setUp(self):
        super(TestPreprintCitationContentMLA, self).setUp()
        self.admin_contributor = AuthUserFactory()
        self.published_preprint = PreprintFactory(
            creator=self.admin_contributor)
        self.node = self.published_preprint.node
        self.node.title = 'My Preprint'
        self.node.save()

        self.admin_contributor.given_name = 'Grapes'
        self.admin_contributor.middle_names = ' Coffee Beans '
        self.admin_contributor.family_name = 'McGee'
        self.admin_contributor.save()
        self.published_preprint_url = '/{}preprints/{}/citation/modern-language-association/'.format(
                     API_BASE, self.published_preprint._id)

        self.second_contrib = AuthUserFactory()
        self.second_contrib.given_name = 'Darla'
        self.second_contrib.middle_names = 'Texas Toast'
        self.second_contrib.family_name = 'Jenkins'
        self.second_contrib.suffix = 'Junior'
        self.second_contrib.save()

        self.third_contrib = AuthUserFactory()
        self.third_contrib.given_name = 'Lilith'
        self.third_contrib.middle_names = 'Radar'
        self.third_contrib.family_name = 'Schematics'
        self.third_contrib.save()
Esempio n. 13
0
    def test_no_permission_raises(self):
        user2 = AuthUserFactory()
        nt.assert_false(user2.has_perm('osf.view_node'))
        self.request.user = user2

        with nt.assert_raises(PermissionDenied):
            self.base_view.as_view()(self.request)
Esempio n. 14
0
    def test_metadata_for_node_only_includes_visible_contribs(self, datacite_client):
        visible_contrib = AuthUserFactory()
        visible_contrib2 = AuthUserFactory()
        visible_contrib2.given_name = u'ヽ༼ ಠ益ಠ ༽ノ'
        visible_contrib2.family_name = u'ლ(´◉❥◉`ლ)'
        visible_contrib2.save()
        invisible_contrib = AuthUserFactory()
        invisible_contrib.given_name = 'Shady'
        invisible_contrib.family_name = 'McCoy'
        invisible_contrib.save()
        registration = RegistrationFactory(is_public=True)

        registration.add_contributor(visible_contrib, visible=True)
        registration.add_contributor(invisible_contrib, visible=False)
        registration.add_contributor(visible_contrib2, visible=True)
        registration.save()

        metadata_xml = datacite_client.build_metadata(registration)
        # includes visible contrib name
        assert u'<givenName>{}</givenName>'.format(visible_contrib.given_name) in metadata_xml
        assert u'<familyName>{}</familyName>'.format(visible_contrib.family_name) in metadata_xml

        # doesn't include invisible contrib name
        assert u'<givenName>{}</givenName>'.format(invisible_contrib.given_name) not in metadata_xml
        assert u'<familyName>{}</familyName>'.format(invisible_contrib.family_name) not in metadata_xml
    def test_reviewer_cannot_delete_draft_registration(self):
        user = AuthUserFactory()
        user.add_system_tag(PREREG_ADMIN_TAG)
        user.save()

        res = self.app.delete_json_api(self.url, auth=user.auth, expect_errors=True)
        assert_equal(res.status_code, 403)
        assert_equal(res.json['errors'][0]['detail'], 'You do not have permission to perform this action.')
    def test_reviewer_cannot_create_draft_registration(self):
        user = AuthUserFactory()
        user.add_system_tag(PREREG_ADMIN_TAG)
        user.save()

        assert_in(self.read_only_user, self.public_project.contributors.all())
        res = self.app.post_json_api(self.url, self.payload, auth=user.auth, expect_errors=True)
        assert_equal(res.status_code, 403)
Esempio n. 17
0
 def test_get_flagged_spam(self):
     user = AuthUserFactory()
     user.is_superuser = True
     user.save()
     request = RequestFactory().get(reverse('nodes:flagged-spam'))
     request.user = user
     response = NodeFlaggedSpamList.as_view()(request)
     nt.assert_equal(response.status_code, 200)
Esempio n. 18
0
 def test_get_known_ham(self):
     user = AuthUserFactory()
     user.is_superuser = True
     user.save()
     request = RequestFactory().get(reverse('nodes:known-ham'))
     request.user = user
     response = NodeKnownHamList.as_view()(request)
     nt.assert_equal(response.status_code, 200)
 def test_many_users_each_with_the_same_github_enabled(self):
     user = AuthUserFactory()
     user.add_addon('github')
     user.external_accounts.add(self.external_account)
     user.save()
     results = AddonSnapshot().get_events()
     github_res = [res for res in results if res['provider']['name'] == 'github'][0]
     assert_equal(github_res['users']['enabled'], 2)
    def test_node_errors(
            self, app, user, institution_one, resource_factory,
            create_payload, node_institutions_url):

        #   test_node_with_no_permissions
        unauthorized_user = AuthUserFactory()
        unauthorized_user.affiliated_institutions.add(institution_one)
        unauthorized_user.save()
        res = app.put_json_api(
            node_institutions_url,
            create_payload([institution_one._id]),
            auth=unauthorized_user.auth,
            expect_errors=True,
        )
        assert res.status_code == 403

    #   test_user_with_no_institution
        unauthorized_user = AuthUserFactory()
        node = resource_factory(creator=unauthorized_user)
        res = app.put_json_api(
            '/{0}{1}s/{2}/relationships/institutions/'.format(API_BASE, node.__class__.__name__.lower(), node._id),
            create_payload(institution_one._id),
            expect_errors=True,
            auth=unauthorized_user.auth
        )
        assert res.status_code == 403

    #   test_institution_does_not_exist
        res = app.put_json_api(
            node_institutions_url,
            create_payload('not_an_id'),
            expect_errors=True,
            auth=user.auth
        )

        assert res.status_code == 404

    #   test_wrong_type
        res = app.put_json_api(
            node_institutions_url,
            {'data': [{'type': 'not_institution', 'id': institution_one._id}]},
            expect_errors=True,
            auth=user.auth
        )

        assert res.status_code == 409

    #   test_remove_institutions_with_no_permissions
        res = app.put_json_api(
            node_institutions_url,
            create_payload(),
            expect_errors=True
        )
        assert res.status_code == 401

    #   test_retrieve_private_node_no_auth
        res = app.get(node_institutions_url, expect_errors=True)
        assert res.status_code == 401
Esempio n. 21
0
class TestCheckPreregAuth(OsfTestCase):

    def setUp(self):
        super(TestCheckPreregAuth, self).setUp()

        self.prereg_challenge_admin_user = AuthUserFactory()
        self.prereg_challenge_admin_user.add_system_tag(settings.PREREG_ADMIN_TAG)
        self.prereg_challenge_admin_user.save()
        prereg_schema = MetaSchema.find_one(
            Q('name', 'eq', 'Prereg Challenge') &
            Q('schema_version', 'eq', 2)
        )

        self.user = AuthUserFactory()
        self.node = factories.ProjectFactory(creator=self.user)

        self.parent = factories.ProjectFactory()
        self.child = factories.NodeFactory(parent=self.parent)

        self.draft_registration = factories.DraftRegistrationFactory(
            initiator=self.user,
            registration_schema=prereg_schema,
            branched_from=self.parent
        )

    def test_has_permission_download_prereg_challenge_admin(self):
        res = views.check_access(self.draft_registration.branched_from,
            Auth(user=self.prereg_challenge_admin_user), 'download', None)
        assert_true(res)

    def test_has_permission_download_on_component_prereg_challenge_admin(self):
        try:
            res = views.check_access(self.draft_registration.branched_from._nodes.first(),
                                     Auth(user=self.prereg_challenge_admin_user), 'download', None)
        except Exception:
            self.fail()
        assert_true(res)

    def test_has_permission_download_not_prereg_challenge_admin(self):
        new_user = AuthUserFactory()
        with assert_raises(HTTPError) as exc_info:
            views.check_access(self.draft_registration.branched_from,
                 Auth(user=new_user), 'download', None)
            assert_equal(exc_info.exception.code, http.FORBIDDEN)

    def test_has_permission_download_prereg_challenge_admin_not_draft(self):
        with assert_raises(HTTPError) as exc_info:
            views.check_access(self.node,
                 Auth(user=self.prereg_challenge_admin_user), 'download', None)
            assert_equal(exc_info.exception.code, http.FORBIDDEN)

    def test_has_permission_write_prereg_challenge_admin(self):
        with assert_raises(HTTPError) as exc_info:
            views.check_access(self.draft_registration.branched_from,
                Auth(user=self.prereg_challenge_admin_user), 'write', None)
            assert_equal(exc_info.exception.code, http.FORBIDDEN)
 def test_reviewer_can_see_draft_registration(self):
     user = AuthUserFactory()
     user.add_system_tag(PREREG_ADMIN_TAG)
     user.save()
     res = self.app.get(self.url, auth=user.auth)
     assert_equal(res.status_code, 200)
     data = res.json['data']
     assert_equal(data['attributes']['registration_supplement'], self.schema._id)
     assert_equal(data['id'], self.draft_registration._id)
     assert_equal(data['attributes']['registration_metadata'], {})
 def test_github_enabled_not_linked_or_authorized(self):
     user = AuthUserFactory()
     user.add_addon('github')
     user.external_accounts.add(self.external_account)
     user.save()
     results = AddonSnapshot().get_events()
     github_res = [res for res in results if res['provider']['name'] == 'github'][0]
     assert_equal(github_res['users']['enabled'], 2)
     assert_equal(github_res['users']['authorized'], 1)
     assert_equal(github_res['users']['linked'], 1)
Esempio n. 24
0
    def test_correct_view_permissions(self):
        user = AuthUserFactory()
        edit_permission = Permission.objects.get(codename='change_subject')
        user.user_permissions.add(edit_permission)
        user.save()

        request = RequestFactory().get(self.url)
        request.user = user

        response = self.plain_view.as_view()(request, pk=self.subject.pk)
        nt.assert_equal(response.status_code, 200)
Esempio n. 25
0
    def test_s3_set_bucket_no_auth(self):

        user = AuthUserFactory()
        user.add_addon('s3')
        self.project.add_contributor(user, save=True)
        url = self.project.api_url_for('s3_set_config')
        res = self.app.put_json(
            url, {'s3_bucket': 'hammertofall'}, auth=user.auth,
            expect_errors=True
        )
        assert_equal(res.status_code, http.FORBIDDEN)
Esempio n. 26
0
 def setUp(self):
     super(TestSpamListView, self).setUp()
     Comment.objects.all().delete()
     self.project = ProjectFactory(is_public=True)
     self.user_1 = AuthUserFactory()
     self.user_2 = AuthUserFactory()
     self.project.add_contributor(self.user_1)
     self.project.add_contributor(self.user_2)
     self.project.save()
     self.user_1.save()
     self.user_2.save()
     date = timezone.now()
     self.comment_1 = CommentFactory(node=self.project, user=self.user_1)
     self.comment_2 = CommentFactory(node=self.project, user=self.user_1)
     self.comment_3 = CommentFactory(node=self.project, user=self.user_1)
     self.comment_4 = CommentFactory(node=self.project, user=self.user_1)
     self.comment_5 = CommentFactory(node=self.project, user=self.user_2)
     self.comment_6 = CommentFactory(node=self.project, user=self.user_2)
     self.comment_1.report_abuse(
         user=self.user_2,
         save=True,
         category='spam',
         date=date - timedelta(seconds=5)
     )
     self.comment_2.report_abuse(
         user=self.user_2,
         save=True,
         category='spam',
         date=date - timedelta(seconds=4)
     )
     self.comment_3.report_abuse(
         user=self.user_2,
         save=True,
         category='spam',
         date=date - timedelta(seconds=3)
     )
     self.comment_4.report_abuse(
         user=self.user_2,
         save=True,
         category='spam',
         date=date - timedelta(seconds=2)
     )
     self.comment_5.report_abuse(
         user=self.user_1,
         save=True,
         category='spam',
         date=date - timedelta(seconds=1)
     )
     self.comment_6.report_abuse(user=self.user_1, save=True,
                                 category='spam')
     self.request = RequestFactory().get('/fake_path')
     self.view = SpamList()
     self.view = setup_view(self.view, self.request, user_id=self.user_1._id)
Esempio n. 27
0
 def user_one(self):
     user_one = AuthUserFactory(fullname='Kanye Omari West')
     user_one.schools = [{
         'degree': 'English',
         'institution': 'Chicago State University'
     }]
     user_one.jobs = [{
         'title': 'Producer',
         'institution': 'GOOD Music, Inc.'
     }]
     user_one.save()
     return user_one
Esempio n. 28
0
    def test_correct_view_permissions(self):
        user = AuthUserFactory()

        view_permission = Permission.objects.get(codename='view_conference')
        user.user_permissions.add(view_permission)
        user.save()

        request = RequestFactory().get(reverse('meetings:list'))
        request.user = user

        response = MeetingListView.as_view()(request)
        nt.assert_equal(response.status_code, 200)
Esempio n. 29
0
    def test_correct_view_permissions(self):
        user = AuthUserFactory()

        view_permission = Permission.objects.get(codename='view_preprintservice')
        user.user_permissions.add(view_permission)
        user.save()

        request = RequestFactory().get(reverse('preprints:preprint', kwargs={'guid': self.preprint._id}))
        request.user = user

        response = self.view.as_view()(request, guid=self.preprint._id)
        nt.assert_equal(response.status_code, 200)
 def test_many_users_each_with_a_different_github(self):
     user = AuthUserFactory()
     user.add_addon('github')
     oauth_settings2 = GitHubAccountFactory(display_name='hmoco2')
     oauth_settings2.save()
     user.external_accounts.add(oauth_settings2)
     user.save()
     results = AddonSnapshot().get_events()
     github_res = [res for res in results if res['provider']['name'] == 'github'][0]
     assert_equal(github_res['users']['enabled'], 2)
     assert_equal(github_res['users']['authorized'], 1)
     assert_equal(github_res['users']['linked'], 1)
 def admin_contributor_bib(self):
     return AuthUserFactory(given_name='Oranges')
Esempio n. 32
0
 def setUp(self):
     super(TestRdmUserKey, self).setUp()
     self.user = AuthUserFactory()
 def read_write_contrib(self):
     return AuthUserFactory()
Esempio n. 34
0
class TestAccountsView(AdminTestCase):
    def setUp(self):
        super(TestAccountsView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()

        self.rdm_addon_option = rdm_addon_factories.RdmAddonOptionFactory()
        self.rdm_addon_option.provider = self.external_account.provider
        self.rdm_addon_option.external_accounts.add(self.external_account)
        self.rdm_addon_option.save()

        self.user.affiliated_institutions.add(
            self.rdm_addon_option.institution)
        self.user.external_accounts.add(self.external_account)
        self.user.save()

        self.request = RequestFactory().get('/fake_path')
        self.view = views.AccountsView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'external_account_id': self.external_account._id,
            'institution_id': self.rdm_addon_option.institution.id,
        }

    def tearDown(self):
        super(TestAccountsView, self).tearDown()
        institution = self.rdm_addon_option.institution
        self.user.affiliated_institutions.remove(institution)
        if self.user.external_accounts.filter(
                pk=self.external_account.id).exists():
            self.user.external_accounts.remove(self.external_account)
        self.user.delete()
        if self.rdm_addon_option.external_accounts.filter(
                pk=self.external_account.id).exists():
            self.rdm_addon_option.external_accounts.remove(
                self.external_account)
        self.rdm_addon_option.delete()
        institution.delete()
        self.external_account.delete()

    def test_super_admin_login(self):
        """test superuser login"""
        self.request.user.is_superuser = True
        nt.assert_true(self.view.test_func())

    def test_admin_login(self):
        """test institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        nt.assert_true(self.view.test_func())

    def test_non_admin_login(self):
        """test user not superuser or institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_active_user_login(self):
        """test invalid user login"""
        self.request.user.is_active = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_registered_user_login(self):
        """test unregistered user login"""
        self.request.user.is_registered = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_affiliated_institution_user_login(self):
        """test user unaffiliated institution login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        self.view.kwargs = {
            'institution_id': self.rdm_addon_option.institution.id + 1
        }
        nt.assert_equal(self.view.test_func(), False)

    def test_delete(self, *args, **kwargs):
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        nt.assert_equal(self.user.external_accounts.count(), 1)
        nt.assert_equal(self.rdm_addon_option.external_accounts.count(), 1)
Esempio n. 35
0
def user_two():
    return AuthUserFactory()
Esempio n. 36
0
 def affiliated_user(self, institution):
     user = AuthUserFactory()
     user.affiliated_institutions.add(institution)
     user.save()
     return user
 def user_admin_contrib(self):
     return AuthUserFactory()
Esempio n. 38
0
 def moderator_pair(self, expected_providers):
     user = AuthUserFactory()
     provider = expected_providers[0]
     user.groups.add(GroupHelper(provider).get_group('moderator'))
     return (user, provider)
Esempio n. 39
0
 def admin_pair(self, expected_providers):
     user = AuthUserFactory()
     provider = expected_providers[1]
     user.groups.add(GroupHelper(provider).get_group('admin'))
     return (user, provider)
Esempio n. 40
0
 def user(self, allowed_providers):
     user = AuthUserFactory()
     for provider in allowed_providers:
         user.groups.add(GroupHelper(provider).get_group('moderator'))
     return user
Esempio n. 41
0
 def moderator(self, provider):
     user = AuthUserFactory()
     provider.add_to_group(user, 'moderator')
     return user
Esempio n. 42
0
 def user(self):
     return AuthUserFactory()
    def test_update_registration(
            self, app, user, read_only_contributor,
            read_write_contributor, public_registration,
            public_url, private_url, make_payload, public_project):

        private_registration_payload = make_payload()
        non_contributor = AuthUserFactory()

    #   test_update_private_registration_logged_out
        res = app.put_json_api(
            private_url,
            private_registration_payload,
            expect_errors=True)
        assert res.status_code == 401

    #   test_update_private_registration_logged_in_admin
        res = app.put_json_api(
            private_url,
            private_registration_payload,
            auth=user.auth)
        assert res.status_code == 200
        assert res.json['data']['attributes']['public'] is True

    #   test_update_private_registration_logged_in_read_only_contributor
        res = app.put_json_api(
            private_url,
            private_registration_payload,
            auth=read_only_contributor.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_update_private_registration_logged_in_read_write_contributor
        res = app.put_json_api(
            private_url,
            private_registration_payload,
            auth=read_write_contributor.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_update_public_registration_to_private
        public_to_private_payload = make_payload(
            id=public_registration._id, attributes={'public': False})

        res = app.put_json_api(
            public_url,
            public_to_private_payload,
            auth=user.auth,
            expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0]['detail'] == 'Registrations can only be turned from private to public.'

        res = app.put_json_api(
            public_url,
            public_to_private_payload,
            auth=non_contributor.auth,
            expect_errors=True)
        assert res.status_code == 403
        assert res.json['errors'][0]['detail'] == 'You do not have permission to perform this action.'

    #   test_osf_group_member_write_cannot_update_registration
        group_mem = AuthUserFactory()
        group = OSFGroupFactory(creator=group_mem)
        public_project.add_osf_group(group, permissions.WRITE)
        res = app.put_json_api(
            public_url,
            public_to_private_payload,
            auth=group_mem.auth,
            expect_errors=True)
        assert res.status_code == 403

    #   test_osf_group_member_admin_cannot_update_registration
        public_project.remove_osf_group(group)
        public_project.add_osf_group(group, permissions.ADMIN)
        res = app.put_json_api(
            public_url,
            public_to_private_payload,
            auth=group_mem.auth,
            expect_errors=True)
        assert res.status_code == 403
Esempio n. 44
0
    def test_serialize_record_datacite(self, node, osf_file):
        # Test all of the parts of serialize_json that are auto-generated
        # from relationships and properties on the node and file

        # add a contributor with an ORCID
        contributor = AuthUserFactory()
        contributor.external_identity = {
            'ORCID': {
                '0000-0001-9143-4653': 'VERIFIED'
            }
        }
        contributor.save()
        node.add_contributor(contributor, save=False)

        # add subjects, tags, license, and guid
        tags = ['fish', 'scale']
        [
            osf_file.add_tag(tag, auth=Auth(node.creator), save=False)
            for tag in tags
        ]
        bepress_subject = SubjectFactory(text='BePress Text')
        new_subject = SubjectFactory(bepress_subject=bepress_subject)
        node.subjects.add(new_subject)
        no_license = NodeLicense.objects.get(name='CC0 1.0 Universal')
        license_detail = {
            'id': no_license.license_id,
            'year': '2018',
            'copyrightHolders': ['Woop', 'Yeah']
        }

        set_license(node, license_detail, Auth(node.creator))

        osf_file.save()
        node.save()
        osf_file.target.reload()

        record = osf_file.records.get(schema___id='datacite')
        serialized_record = json.loads(record.serialize())

        # test titles
        titles = [title['title'] for title in serialized_record['titles']]
        assert osf_file.name in titles
        assert node.title in titles

        # test dates
        dates = [date['date'] for date in serialized_record['dates']]
        assert str(osf_file.created) in dates
        assert str(osf_file.modified) in dates
        assert str(
            osf_file.created.year) == serialized_record['publicationYear']

        # no resource type provided
        assert serialized_record['resourceType']['resourceType'] == '(:unas)'
        assert serialized_record['resourceType'][
            'resourceTypeGeneral'] == 'Other'

        # guid in alternate identifiers
        file_guid = osf_file.guids.first()._id
        alternate_identifier = serialized_record['alternateIdentifiers'][0]
        assert file_guid in alternate_identifier['alternateIdentifier']

        # check for tags and subjects
        subjects_in_record = [
            sub['subject'] for sub in serialized_record['subjects']
        ]
        assert bepress_subject.text in subjects_in_record
        for tag in tags:
            assert tag in subjects_in_record

        # node license
        rights = serialized_record['rightsList'][0]
        assert rights['rights'] == no_license.name
        assert rights['rightsURI'] == no_license.url

        # test most recent version
        assert serialized_record['version'] == osf_file.versions.first(
        ).identifier
Esempio n. 45
0
    def test_creates_child(self, app, user, project, child, url):

        #   test_creates_child_logged_out_user
        res = app.post_json_api(url, child, expect_errors=True)
        assert res.status_code == 401

        project.reload()
        assert len(project.nodes) == 0

    #   test_creates_child_logged_in_read_contributor
        read_contrib = AuthUserFactory()
        project.add_contributor(
            read_contrib,
            permissions=[permissions.READ],
            auth=Auth(user), save=True
        )
        res = app.post_json_api(
            url, child, auth=read_contrib.auth,
            expect_errors=True
        )
        assert res.status_code == 403

        project.reload()
        assert len(project.nodes) == 0

    #   test_creates_child_logged_in_non_contributor
        non_contrib = AuthUserFactory()
        res = app.post_json_api(
            url, child, auth=non_contrib.auth,
            expect_errors=True
        )
        assert res.status_code == 403

        project.reload()
        assert len(project.nodes) == 0

    #   test_creates_child_no_type
        child = {
            'data': {
                'attributes': {
                    'title': 'child',
                    'description': 'this is a child project',
                    'category': 'project',
                }
            }
        }
        res = app.post_json_api(url, child, auth=user.auth, expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0]['detail'] == 'This field may not be null.'
        assert res.json['errors'][0]['source']['pointer'] == '/data/type'

    #   test_creates_child_incorrect_type
        child = {
            'data': {
                'type': 'Wrong type.',
                'attributes': {
                    'title': 'child',
                    'description': 'this is a child project',
                    'category': 'project',
                }
            }
        }
        res = app.post_json_api(url, child, auth=user.auth, expect_errors=True)
        assert res.status_code == 409
        assert res.json['errors'][0]['detail'] == 'This resource has a type of "nodes", but you set the json body\'s type field to "Wrong type.". You probably need to change the type field to match the resource\'s type.'

    #   test_creates_child_properties_not_nested
        child = {
            'data': {
                'attributes': {
                    'title': 'child',
                    'description': 'this is a child project'
                },
                'category': 'project'
            }
        }
        res = app.post_json_api(url, child, auth=user.auth, expect_errors=True)
        assert res.status_code == 400
        assert res.json['errors'][0]['detail'] == 'This field is required.'
        assert res.json['errors'][0]['source']['pointer'] == '/data/attributes/category'
 def non_contributor(self):
     return AuthUserFactory()
Esempio n. 47
0
    def test_add_incorrect_permissions(self, app, admin, user, affiliated_user,
                                       registration_no_affiliation,
                                       url_institution_registrations,
                                       institution):
        # No authentication
        res = app.post_json_api(
            url_institution_registrations,
            make_registration_payload(registration_no_affiliation._id),
            expect_errors=True,
        )
        assert res.status_code == 401

        # User has no permission
        res = app.post_json_api(url_institution_registrations,
                                make_registration_payload(
                                    registration_no_affiliation._id),
                                expect_errors=True,
                                auth=AuthUserFactory().auth)
        assert res.status_code == 403

        # User has read permission
        registration_no_affiliation.add_contributor(
            affiliated_user, permissions=permissions.READ)
        registration_no_affiliation.save()

        res = app.post_json_api(url_institution_registrations,
                                make_registration_payload(
                                    registration_no_affiliation._id),
                                auth=user.auth,
                                expect_errors=True)
        assert res.status_code == 403

        # User is admin but not affiliated
        registration = RegistrationFactory(creator=user)
        res = app.post_json_api(url_institution_registrations,
                                make_registration_payload(registration._id),
                                expect_errors=True,
                                auth=user.auth)
        assert res.status_code == 403
        registration.reload()
        assert institution not in registration.affiliated_institutions.all()

        # Registration does not exist
        res = app.post_json_api(url_institution_registrations,
                                make_registration_payload('notIdatAll'),
                                expect_errors=True,
                                auth=admin.auth)
        assert res.status_code == 404

        # Attempt to use endpoint on Node
        res = app.post_json_api(url_institution_registrations, {
            'data': [{
                'type': 'nodes',
                'id': NodeFactory(creator=admin)._id
            }]
        },
                                expect_errors=True,
                                auth=admin.auth)
        assert res.status_code == 409

        registration_no_affiliation.reload()
        assert institution not in registration_no_affiliation.affiliated_institutions.all(
        )
Esempio n. 48
0
def user_one():
    return AuthUserFactory()
Esempio n. 49
0
 def user(self, institution):
     return AuthUserFactory()
Esempio n. 50
0
 def moderator(self, provider):
     moderator = AuthUserFactory()
     moderator.groups.add(GroupHelper(provider).get_group('moderator'))
     return moderator
 def read_contributor_bib(self):
     return AuthUserFactory(given_name='Grapes')
Esempio n. 52
0
 def setUp(self):
     super(TestCompleteView, self).setUp()
     self.user = AuthUserFactory()
     self.request = RequestFactory().get('/fake_path')
     self.view = views.CompleteView()
     self.view = setup_user_view(self.view, self.request, user=self.user)
Esempio n. 53
0
    def test_create_permissions(self, app, url, preprint, node_admin,
                                moderator):
        assert preprint.machine_state == 'initial'

        submit_payload = self.create_payload(preprint._id, trigger='submit')

        # Unauthorized user can't submit
        res = app.post_json_api(url, submit_payload, expect_errors=True)
        assert res.status_code == 401

        # A random user can't submit
        some_rando = AuthUserFactory()
        res = app.post_json_api(url,
                                submit_payload,
                                auth=some_rando.auth,
                                expect_errors=True)
        assert res.status_code == 403

        # Node admin can submit
        res = app.post_json_api(url, submit_payload, auth=node_admin.auth)
        assert res.status_code == 201
        preprint.refresh_from_db()
        assert preprint.machine_state == 'pending'
        assert not preprint.is_published

        accept_payload = self.create_payload(preprint._id,
                                             trigger='accept',
                                             comment='This is good.')

        # Unauthorized user can't accept
        res = app.post_json_api(url, accept_payload, expect_errors=True)
        assert res.status_code == 401

        # A random user can't accept
        res = app.post_json_api(url,
                                accept_payload,
                                auth=some_rando.auth,
                                expect_errors=True)
        assert res.status_code == 403

        # Moderator from another provider can't accept
        another_moderator = AuthUserFactory()
        another_moderator.groups.add(
            GroupHelper(PreprintProviderFactory()).get_group('moderator'))
        res = app.post_json_api(url,
                                accept_payload,
                                auth=another_moderator.auth,
                                expect_errors=True)
        assert res.status_code == 403

        # Node admin can't accept
        res = app.post_json_api(url,
                                accept_payload,
                                auth=node_admin.auth,
                                expect_errors=True)
        assert res.status_code == 403

        # Still unchanged after all those tries
        preprint.refresh_from_db()
        assert preprint.machine_state == 'pending'
        assert not preprint.is_published

        # Moderator can accept
        res = app.post_json_api(url, accept_payload, auth=moderator.auth)
        assert res.status_code == 201
        preprint.refresh_from_db()
        assert preprint.machine_state == 'accepted'
        assert preprint.is_published
 def user_admin(self):
     return AuthUserFactory()
Esempio n. 55
0
 def node_admin(self):
     return AuthUserFactory()
Esempio n. 56
0
def user():
    return AuthUserFactory()
 def write_contributor_non_bib(self):
     return AuthUserFactory()
Esempio n. 58
0
 def other_user(self):
     return AuthUserFactory()
Esempio n. 59
0
class TestConnectView(AdminTestCase):
    def setUp(self):
        super(TestConnectView, self).setUp()
        self.user = AuthUserFactory()
        self.external_account = ExternalAccountFactory()
        self.institution = InstitutionFactory()

        self.user.affiliated_institutions.add(self.institution)

        self.provider = MockOAuth2Provider(self.external_account)

        self.request = RequestFactory().get('/fake_path')
        add_session_to_request(self.request)
        self.view = views.ConnectView()
        self.view = setup_user_view(self.view, self.request, user=self.user)
        self.view.kwargs = {
            'addon_name': self.external_account.provider,
            'institution_id': self.institution.id,
        }

    def tearDown(self):
        super(TestConnectView, self).tearDown()
        self.user.affiliated_institutions.remove(self.institution)
        self.user.delete()
        self.institution.delete()
        self.external_account.delete()

    def test_super_admin_login(self):
        """test superuser login"""
        self.request.user.is_superuser = True
        nt.assert_true(self.view.test_func())

    def test_admin_login(self):
        """test institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        nt.assert_true(self.view.test_func())

    def test_non_admin_login(self):
        """test user not superuser or institution administrator login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_active_user_login(self):
        """test invalid user login"""
        self.request.user.is_active = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_registered_user_login(self):
        """test unregistered user login"""
        self.request.user.is_registered = False
        nt.assert_equal(self.view.test_func(), False)

    def test_non_affiliated_institution_user_login(self):
        """test user unaffiliated institution login"""
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        self.view.kwargs = {'institution_id': self.institution.id + 1}
        nt.assert_equal(self.view.test_func(), False)

    def test_get(self, *args, **kwargs):
        self.request.user.is_superuser = False
        self.request.user.is_staff = True
        res = self.view.get(self.request, *args, **self.view.kwargs)
        nt.assert_equal(res.status_code, 302)
Esempio n. 60
0
 def setUp(self):
     super(TestViews, self).setUp()
     self.user = AuthUserFactory()
     self.user_addon = self.user.get_or_add_addon('twofactor')
     self.user_settings = self.user.get_addon('twofactor')