Exemplo n.º 1
0
 def setUp(self):
     self.user = UserFactory()
     self.public_node = ProjectFactory(creator=self.user, is_public=True)
     self.public_node = ProjectFactory(creator=self.user, is_public=False)
     self.request = RequestFactory().post('/fake_path')
     self.view = views.SpamUserDeleteView
     self.view = setup_log_view(self.view, self.request, guid=self.user._id)
Exemplo n.º 2
0
    def test_fork_reverts_to_using_user_storage_default(self):
        user = UserFactory()
        user2 = UserFactory()
        us = RegionFactory()
        canada = RegionFactory()

        user_settings = user.get_addon('osfstorage')
        user_settings.default_region = us
        user_settings.save()
        user2_settings = user2.get_addon('osfstorage')
        user2_settings.default_region = canada
        user2_settings.save()

        project = ProjectFactory(creator=user, is_public=True)
        child = NodeFactory(parent=project, creator=user, is_public=True)
        child_settings = child.get_addon('osfstorage')
        child_settings.region_id = canada.id
        child_settings.save()

        fork = project.fork_node(Auth(user))
        child_fork = models.Node.objects.get_children(fork).first()
        assert fork.get_addon('osfstorage').region_id == us.id
        assert fork.get_addon('osfstorage').user_settings == user.get_addon('osfstorage')
        assert child_fork.get_addon('osfstorage').region_id == us.id

        fork = project.fork_node(Auth(user2))
        child_fork = models.Node.objects.get_children(fork).first()
        assert fork.get_addon('osfstorage').region_id == canada.id
        assert fork.get_addon('osfstorage').user_settings == user2.get_addon('osfstorage')
        assert child_fork.get_addon('osfstorage').region_id == canada.id
Exemplo n.º 3
0
    def setUp(self):
        super(TestRegistrationFiltering, self).setUp()
        self.user_one = AuthUserFactory()
        self.user_two = AuthUserFactory()
        self.project_one = ProjectFactory(title="Project One", description='Two', is_public=True, creator=self.user_one, category='hypothesis')
        self.project_two = ProjectFactory(title="Project Two", description="One Three", is_public=True, creator=self.user_one)
        self.project_three = ProjectFactory(title="Three", is_public=True, creator=self.user_two)


        self.private_project_user_one = ProjectFactory(title="Private Project User One",
                                                       is_public=False,
                                                       creator=self.user_one)
        self.private_project_user_two = ProjectFactory(title="Private Project User Two",
                                                       is_public=False,
                                                       creator=self.user_two)

        self.project_one.add_tag('tag1', Auth(self.project_one.creator), save=False)
        self.project_one.add_tag('tag2', Auth(self.project_one.creator), save=False)
        self.project_one.save()
        self.project_two.add_tag('tag1', Auth(self.project_two.creator), save=True)
        self.project_two.save()

        self.project_one_reg = RegistrationFactory(creator=self.user_one, project=self.project_one, is_public=True)
        self.project_two_reg = RegistrationFactory(creator=self.user_one, project=self.project_two, is_public=True)
        self.project_three_reg = RegistrationFactory(creator=self.user_two, project=self.project_three, is_public=True)
        self.private_project_user_one_reg = RegistrationFactory(creator=self.user_one, project=self.private_project_user_one, is_public=False)
        self.private_project_user_two_reg = RegistrationFactory(creator=self.user_two, project=self.private_project_user_two, is_public=False)

        self.folder = CollectionFactory()
        self.bookmark_collection = find_bookmark_collection(self.user_one)

        self.url = "/{}registrations/".format(API_BASE)
    def test_unregistered_contributor_added_has_contributor_info_in_params(
            self, app, user_one):
        project = ProjectFactory(creator=user_one)
        project.add_unregistered_contributor(
            'Robert Jackson',
            '*****@*****.**',
            auth=Auth(user_one), save=True
        )
        relevant_log = project.logs.latest()
        url = '/{}logs/{}/'.format(API_BASE, relevant_log._id)
        res = app.get(url, auth=user_one.auth)

        assert res.status_code == 200

        params = res.json['data']['attributes']['params']
        params_node = params['params_node']
        contributors = params['contributors'][0]

        assert params_node['id'] == project._id
        assert params_node['title'] == project.title

        assert contributors['family_name'] == 'Jackson'
        assert contributors['full_name'] == 'Robert Jackson'
        assert contributors['given_name'] == 'Robert'
        assert contributors['unregistered_name'] == 'Robert Jackson'
    def test_cannot_delete_if_registration(
            self, app, user, public_project, user_two, public_pointer):
        registration = RegistrationFactory(project=public_project)

        url = '/{}registrations/{}/node_links/'.format(
            API_BASE,
            registration._id,
        )
        res = app.get(url, auth=user.auth)
        assert res.status_code == 200
        pointer_id = res.json['data'][0]['id']

        # registration delete nodelink to a project
        url = '/{}registrations/{}/node_links/{}/'.format(
            API_BASE,
            registration._id,
            pointer_id,
        )
        res = app.delete(url, auth=user.auth, expect_errors=True)
        assert res.status_code == 405

        # registration delete nodelink to a registration
        project_user_two = ProjectFactory(creator=user_two, is_public=False)
        pointer = project_user_two.add_pointer(
            registration, auth=Auth(user_two), save=True)
        registration_user_two = RegistrationFactory(
            project=project_user_two, creator=user_two)

        url = '/{}registrations/{}/node_links/{}/'.format(
            API_BASE,
            registration_user_two._id,
            pointer._id,
        )
        res = app.delete(url, auth=user_two.auth, expect_errors=True)
        assert res.status_code == 405
Exemplo n.º 6
0
 def project(self, user_admin_contrib, user_write_contrib):
     project = ProjectFactory(creator=user_admin_contrib, is_public=True)
     project.add_contributor(
         user_write_contrib,
         permissions=permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS,
         save=True)
     return project
Exemplo n.º 7
0
class TestNodeConfirmHamView(AdminTestCase):
    def setUp(self):
        super(TestNodeConfirmHamView, self).setUp()

        self.request = RequestFactory().post('/fake_path')
        self.user = AuthUserFactory()

        self.node = ProjectFactory(creator=self.user)
        self.registration = RegistrationFactory(creator=self.user)

    def test_confirm_node_as_ham(self):
        view = NodeConfirmHamView()
        view = setup_log_view(view, self.request, guid=self.node._id)
        view.delete(self.request)

        self.node.refresh_from_db()
        nt.assert_true(self.node.spam_status == 4)

    def test_confirm_registration_as_ham(self):
        view = NodeConfirmHamView()
        view = setup_log_view(view, self.request, guid=self.registration._id)
        view.delete(self.request)

        self.registration.refresh_from_db()
        nt.assert_true(self.registration.spam_status == 4)
Exemplo n.º 8
0
    def test__initiate_embargo_adds_admins_on_child_nodes(self):
        project_admin = UserFactory()
        project_non_admin = UserFactory()
        child_admin = UserFactory()
        child_non_admin = UserFactory()
        grandchild_admin = UserFactory()

        project = ProjectFactory(creator=project_admin)
        project.add_contributor(project_non_admin, auth=Auth(project.creator), save=True)

        child = NodeFactory(creator=child_admin, parent=project)
        child.add_contributor(child_non_admin, auth=Auth(child.creator), save=True)

        grandchild = NodeFactory(creator=grandchild_admin, parent=child)  # noqa

        registration = RegistrationFactory(project=project)

        embargo = registration._initiate_embargo(
            project.creator,
            self.valid_embargo_end_date,
            for_existing_registration=True
        )
        assert_in(project_admin._id, embargo.approval_state)
        assert_in(child_admin._id, embargo.approval_state)
        assert_in(grandchild_admin._id, embargo.approval_state)

        assert_not_in(project_non_admin._id, embargo.approval_state)
        assert_not_in(child_non_admin._id, embargo.approval_state)
Exemplo n.º 9
0
class TestPreprintConfirmationEmails(OsfTestCase):
    def setUp(self):
        super(TestPreprintConfirmationEmails, self).setUp()
        self.user = AuthUserFactory()
        self.write_contrib = AuthUserFactory()
        self.project = ProjectFactory(creator=self.user)
        self.project.add_contributor(self.write_contrib, permissions=[permissions.WRITE])
        self.preprint = PreprintFactory(project=self.project, provider=PreprintProviderFactory(_id='osf'), is_published=False)
        self.preprint_branded = PreprintFactory(creator=self.user, is_published=False)

    @mock.patch('website.mails.send_mail')
    def test_creator_gets_email(self, send_mail):
        self.preprint.set_published(True, auth=Auth(self.user), save=True)
        domain = self.preprint.provider.domain or settings.DOMAIN
        send_mail.assert_called_with(
            self.user.email,
            mails.REVIEWS_SUBMISSION_CONFIRMATION,
            user=self.user,
            mimetype='html',
            provider_url='{}preprints/{}'.format(domain, self.preprint.provider._id),
            domain=domain,
            provider_contact_email=settings.OSF_CONTACT_EMAIL,
            provider_support_email=settings.OSF_SUPPORT_EMAIL,
            workflow=None,
            reviewable=self.preprint,
            is_creator=True,
            provider_name=self.preprint.provider.name,
            no_future_emails=[],
            logo=settings.OSF_PREPRINTS_LOGO,
        )
        assert_equals(send_mail.call_count, 1)

        self.preprint_branded.set_published(True, auth=Auth(self.user), save=True)
        assert_equals(send_mail.call_count, 2)
Exemplo n.º 10
0
    def setUp(self):
        super(LogsTestCase, self).setUp()

        self.user = AuthUserFactory()
        self.user_two = AuthUserFactory()

        self.action_set = NodeLog.actions
        self.node = ProjectFactory(is_public=False)

        self.node.add_contributor(self.user, permissions=[osf_permissions.READ], auth=Auth(self.node.creator), log=True, save=True)

        logs = list(self.node.logs.order_by('date'))
        self.log = logs[0]
        self.log_add_contributor = logs[1]

        self.public_node = ProjectFactory(is_public=True)
        self.public_node.add_contributor(self.user, permissions=[osf_permissions.READ], auth=Auth(self.public_node.creator), log=True, save=True)

        public_logs = list(self.public_node.logs.order_by('date'))
        self.public_log = public_logs[0]
        self.public_log_add_contributor = public_logs[1]

        self.node_log_url = '/{}nodes/{}/logs/'.format(API_BASE, self.node._id)
        self.url = '/{}logs/'.format(API_BASE)
        self.log_nodes_url = self.url + '{}/nodes/'.format(self.log._id)
        self.private_log_detail = self.url + '{}/'.format(self.log._id)
        self.log_public_nodes_url = self.url + '{}/nodes/'.format(self.public_log._id)
        self.public_log_detail = self.url + '{}/'.format(self.public_log._id)
Exemplo n.º 11
0
 def test_node_citation_view(self):
     node = ProjectFactory()
     user = AuthUserFactory()
     node.add_contributor(user)
     node.save()
     response = self.app.get("/api/v1" + "/project/" + node._id + "/citation/", auto_follow=True, auth=user.auth)
     assert_true(response.json)
Exemplo n.º 12
0
    def test_move_file_out_of_node(self):
        folder = self.root_node.append_folder('A long time ago')
        file = folder.append_file('in a galaxy')
        # project having a preprint should not block other moves
        preprint_file = self.root_node.append_file('far')
        self.node.preprint_file = preprint_file
        self.node.save()

        project = ProjectFactory(creator=self.user)
        project_settings = project.get_addon('osfstorage')
        project_root_node = project_settings.get_root()

        folder_two = project_root_node.append_folder('far away')
        res = self.send_hook(
            'osfstorage_move_hook',
            {'nid': self.root_node.node._id},
            payload={
                'source': folder._id,
                'node': self.root_node._id,
                'user': self.user._id,
                'destination': {
                    'parent': folder_two._id,
                    'node': folder_two.node._id,
                    'name': folder_two.name,
                }
            },
            method='post_json',
            expect_errors=True,
        )
        assert_equal(res.status_code, 200)
Exemplo n.º 13
0
    def test_has_permission_on_parent_node_copyfrom(self):
        component_admin = AuthUserFactory()
        component = ProjectFactory(creator=component_admin, is_public=False, parent=self.node)

        assert_false(component.has_permission(self.user, 'write'))
        res = views.check_access(component, Auth(user=self.user), 'copyfrom', None)
        assert_true(res)
Exemplo n.º 14
0
    def test_merge_user_settings(self):
        other_node = ProjectFactory()
        other_user = other_node.creator
        other_account = self.ExternalAccountFactory()
        other_user.external_accounts.add(other_account)
        other_user_settings = other_user.get_or_add_addon(self.short_name)
        other_node_settings = other_node.get_or_add_addon(self.short_name, auth=Auth(other_user))
        other_node_settings.set_auth(
            user=other_user,
            external_account=other_account
        )

        assert other_node_settings.has_auth
        assert other_node._id not in self.user_settings.oauth_grants
        assert other_node_settings.user_settings == other_user_settings

        self.user.merge_user(other_user)
        self.user.save()

        other_node_settings.reload()
        self.user_settings.reload()

        assert other_node_settings.has_auth
        assert other_node._id in self.user_settings.oauth_grants
        assert other_node_settings.user_settings == self.user_settings
Exemplo n.º 15
0
class TestPreprintConfirmationEmails(OsfTestCase):
    def setUp(self):
        super(TestPreprintConfirmationEmails, self).setUp()
        self.user = AuthUserFactory()
        self.write_contrib = AuthUserFactory()
        self.project = ProjectFactory(creator=self.user)
        self.project.add_contributor(self.write_contrib, permissions=[permissions.WRITE])
        self.preprint = PreprintFactory(project=self.project, provider=PreprintProviderFactory(_id='osf'), is_published=False)
        self.preprint_branded = PreprintFactory(creator=self.user, is_published=False)

    @mock.patch('website.mails.send_mail')
    def test_creator_gets_email(self, send_mail):
        self.preprint.set_published(True, auth=Auth(self.user), save=True)

        send_mail.assert_called_with(
            self.user.email,
            mails.PREPRINT_CONFIRMATION_DEFAULT,
            user=self.user,
            node=self.preprint.node,
            preprint=self.preprint
        )

        assert_equals(send_mail.call_count, 1)

        self.preprint_branded.set_published(True, auth=Auth(self.user), save=True)
        assert_equals(send_mail.call_count, 2)
Exemplo n.º 16
0
 def test_sees_projects_in_her_dashboard(self):
     # the user already has a project
     project = ProjectFactory(creator=self.user)
     project.add_contributor(self.user)
     project.save()
     res = self.app.get('/myprojects/', auth=self.user.auth)
     assert_in('Projects', res)  # Projects heading
Exemplo n.º 17
0
    def project_with_different_regions(self, user):
        """
        A complex project configuration with many regions.
        :param user:
        :return:
        """
        parent_node = root_node = ProjectFactory(creator=user)

        # components have nested children
        for _ in range(0, 1):
            parent_node = ProjectFactory(creator=user, parent=parent_node)
            addon = parent_node.get_addon('osfstorage')
            addon.region = RegionFactory()
            addon.save()

        # root project has two direct children
        for _ in range(0, 1):
            parent_node = ProjectFactory(creator=user, parent=root_node)
            addon = parent_node.get_addon('osfstorage')
            addon.region = RegionFactory()
            addon.save()

        addon = root_node.get_addon('osfstorage')
        addon.region = RegionFactory()
        addon.save()

        return root_node
Exemplo n.º 18
0
    def test_move_preprint_file_out_of_node(self):
        folder = self.root_node.append_folder('From Here')
        file = folder.append_file('No I don\'t wanna go')
        self.node.preprint_file = file
        self.node.save()

        project = ProjectFactory(creator=self.user)
        project_settings = project.get_addon('osfstorage')
        project_root_node = project_settings.get_root()

        folder_two = project_root_node.append_folder('To There')
        res = self.send_hook(
            'osfstorage_move_hook',
            {'nid': self.root_node.node._id},
            payload={
                'source': folder._id,
                'node': self.root_node._id,
                'user': self.user._id,
                'destination': {
                    'parent': folder_two._id,
                    'node': folder_two.node._id,
                    'name': folder_two.name,
                }
            },
            method='post_json',
            expect_errors=True,
        )
        assert_equal(res.status_code, 403)
    def test_cannot_create_draft_errors(
            self, app, user, project_public, payload):

        #   test_cannot_create_draft_from_a_registration
        registration = RegistrationFactory(
            project=project_public, creator=user)
        url = '/{}nodes/{}/draft_registrations/'.format(
            API_BASE, registration._id)
        res = app.post_json_api(
            url, payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 404

    #   test_cannot_create_draft_from_deleted_node
        project = ProjectFactory(is_public=True, creator=user)
        project.is_deleted = True
        project.save()
        url_project = '/{}nodes/{}/draft_registrations/'.format(
            API_BASE, project._id)
        res = app.post_json_api(
            url_project, payload,
            auth=user.auth, expect_errors=True)
        assert res.status_code == 410
        assert res.json['errors'][0]['detail'] == 'The requested node is no longer available.'

    #   test_cannot_create_draft_from_collection
        collection = CollectionFactory(creator=user)
        url = '/{}nodes/{}/draft_registrations/'.format(
            API_BASE, collection._id)
        res = app.post_json_api(
            url, payload, auth=user.auth,
            expect_errors=True)
        assert res.status_code == 404
Exemplo n.º 20
0
    def test_has_permission_on_parent_node_copyto_fail_if_not_registration(self):
        component_admin = AuthUserFactory()
        component = ProjectFactory(creator=component_admin, parent=self.node)

        assert_false(component.has_permission(self.user, 'write'))
        with assert_raises(HTTPError):
            views.check_access(component, Auth(user=self.user), 'copyto', None)
Exemplo n.º 21
0
 def project(self, user, user_write_contrib):
     project = ProjectFactory(creator=user)
     project.add_contributor(
         user_write_contrib,
         permissions=[permissions.READ, permissions.WRITE],
         visible=True, save=True)
     return project
Exemplo n.º 22
0
    def test_serializing_log_with_legacy_non_registered_contributor_data(self, fake):
        # Old logs store unregistered contributors in params as dictionaries of the form:
        # {
        #     'nr_email': <email>,
        #     'nr_name': <name>,
        # }
        # This test ensures that the NodeLogSerializer can handle this legacy data.
        project = ProjectFactory()
        user = UserFactory()
        request = make_drf_request_with_version()
        nr_data = {'nr_email': fake.email(), 'nr_name': fake.name()}
        log = project.add_log(
            action=NodeLog.CONTRIB_ADDED,
            auth=Auth(project.creator),
            params={
                'project': project._id,
                'node': project._id,
                'contributors': [user._id, nr_data],
            }
        )
        serialized = NodeLogSerializer(log, context={'request': request}).data
        contributor_data = serialized['data']['attributes']['params']['contributors']
        # contributor_data will have two dicts:
        # the first will be the registered contrib, 2nd will be non-reg contrib
        reg_contributor_data, unreg_contributor_data = contributor_data
        assert reg_contributor_data['id'] == user._id
        assert reg_contributor_data['full_name'] == user.fullname

        assert unreg_contributor_data['id'] is None
        assert unreg_contributor_data['full_name'] == nr_data['nr_name']
Exemplo n.º 23
0
    def setUp(self):
        super(TestMustBeContributorOrPublicButNotAnonymizedDecorator, self).setUp()
        self.contrib = AuthUserFactory()
        self.non_contrib = AuthUserFactory()
        admin = UserFactory()
        self.public_project = ProjectFactory(is_public=True)
        self.public_project.add_contributor(admin, auth=Auth(self.public_project.creator), permissions=['read', 'write', 'admin'])
        self.private_project = ProjectFactory(is_public=False)
        self.private_project.add_contributor(admin, auth=Auth(self.private_project.creator), permissions=['read', 'write', 'admin'])
        self.public_project.add_contributor(self.contrib, auth=Auth(self.public_project.creator))
        self.private_project.add_contributor(self.contrib, auth=Auth(self.private_project.creator))
        self.public_project.save()
        self.private_project.save()
        self.anonymized_link_to_public_project = PrivateLinkFactory(anonymous=True)
        self.anonymized_link_to_private_project = PrivateLinkFactory(anonymous=True)
        self.anonymized_link_to_public_project.nodes.add(self.public_project)
        self.anonymized_link_to_public_project.save()
        self.anonymized_link_to_private_project.nodes.add(self.private_project)
        self.anonymized_link_to_private_project.save()
        self.flaskapp = Flask('Testing decorator')

        @self.flaskapp.route('/project/<pid>/')
        @must_be_contributor_or_public_but_not_anonymized
        def project_get(**kwargs):
            return 'success', 200
        self.app = WebtestApp(self.flaskapp)
Exemplo n.º 24
0
 def test_serialized_pointer_has_flag_indicating_its_a_pointer(self):
     project = ProjectFactory(creator=self.consolidated_auth.user)
     pointed_project = ProjectFactory(is_public=True)
     project.add_pointer(pointed_project, auth=self.consolidated_auth)
     serializer = rubeus.NodeFileCollector(node=project, auth=self.consolidated_auth)
     ret = serializer._serialize_node(project)
     child = ret['children'][1]  # first child is OSFStorage, second child is pointer
     assert_true(child['isPointer'])
Exemplo n.º 25
0
 def test_get_public_components_excludes_linked_contributor_projects(self):
     # self.user is a contributor to linked project
     pointee = ProjectFactory(is_public=True)
     pointee.add_contributor(self.user, auth=Auth(pointee.creator))
     self.public.add_node_link(pointee, auth=Auth(self.public.creator), save=True)
     res = get_public_components(uid=self.user._id)
     node_ids = [each['id'] for each in res]
     assert_not_in(pointee._id, node_ids)
    def test_wiki_deleted_shows_as_deleted(self):
        node = ProjectFactory(creator=self.user)
        node.delete_addon('wiki', auth=Auth(self.user))

        results = AddonSnapshot().get_events()
        wiki_res = [res for res in results if res['provider']['name'] == 'wiki'][0]

        assert_equal(wiki_res['nodes']['deleted'], 1)
Exemplo n.º 27
0
 def test_must_have_permission_true(self, mock_from_kwargs, mock_to_nodes):
     project = ProjectFactory()
     user = UserFactory()
     project.add_contributor(user, permissions=[permissions.READ, permissions.WRITE, permissions.ADMIN],
                             auth=Auth(project.creator))
     mock_from_kwargs.return_value = Auth(user=user)
     mock_to_nodes.return_value = (None, project)
     thriller(node=project)
Exemplo n.º 28
0
 def test_sees_osffiles_in_project_addon_settings(self):
     project = ProjectFactory(creator=self.user)
     project.add_contributor(
         self.user,
         permissions=['read', 'write', 'admin'],
         save=True)
     res = self.app.get('/{0}/addons/'.format(project._primary_key), auth=self.auth, auto_follow=True)
     assert_in('OSF Storage', res)
Exemplo n.º 29
0
def create_fake_conference_nodes(n, endpoint):
    nodes = []
    for i in range(n):
        node = ProjectFactory(is_public=True)
        node.add_tag(endpoint, Auth(node.creator))
        node.save()
        nodes.append(node)
    return nodes
Exemplo n.º 30
0
    def test_has_permission_read_scope_write_action_forbidden(self):
        component = ProjectFactory(creator=self.user, is_public=False, parent=self.node)
        cas_resp = cas.CasResponse(authenticated=True, status=None, user=self.user._id,
                                   attributes={'accessTokenScope': {'osf.nodes.data_read'}})

        assert_true(component.has_permission(self.user, 'write'))
        with assert_raises(HTTPError) as exc_info:
            views.check_access(component, Auth(user=self.user), 'upload', cas_resp)
        assert_equal(exc_info.exception.code, 403)
Exemplo n.º 31
0
 def project_private_user_two(self, user_two):
     return ProjectFactory(
         title='Private Project User Two',
         is_public=False,
         creator=user_two)
Exemplo n.º 32
0
 def read_node(self, creator, contrib):
     node = ProjectFactory(creator=creator)
     node.add_contributor(contrib, permissions=permissions.READ, save=True)
     return node
Exemplo n.º 33
0
class TestMustBeContributorOrPublicDecorator(AuthAppTestCase):
    def setUp(self):
        super(TestMustBeContributorOrPublicDecorator, self).setUp()
        self.contrib = AuthUserFactory()
        self.non_contrib = AuthUserFactory()
        self.public_project = ProjectFactory(is_public=True)
        self.private_project = ProjectFactory(is_public=False)
        self.public_project.add_contributor(self.contrib,
                                            auth=Auth(
                                                self.public_project.creator))
        self.private_project.add_contributor(self.contrib,
                                             auth=Auth(
                                                 self.private_project.creator))
        self.public_project.save()
        self.private_project.save()

    def test_must_be_contributor_when_user_is_contributor_and_public_project(
            self):
        result = view_that_needs_contributor_or_public(
            pid=self.public_project._primary_key, user=self.contrib)
        assert_equal(result, self.public_project)

    def test_must_be_contributor_when_user_is_not_contributor_and_public_project(
            self):
        result = view_that_needs_contributor_or_public(
            pid=self.public_project._primary_key, user=self.non_contrib)
        assert_equal(result, self.public_project)

    def test_must_be_contributor_when_user_is_contributor_and_private_project(
            self):
        result = view_that_needs_contributor_or_public(
            pid=self.private_project._primary_key, user=self.contrib)
        assert_equal(result, self.private_project)

    def test_must_be_contributor_when_user_is_not_contributor_and_private_project_raise_error(
            self):
        with assert_raises(HTTPError):
            view_that_needs_contributor_or_public(
                pid=self.private_project._primary_key, user=self.non_contrib)

    def test_must_be_contributor_no_user_and_public_project(self):
        res = view_that_needs_contributor_or_public(
            pid=self.public_project._primary_key,
            user=None,
        )
        assert_equal(res, self.public_project)

    def test_must_be_contributor_no_user_and_private_project(self):
        res = view_that_needs_contributor_or_public(
            pid=self.private_project._primary_key,
            user=None,
        )
        assert_is_redirect(res)
        # redirects to login url
        redirect_url = res.headers['Location']
        login_url = cas.get_login_url(service_url='http://localhost/')
        assert_equal(redirect_url, login_url)

    def test_must_be_contributor_parent_admin_and_public_project(self):
        user = UserFactory()
        node = NodeFactory(parent=self.public_project, creator=user)
        res = view_that_needs_contributor_or_public(
            pid=self.public_project._id,
            nid=node._id,
            user=self.public_project.creator,
        )
        assert_equal(res, node)

    def test_must_be_contributor_parent_admin_and_private_project(self):
        user = UserFactory()
        node = NodeFactory(parent=self.private_project, creator=user)
        res = view_that_needs_contributor_or_public(
            pid=self.private_project._id,
            nid=node._id,
            user=self.private_project.creator,
        )
        assert_equal(res, node)

    def test_must_be_contributor_parent_write_public_project(self):
        user = UserFactory()
        node = NodeFactory(parent=self.public_project, creator=user)
        contrib = UserFactory()
        self.public_project.add_contributor(contrib,
                                            auth=Auth(
                                                self.public_project.creator),
                                            permissions=['read', 'write'])
        self.public_project.save()
        with assert_raises(HTTPError) as exc_info:
            view_that_needs_contributor_or_public(
                pid=self.public_project._id,
                nid=node._id,
                user=contrib,
            )
        assert_equal(exc_info.exception.code, 403)

    def test_must_be_contributor_parent_write_private_project(self):
        user = UserFactory()
        node = NodeFactory(parent=self.private_project, creator=user)
        contrib = UserFactory()
        self.private_project.add_contributor(contrib,
                                             auth=Auth(
                                                 self.private_project.creator),
                                             permissions=['read', 'write'])
        self.private_project.save()
        with assert_raises(HTTPError) as exc_info:
            view_that_needs_contributor_or_public(
                pid=self.private_project._id,
                nid=node._id,
                user=contrib,
            )
        assert_equal(exc_info.exception.code, 403)
Exemplo n.º 34
0
 def setUp(self):
     self.admin = AuthUserFactory()
     self.provider = PreprintProviderFactory()
     self.project = ProjectFactory(creator=self.admin, is_public=True)
     self.url = '/{}preprints/?version=2.2&'.format(API_BASE)
     super(TestPreprintIsValidList, self).setUp()
Exemplo n.º 35
0
 def write_node(self, creator, contrib):
     node = ProjectFactory(creator=creator)
     node.add_contributor(contrib, permissions=permissions.WRITE, save=True)
     return node
Exemplo n.º 36
0
 def project_public_user_one(self, user_one):
     return ProjectFactory(
         title='Public Project User One',
         is_public=True,
         creator=user_one)
class TestGithubViews(OsfTestCase):
    def setUp(self):
        super(TestGithubViews, self).setUp()
        self.user = AuthUserFactory()
        self.consolidated_auth = Auth(user=self.user)

        self.project = ProjectFactory(creator=self.user)
        self.non_authenticator = UserFactory()
        self.project.add_contributor(
            contributor=self.non_authenticator,
            auth=self.consolidated_auth,
        )
        self.project.creator.add_addon('github')
        self.project.creator.external_accounts.add(GitHubAccountFactory())
        self.project.creator.save()
        self.project.save()
        self.project.add_addon('github', auth=self.consolidated_auth)

        self.github = create_mock_github(user='******', private=False)

        self.node_settings = self.project.get_addon('github')
        self.node_settings.user_settings = self.project.creator.get_addon(
            'github')
        # Set the node addon settings to correspond to the values of the mock repo
        self.node_settings.user = self.github.repo.return_value.owner.login
        self.node_settings.repo = self.github.repo.return_value.name
        self.node_settings.save()

    def _get_sha_for_branch(self, branch=None, mock_branches=None):
        github_mock = self.github
        if mock_branches is None:
            mock_branches = github_mock.branches
        if branch is None:  # Get default branch name
            branch = self.github.repo.return_value.default_branch
        for each in mock_branches.return_value:
            if each.name == branch:
                branch_sha = each.commit.sha
        return branch_sha

    # Tests for _get_refs
    @mock.patch('addons.github.api.GitHubClient.branches')
    @mock.patch('addons.github.api.GitHubClient.repo')
    def test_get_refs_defaults(self, mock_repo, mock_branches):
        github_mock = self.github
        mock_repo.return_value = github_mock.repo.return_value
        mock_branches.return_value = github_mock.branches.return_value
        branch, sha, branches = utils.get_refs(self.node_settings)
        assert_equal(branch, github_mock.repo.return_value.default_branch)
        assert_equal(sha, self._get_sha_for_branch(
            branch=None))  # Get refs for default branch
        assert_equal(branches, github_mock.branches.return_value)

    @mock.patch('addons.github.api.GitHubClient.branches')
    @mock.patch('addons.github.api.GitHubClient.repo')
    def test_get_refs_branch(self, mock_repo, mock_branches):
        github_mock = self.github
        mock_repo.return_value = github_mock.repo.return_value
        mock_branches.return_value = github_mock.branches.return_value
        branch, sha, branches = utils.get_refs(self.node_settings, 'master')
        assert_equal(branch, 'master')
        branch_sha = self._get_sha_for_branch('master')
        assert_equal(sha, branch_sha)
        assert_equal(branches, github_mock.branches.return_value)

    def test_before_fork(self):
        url = self.project.api_url + 'fork/before/'
        res = self.app.get(url, auth=self.user.auth).maybe_follow()
        assert_equal(len(res.json['prompts']), 1)

    def test_get_refs_sha_no_branch(self):
        with assert_raises(HTTPError):
            utils.get_refs(self.node_settings, sha='12345')

    def test_get_refs_registered_missing_branch(self):
        github_mock = self.github
        self.node_settings.registration_data = {
            'branches':
            [branch.as_json() for branch in github_mock.branches.return_value]
        }
        with mock.patch('osf.models.node.AbstractNode.is_registration',
                        new_callable=mock.PropertyMock) as mock_is_reg:
            mock_is_reg.return_value = True
            with assert_raises(HTTPError):
                utils.get_refs(self.node_settings, branch='nothere')

    # Tests for _check_permissions
    # make a user with no authorization; make sure check_permissions returns false
    def test_permissions_no_auth(self):
        github_mock = self.github
        # project is set to private right now
        connection = github_mock
        non_authenticated_user = UserFactory()
        non_authenticated_auth = Auth(user=non_authenticated_user)
        branch = 'master'
        assert_false(
            check_permissions(self.node_settings, non_authenticated_auth,
                              connection, branch))

    # make a repository that doesn't allow push access for this user;
    # make sure check_permissions returns false
    @mock.patch('addons.github.models.UserSettings.has_auth')
    @mock.patch('addons.github.api.GitHubClient.repo')
    def test_permissions_no_access(self, mock_repo, mock_has_auth):
        github_mock = self.github
        mock_has_auth.return_value = True
        connection = github_mock
        branch = 'master'
        mock_repository = mock.NonCallableMock()
        mock_repository.user = '******'
        mock_repository.repo = 'mock-repo'
        mock_repository.permissions = dict(push=False)
        mock_repo.return_value = mock_repository
        assert_false(
            check_permissions(self.node_settings,
                              self.consolidated_auth,
                              connection,
                              branch,
                              repo=mock_repository))

    # make a branch with a different commit than the commit being passed into check_permissions
    @mock.patch('addons.github.models.UserSettings.has_auth')
    def test_permissions_not_head(self, mock_has_auth):
        github_mock = self.github
        mock_has_auth.return_value = True
        connection = github_mock
        mock_branch = mock.NonCallableMock()
        mock_branch.commit.sha = '67890'
        sha = '12345'
        assert_false(
            check_permissions(self.node_settings,
                              self.consolidated_auth,
                              connection,
                              mock_branch,
                              sha=sha))

    # # make sure permissions are not granted for editing a registration
    @mock.patch('addons.github.models.UserSettings.has_auth')
    def test_permissions(self, mock_has_auth):
        github_mock = self.github
        mock_has_auth.return_value = True
        connection = github_mock
        with mock.patch('osf.models.node.AbstractNode.is_registration',
                        new_callable=mock.PropertyMock) as mock_is_reg:
            mock_is_reg.return_value = True
            assert_false(
                check_permissions(self.node_settings, self.consolidated_auth,
                                  connection, 'master'))

    def check_hook_urls(self, urls, node, path, sha):
        url = node.web_url_for('addon_view_or_download_file',
                               path=path,
                               provider='github')
        expected_urls = {
            'view': '{0}?ref={1}'.format(url, sha),
            'download': '{0}?action=download&ref={1}'.format(url, sha)
        }

        assert_equal(urls['view'], expected_urls['view'])
        assert_equal(urls['download'], expected_urls['download'])

    @mock.patch('addons.github.views.verify_hook_signature')
    def test_hook_callback_add_file_not_thro_osf(self, mock_verify):
        url = '/api/v1/project/{0}/github/hook/'.format(self.project._id)
        timestamp = str(timezone.now())
        self.app.post_json(
            url,
            {
                'test':
                True,
                'commits': [{
                    'id': 'b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                    'distinct': True,
                    'message': 'foo',
                    'timestamp': timestamp,
                    'url':
                    'https://github.com/tester/addontesting/commit/b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                    'author': {
                        'name': 'Illidan',
                        'email': '*****@*****.**'
                    },
                    'committer': {
                        'name': 'Testor',
                        'email': '*****@*****.**',
                        'username': '******'
                    },
                    'added': ['PRJWN3TV'],
                    'removed': [],
                    'modified': [],
                }]
            },
            content_type='application/json',
        ).maybe_follow()
        self.project.reload()
        assert_equal(self.project.logs.latest().action, 'github_file_added')
        urls = self.project.logs.latest().params['urls']
        self.check_hook_urls(
            urls,
            self.project,
            path='PRJWN3TV',
            sha='b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
        )

    @mock.patch('addons.github.views.verify_hook_signature')
    def test_hook_callback_modify_file_not_thro_osf(self, mock_verify):
        url = '/api/v1/project/{0}/github/hook/'.format(self.project._id)
        timestamp = str(timezone.now())
        self.app.post_json(url, {
            'test':
            True,
            'commits': [{
                'id': 'b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                'distinct': True,
                'message': ' foo',
                'timestamp': timestamp,
                'url':
                'https://github.com/tester/addontesting/commit/b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                'author': {
                    'name': 'Illidan',
                    'email': '*****@*****.**'
                },
                'committer': {
                    'name': 'Testor',
                    'email': '*****@*****.**',
                    'username': '******'
                },
                'added': [],
                'removed': [],
                'modified': ['PRJWN3TV']
            }]
        },
                           content_type='application/json').maybe_follow()
        self.project.reload()
        assert_equal(self.project.logs.latest().action, 'github_file_updated')
        urls = self.project.logs.latest().params['urls']
        self.check_hook_urls(
            urls,
            self.project,
            path='PRJWN3TV',
            sha='b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
        )

    @mock.patch('addons.github.views.verify_hook_signature')
    def test_hook_callback_remove_file_not_thro_osf(self, mock_verify):
        url = '/api/v1/project/{0}/github/hook/'.format(self.project._id)
        timestamp = str(timezone.now())
        self.app.post_json(url, {
            'test':
            True,
            'commits': [{
                'id': 'b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                'distinct': True,
                'message': 'foo',
                'timestamp': timestamp,
                'url':
                'https://github.com/tester/addontesting/commit/b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                'author': {
                    'name': 'Illidan',
                    'email': '*****@*****.**'
                },
                'committer': {
                    'name': 'Testor',
                    'email': '*****@*****.**',
                    'username': '******'
                },
                'added': [],
                'removed': ['PRJWN3TV'],
                'modified': []
            }]
        },
                           content_type='application/json').maybe_follow()
        self.project.reload()
        assert_equal(self.project.logs.latest().action, 'github_file_removed')
        urls = self.project.logs.latest().params['urls']
        assert_equal(urls, {})

    @mock.patch('addons.github.views.verify_hook_signature')
    def test_hook_callback_add_file_thro_osf(self, mock_verify):
        url = '/api/v1/project/{0}/github/hook/'.format(self.project._id)
        self.app.post_json(url, {
            'test':
            True,
            'commits': [{
                'id': 'b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                'distinct': True,
                'message': 'Added via the Open Science Framework',
                'timestamp': '2014-01-08T14:15:51-08:00',
                'url':
                'https://github.com/tester/addontesting/commit/b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                'author': {
                    'name': 'Illidan',
                    'email': '*****@*****.**'
                },
                'committer': {
                    'name': 'Testor',
                    'email': '*****@*****.**',
                    'username': '******'
                },
                'added': ['PRJWN3TV'],
                'removed': [],
                'modified': []
            }]
        },
                           content_type='application/json').maybe_follow()
        self.project.reload()
        assert_not_equal(self.project.logs.latest().action,
                         'github_file_added')

    @mock.patch('addons.github.views.verify_hook_signature')
    def test_hook_callback_modify_file_thro_osf(self, mock_verify):
        url = '/api/v1/project/{0}/github/hook/'.format(self.project._id)
        self.app.post_json(url, {
            'test':
            True,
            'commits': [{
                'id': 'b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                'distinct': True,
                'message': 'Updated via the Open Science Framework',
                'timestamp': '2014-01-08T14:15:51-08:00',
                'url':
                'https://github.com/tester/addontesting/commit/b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                'author': {
                    'name': 'Illidan',
                    'email': '*****@*****.**'
                },
                'committer': {
                    'name': 'Testor',
                    'email': '*****@*****.**',
                    'username': '******'
                },
                'added': [],
                'removed': [],
                'modified': ['PRJWN3TV']
            }]
        },
                           content_type='application/json').maybe_follow()
        self.project.reload()
        assert_not_equal(self.project.logs.latest().action,
                         'github_file_updated')

    @mock.patch('addons.github.views.verify_hook_signature')
    def test_hook_callback_remove_file_thro_osf(self, mock_verify):
        url = '/api/v1/project/{0}/github/hook/'.format(self.project._id)
        self.app.post_json(url, {
            'test':
            True,
            'commits': [{
                'id': 'b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                'distinct': True,
                'message': 'Deleted via the Open Science Framework',
                'timestamp': '2014-01-08T14:15:51-08:00',
                'url':
                'https://github.com/tester/addontesting/commit/b08dbb5b6fcd74a592e5281c9d28e2020a1db4ce',
                'author': {
                    'name': 'Illidan',
                    'email': '*****@*****.**'
                },
                'committer': {
                    'name': 'Testor',
                    'email': '*****@*****.**',
                    'username': '******'
                },
                'added': [],
                'removed': ['PRJWN3TV'],
                'modified': []
            }]
        },
                           content_type='application/json').maybe_follow()
        self.project.reload()
        assert_not_equal(self.project.logs.latest().action,
                         'github_file_removed')
Exemplo n.º 38
0
class TestAUserProfile(OsfTestCase):
    def setUp(self):
        OsfTestCase.setUp(self)

        self.user = AuthUserFactory()
        self.me = AuthUserFactory()
        self.project = ProjectFactory(creator=self.me,
                                      is_public=True,
                                      title=fake.bs())
        self.component = NodeFactory(creator=self.me,
                                     parent=self.project,
                                     is_public=True,
                                     title=fake.bs())

    # regression test for https://github.com/CenterForOpenScience/osf.io/issues/2623
    def test_has_public_projects_and_components(self):
        # I go to my own profile
        url = web_url_for('profile_view_id', uid=self.me._primary_key)
        # I see the title of both my project and component
        res = self.app.get(url, auth=self.me.auth)
        assert_in_html(self.component.title, res)
        assert_in_html(self.project.title, res)

        # Another user can also see my public project and component
        url = web_url_for('profile_view_id', uid=self.me._primary_key)
        # I see the title of both my project and component
        res = self.app.get(url, auth=self.user.auth)
        assert_in_html(self.component.title, res)
        assert_in_html(self.project.title, res)

    def test_shows_projects_with_many_contributors(self):
        # My project has many contributors
        for _ in range(5):
            user = UserFactory()
            self.project.add_contributor(user,
                                         auth=Auth(self.project.creator),
                                         save=True)

        # I go to my own profile
        url = web_url_for('profile_view_id', uid=self.me._primary_key)
        res = self.app.get(url, auth=self.me.auth)
        # I see '3 more' as a link
        assert_in('3 more', res)

        res = res.click('3 more')
        assert_equal(res.request.path, self.project.url)

    def test_has_no_public_projects_or_components_on_own_profile(self):
        # User goes to their profile
        url = web_url_for('profile_view_id', uid=self.user._id)
        res = self.app.get(url, auth=self.user.auth)

        # user has no public components/projects
        assert_in('You have no public projects', res)
        assert_in('You have no public components', res)

    def test_user_no_public_projects_or_components(self):
        # I go to other user's profile
        url = web_url_for('profile_view_id', uid=self.user._id)
        # User has no public components/projects
        res = self.app.get(url, auth=self.me.auth)
        assert_in('This user has no public projects', res)
        assert_in('This user has no public components', res)

    # regression test
    def test_does_not_show_registrations(self):
        project = ProjectFactory(creator=self.user)
        component = NodeFactory(parent=project,
                                creator=self.user,
                                is_public=False)
        # User has a registration with public components
        reg = RegistrationFactory(project=component.parent_node,
                                  creator=self.user,
                                  is_public=True)
        for each in reg.nodes:
            each.is_public = True
            each.save()
        # I go to other user's profile
        url = web_url_for('profile_view_id', uid=self.user._id)
        # Registration does not appear on profile
        res = self.app.get(url, auth=self.me.auth)
        assert_in('This user has no public components', res)
        assert_not_in(reg.title, res)
        assert_not_in(reg.nodes[0].title, res)
Exemplo n.º 39
0
class TestSpamListView(AdminTestCase):
    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)

    def test_get_spam(self):
        res = list(self.view.get_queryset())
        nt.assert_equal(len(res), 6)
        response_list = [r._id for r in res]
        should_be = [
            self.comment_6._id, self.comment_5._id, self.comment_4._id,
            self.comment_3._id, self.comment_2._id, self.comment_1._id
        ]
        nt.assert_list_equal(should_be, response_list)

    def test_get_context_data(self):
        self.view.object_list = self.view.get_queryset()
        res = self.view.get_context_data()
        nt.assert_is_instance(res['spam'], list)
        nt.assert_is_instance(res['spam'][0], dict)
        nt.assert_equal(res['status'], '1')
        nt.assert_equal(res['page_number'], 1)
Exemplo n.º 40
0
 def test_sees_logs_on_a_project(self):
     project = ProjectFactory(is_public=True)
     # User goes to the project's page
     res = self.app.get(project.url, auth=self.auth).maybe_follow()
     # Can see log event
     assert_in('created', res)
Exemplo n.º 41
0
class TestPreprintBannerView(OsfTestCase):
    def setUp(self):
        super(TestPreprintBannerView, self).setUp()

        self.admin = AuthUserFactory()
        self.provider_one = PreprintProviderFactory()
        self.provider_two = PreprintProviderFactory()
        self.project_one = ProjectFactory(creator=self.admin, is_public=True)
        self.project_two = ProjectFactory(creator=self.admin, is_public=True)
        self.project_three = ProjectFactory(creator=self.admin, is_public=True)

        self.subject_one = SubjectFactory()
        self.subject_two = SubjectFactory()

        self.file_one = test_utils.create_test_file(self.project_one,
                                                    self.admin, 'mgla.pdf')
        self.file_two = test_utils.create_test_file(self.project_two,
                                                    self.admin, 'saor.pdf')

        self.published_preprint = PreprintFactory(
            creator=self.admin,
            filename='mgla.pdf',
            provider=self.provider_one,
            subjects=[[self.subject_one._id]],
            project=self.project_one,
            is_published=True)
        self.unpublished_preprint = PreprintFactory(
            creator=self.admin,
            filename='saor.pdf',
            provider=self.provider_two,
            subjects=[[self.subject_two._id]],
            project=self.project_two,
            is_published=False)

    def test_public_project_published_preprint(self):
        url = self.project_one.web_url_for('view_project')
        res = self.app.get(url, auth=self.admin.auth)
        assert_not_in(
            'has a preprint, but has been made Private. Make your preprint discoverable by making this',
            res.body)

    def test_private_project_published_preprint(self):
        self.project_one.is_public = False
        self.project_one.save()
        url = self.project_one.web_url_for('view_project')
        res = self.app.get(url, auth=self.admin.auth)
        assert_in(
            'has a preprint, but has been made Private. Make your preprint discoverable by making this',
            res.body)

    def test_public_project_unpublished_preprint(self):
        url = self.project_two.web_url_for('view_project')
        res = self.app.get(url, auth=self.admin.auth)
        assert_not_in(
            'has a preprint, but has been made Private. Make your preprint discoverable by making this',
            res.body)

    def test_private_project_unpublished_preprint(self):
        # Do not show banner on unpublished preprints
        self.project_two.is_public = False
        self.project_two.save()
        url = self.project_two.web_url_for('view_project')
        res = self.app.get(url, auth=self.admin.auth)
        assert_not_in(
            'has a preprint, but has been made Private. Make your preprint discoverable by making this',
            res.body)

    def test_public_project_no_preprint(self):
        url = self.project_three.web_url_for('view_project')
        res = self.app.get(url, auth=self.admin.auth)
        assert_not_in(
            'has a preprint, but has been made Private. Make your preprint discoverable by making this',
            res.body)

    def test_private_project_no_preprint(self):
        self.project_three.is_public = False
        self.project_three.save()
        url = self.project_three.web_url_for('view_project')
        res = self.app.get(url, auth=self.admin.auth)
        assert_not_in(
            'has a preprint, but has been made Private. Make your preprint discoverable by making this',
            res.body)
Exemplo n.º 42
0
class TestComponents(OsfTestCase):
    def setUp(self):
        super(TestComponents, self).setUp()
        self.user = AuthUserFactory()
        self.consolidate_auth = Auth(user=self.user)
        self.project = ProjectFactory(creator=self.user)
        self.project.add_contributor(contributor=self.user,
                                     auth=self.consolidate_auth)
        # A non-project componenet
        self.component = NodeFactory(
            category='hypothesis',
            creator=self.user,
            parent=self.project,
        )
        self.component.save()
        self.component.set_privacy('public', self.consolidate_auth)
        self.component.set_privacy('private', self.consolidate_auth)
        self.project.save()
        self.project_url = self.project.web_url_for('view_project')

    def test_sees_parent(self):
        res = self.app.get(self.component.url,
                           auth=self.user.auth).maybe_follow()
        parent_title = res.html.find_all('h2', class_='node-parent-title')
        assert_equal(len(parent_title), 1)
        assert_in(self.project.title,
                  parent_title[0].text)  # Bs4 will handle unescaping HTML here

    def test_delete_project(self):
        res = self.app.get(self.component.url + 'settings/',
                           auth=self.user.auth).maybe_follow()
        assert_in('Delete {0}'.format(self.component.project_or_component),
                  res)

    def test_cant_delete_project_if_not_admin(self):
        non_admin = AuthUserFactory()
        self.component.add_contributor(
            non_admin,
            permissions=['read', 'write'],
            auth=self.consolidate_auth,
            save=True,
        )
        res = self.app.get(self.component.url + 'settings/',
                           auth=non_admin.auth).maybe_follow()
        assert_not_in('Delete {0}'.format(self.component.project_or_component),
                      res)

    def test_can_configure_comments_if_admin(self):
        res = self.app.get(
            self.component.url + 'settings/',
            auth=self.user.auth,
        ).maybe_follow()
        assert_in('Commenting', res)

    def test_cant_configure_comments_if_not_admin(self):
        non_admin = AuthUserFactory()
        self.component.add_contributor(
            non_admin,
            permissions=['read', 'write'],
            auth=self.consolidate_auth,
            save=True,
        )
        res = self.app.get(self.component.url + 'settings/',
                           auth=non_admin.auth).maybe_follow()
        assert_not_in('Commenting', res)

    def test_components_should_have_component_list(self):
        res = self.app.get(self.component.url, auth=self.user.auth)
        assert_in('Components', res)
 def node(self, user):
     return ProjectFactory(is_public=True, creator=user)
Exemplo n.º 44
0
 def abandoned_preprint_node(self, user):
     return ProjectFactory(creator=user)
Exemplo n.º 45
0
 def project_public_user_two(self, user_two):
     return ProjectFactory(
         title='Public Project User Two',
         is_public=True,
         creator=user_two)
Exemplo n.º 46
0
 def setUp(self):
     super(CitationsNodeTestCase, self).setUp()
     self.node = ProjectFactory()
Exemplo n.º 47
0
 def project_private_user_one(self, user_one):
     return ProjectFactory(
         title='Private Project User One',
         is_public=False,
         creator=user_one)
Exemplo n.º 48
0
class CitationsNodeTestCase(OsfTestCase):
    def setUp(self):
        super(CitationsNodeTestCase, self).setUp()
        self.node = ProjectFactory()

    def tearDown(self):
        super(CitationsNodeTestCase, self).tearDown()
        OSFUser.objects.all().delete()

    def test_csl_single_author(self):
        # Nodes with one contributor generate valid CSL-data
        assert_equal(
            self.node.csl,
            {
                'publisher':
                'OSF',
                'author': [{
                    'given': self.node.creator.given_name,
                    'family': self.node.creator.family_name,
                }],
                'URL':
                self.node.display_absolute_url,
                'issued':
                datetime_to_csl(self.node.logs.latest().date),
                'title':
                self.node.title,
                'type':
                'webpage',
                'id':
                self.node._id,
            },
        )

    def test_csl_multiple_authors(self):
        # Nodes with multiple contributors generate valid CSL-data
        user = UserFactory()
        self.node.add_contributor(user)
        self.node.save()

        assert_equal(
            self.node.csl,
            {
                'publisher':
                'OSF',
                'author': [{
                    'given': self.node.creator.given_name,
                    'family': self.node.creator.family_name,
                }, {
                    'given': user.given_name,
                    'family': user.family_name,
                }],
                'URL':
                self.node.display_absolute_url,
                'issued':
                datetime_to_csl(self.node.logs.latest().date),
                'title':
                self.node.title,
                'type':
                'webpage',
                'id':
                self.node._id,
            },
        )

    def test_non_visible_contributors_arent_included_in_csl(self):
        node = ProjectFactory()
        visible = UserFactory()
        node.add_contributor(visible, auth=Auth(node.creator))
        invisible = UserFactory()
        node.add_contributor(invisible, auth=Auth(node.creator), visible=False)
        node.save()
        assert_equal(len(node.csl['author']), 2)
        expected_authors = [
            contrib.csl_name(node._id) for contrib in [node.creator, visible]
        ]

        assert_equal(node.csl['author'], expected_authors)
class TestGithubSettings(OsfTestCase):
    def setUp(self):

        super(TestGithubSettings, self).setUp()
        self.github = create_mock_github(user='******', private=False)
        self.project = ProjectFactory()
        self.auth = self.project.creator.auth
        self.consolidated_auth = Auth(user=self.project.creator)

        self.project.add_addon('github', auth=self.consolidated_auth)
        self.project.creator.add_addon('github')
        self.node_settings = self.project.get_addon('github')
        self.user_settings = self.project.creator.get_addon('github')
        self.node_settings.user_settings = self.user_settings
        self.node_settings.user = '******'
        self.node_settings.repo = 'Sheer-Heart-Attack'
        self.node_settings.save()

    @mock.patch('addons.github.models.NodeSettings.add_hook')
    @mock.patch('addons.github.api.GitHubClient.repo')
    def test_link_repo(self, mock_repo, mock_add_hook):
        github_mock = self.github
        mock_repo.return_value = github_mock.repo.return_value

        url = self.project.api_url + 'github/settings/'
        self.app.post_json(url, {
            'github_user': '******',
            'github_repo': 'night at the opera',
        },
                           auth=self.auth).maybe_follow()

        self.project.reload()
        self.node_settings.reload()

        assert_equal(self.node_settings.user, 'queen')
        assert_equal(self.node_settings.repo, 'night at the opera')
        assert_equal(self.project.logs.latest().action, 'github_repo_linked')
        mock_add_hook.assert_called_once_with(save=False)

    @mock.patch('addons.github.models.NodeSettings.add_hook')
    @mock.patch('addons.github.api.GitHubClient.repo')
    def test_link_repo_no_change(self, mock_repo, mock_add_hook):
        github_mock = self.github
        mock_repo.return_value = github_mock.repo.return_value

        log_count = self.project.logs.count()

        url = self.project.api_url + 'github/settings/'
        self.app.post_json(url, {
            'github_user': '******',
            'github_repo': 'Sheer-Heart-Attack',
        },
                           auth=self.auth).maybe_follow()

        self.project.reload()
        self.node_settings.reload()

        assert_equal(self.project.logs.count(), log_count)
        assert_false(mock_add_hook.called)

    @mock.patch('addons.github.api.GitHubClient.repo')
    def test_link_repo_non_existent(self, mock_repo):

        mock_repo.return_value = None

        url = self.project.api_url + 'github/settings/'
        res = self.app.post_json(url, {
            'github_user': '******',
            'github_repo': 'night at the opera',
        },
                                 auth=self.auth,
                                 expect_errors=True).maybe_follow()

        assert_equal(res.status_code, 400)

    @mock.patch('addons.github.api.GitHubClient.branches')
    def test_link_repo_registration(self, mock_branches):

        mock_branches.return_value = [
            Branch.from_json(
                dumps({
                    'name': 'master',
                    'commit': {
                        'sha':
                        '6dcb09b5b57875f334f61aebed695e2e4193db5e',
                        'url':
                        'https://api.github.com/repos/octocat/Hello-World/commits/c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc',
                    }
                })),
            Branch.from_json(
                dumps({
                    'name': 'develop',
                    'commit': {
                        'sha':
                        '6dcb09b5b57875asdasedawedawedwedaewdwdass',
                        'url':
                        'https://api.github.com/repos/octocat/Hello-World/commits/cdcb09b5b57875asdasedawedawedwedaewdwdass',
                    }
                }))
        ]

        registration = self.project.register_node(
            schema=get_default_metaschema(),
            auth=self.consolidated_auth,
            draft_registration=DraftRegistrationFactory(
                branched_from=self.project))

        url = registration.api_url + 'github/settings/'
        res = self.app.post_json(url, {
            'github_user': '******',
            'github_repo': 'night at the opera',
        },
                                 auth=self.auth,
                                 expect_errors=True).maybe_follow()

        assert_equal(res.status_code, 400)

    @mock.patch('addons.github.models.NodeSettings.delete_hook')
    def test_deauthorize(self, mock_delete_hook):

        url = self.project.api_url + 'github/user_auth/'

        self.app.delete(url, auth=self.auth).maybe_follow()

        self.project.reload()
        self.node_settings.reload()
        assert_equal(self.node_settings.user, None)
        assert_equal(self.node_settings.repo, None)
        assert_equal(self.node_settings.user_settings, None)

        assert_equal(self.project.logs.latest().action,
                     'github_node_deauthorized')
Exemplo n.º 50
0
 def setUp(self):
     super(TestMustBeAddonAuthorizerDecorator, self).setUp()
     self.project = ProjectFactory()
     self.decorated = must_be_addon_authorizer('github')(needs_addon_view)
Exemplo n.º 51
0
class TestPreprintCreate(ApiTestCase):
    def setUp(self):
        super(TestPreprintCreate, self).setUp()

        self.user = AuthUserFactory()
        self.other_user = AuthUserFactory()
        self.private_project = ProjectFactory(creator=self.user)
        self.public_project = ProjectFactory(creator=self.user, is_public=True)
        self.public_project.add_contributor(self.other_user, permissions=permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS, save=True)
        self.subject = SubjectFactory()
        self.provider = PreprintProviderFactory()

        self.user_two = AuthUserFactory()

        self.file_one_public_project = test_utils.create_test_file(self.public_project, self.user, 'millionsofdollars.pdf')
        self.file_one_private_project = test_utils.create_test_file(self.private_project, self.user, 'woowoowoo.pdf')

        self.url = '/{}preprints/'.format(API_BASE)

    def test_create_preprint_from_public_project(self):
        public_project_payload = build_preprint_create_payload(self.public_project._id, self.provider._id, self.file_one_public_project._id)
        res = self.app.post_json_api(self.url, public_project_payload, auth=self.user.auth)

        assert_equal(res.status_code, 201)

    def test_create_preprint_from_private_project(self):
        private_project_payload = build_preprint_create_payload(self.private_project._id, self.provider._id, self.file_one_private_project._id, attrs={
                'subjects': [[SubjectFactory()._id]],
                'is_published': True
            })
        res = self.app.post_json_api(self.url, private_project_payload, auth=self.user.auth)

        self.private_project.reload()
        assert_equal(res.status_code, 201)
        assert_true(self.private_project.is_public)

    def test_non_authorized_user(self):
        public_project_payload = build_preprint_create_payload(self.public_project._id, self.provider._id, self.file_one_public_project._id)
        res = self.app.post_json_api(self.url, public_project_payload, auth=self.user_two.auth, expect_errors=True)

        assert_equal(res.status_code, 403)

    def test_read_write_user_not_admin(self):
        assert_in(self.other_user, self.public_project.contributors)
        public_project_payload = build_preprint_create_payload(self.public_project._id, self.provider._id, self.file_one_public_project._id)
        res = self.app.post_json_api(self.url, public_project_payload, auth=self.other_user.auth, expect_errors=True)

        assert_equal(res.status_code, 403)

    def test_file_is_not_in_node(self):
        wrong_project_payload = build_preprint_create_payload(self.public_project._id, self.provider._id, self.file_one_private_project._id)
        res = self.app.post_json_api(self.url, wrong_project_payload, auth=self.user.auth, expect_errors=True)

        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'], 'This file is not a valid primary file for this preprint.')

    def test_already_a_preprint_with_conflicting_provider(self):
        preprint = PreprintFactory(creator=self.user)
        file_one_preprint = test_utils.create_test_file(preprint.node, self.user, 'openupthatwindow.pdf')

        already_preprint_payload = build_preprint_create_payload(preprint.node._id, preprint.provider._id, file_one_preprint._id)
        res = self.app.post_json_api(self.url, already_preprint_payload, auth=self.user.auth, expect_errors=True)

        assert_equal(res.status_code, 409)
        assert_in('Only one preprint per provider can be submitted for a node.', res.json['errors'][0]['detail'])

    def test_read_write_user_already_a_preprint_with_conflicting_provider(self):
        assert_in(self.other_user, self.public_project.contributors)

        preprint = PreprintFactory(creator=self.user)
        preprint.node.add_contributor(self.other_user, permissions=permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS, save=True)
        file_one_preprint = test_utils.create_test_file(preprint.node, self.user, 'openupthatwindow.pdf')

        already_preprint_payload = build_preprint_create_payload(preprint.node._id, self.provider._id, file_one_preprint._id)
        res = self.app.post_json_api(self.url, already_preprint_payload, auth=self.other_user.auth, expect_errors=True)

        assert_equal(res.status_code, 403)

    def test_no_primary_file_passed(self):
        no_file_payload = build_preprint_create_payload(self.public_project._id, self.provider._id)

        res = self.app.post_json_api(self.url, no_file_payload, auth=self.user.auth, expect_errors=True)

        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'], 'You must specify a valid primary_file to create a preprint.')

    def test_invalid_primary_file(self):
        invalid_file_payload = build_preprint_create_payload(self.public_project._id, self.provider._id, 'totallynotanid')
        res = self.app.post_json_api(self.url, invalid_file_payload, auth=self.user.auth, expect_errors=True)

        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'], 'You must specify a valid primary_file to create a preprint.')

    def test_no_provider_given(self):
        no_providers_payload = build_preprint_create_payload(self.public_project._id, self.provider._id, self.file_one_public_project._id)
        del no_providers_payload['data']['relationships']['provider']
        res = self.app.post_json_api(self.url, no_providers_payload, auth=self.user.auth, expect_errors=True)

        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'], 'You must specify a valid provider to create a preprint.')

    def test_invalid_provider_given(self):
        wrong_provider_payload = build_preprint_create_payload(self.public_project._id, 'jobbers', self.file_one_public_project._id)

        res = self.app.post_json_api(self.url, wrong_provider_payload, auth=self.user.auth, expect_errors=True)

        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'], 'You must specify a valid provider to create a preprint.')

    def test_request_id_does_not_match_request_url_id(self):
        public_project_payload = build_preprint_create_payload(self.private_project._id, self.provider._id, self.file_one_public_project._id)
        res = self.app.post_json_api(self.url, public_project_payload, auth=self.user.auth, expect_errors=True)

        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'], 'This file is not a valid primary file for this preprint.')

    def test_file_not_osfstorage(self):
        github_file = self.file_one_public_project
        github_file.recast(GithubFile._typedmodels_type)
        github_file.save()
        public_project_payload = build_preprint_create_payload(self.public_project._id, self.provider._id, github_file._id)
        res = self.app.post_json_api(self.url, public_project_payload, auth=self.user.auth, expect_errors=True)

        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'], 'This file is not a valid primary file for this preprint.')

    def test_preprint_contributor_signal_not_sent_on_creation(self):
        with capture_signals() as mock_signals:
            public_project_payload = build_preprint_create_payload(self.public_project._id, self.provider._id,
                                                                   self.file_one_public_project._id)
            res = self.app.post_json_api(self.url, public_project_payload, auth=self.user.auth)

            assert_equal(res.status_code, 201)
            assert_not_in(project_signals.contributor_added, mock_signals.signals_sent())

    def test_create_preprint_with_deleted_node_should_fail(self):
        self.public_project.is_deleted = True
        self.public_project.save()
        public_project_payload = build_preprint_create_payload(self.public_project._id, self.provider._id, self.file_one_public_project._id)
        res = self.app.post_json_api(self.url, public_project_payload, auth=self.user.auth, expect_errors=True)
        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'], 'Cannot create a preprint from a deleted node.')

    def test_create_preprint_adds_log_if_published(self):
        public_project_payload = build_preprint_create_payload(
            self.public_project._id,
            self.provider._id,
            self.file_one_public_project._id,
            {
                'is_published': True,
                'subjects': [[SubjectFactory()._id]],
            }
        )
        res = self.app.post_json_api(self.url, public_project_payload, auth=self.user.auth)
        assert_equal(res.status_code, 201)
        preprint_id = res.json['data']['id']
        preprint = PreprintService.load(preprint_id)
        log = preprint.node.logs.latest()
        assert_equal(log.action, 'preprint_initiated')
        assert_equal(log.params.get('preprint'), preprint_id)

    @mock.patch('website.preprints.tasks.on_preprint_updated.s')
    def test_create_preprint_from_project_published_hits_update(self, mock_on_preprint_updated):
        private_project_payload = build_preprint_create_payload(self.private_project._id, self.provider._id, self.file_one_private_project._id, attrs={
                'subjects': [[SubjectFactory()._id]],
                'is_published': True
            })
        res = self.app.post_json_api(self.url, private_project_payload, auth=self.user.auth)
        assert mock_on_preprint_updated.called

    @mock.patch('website.preprints.tasks.on_preprint_updated.s')
    def test_create_preprint_from_project_unpublished_does_not_hit_update(self, mock_on_preprint_updated):
        private_project_payload = build_preprint_create_payload(self.private_project._id, self.provider._id, self.file_one_private_project._id, attrs={
                'subjects': [[SubjectFactory()._id]],
                'is_published': False
            })
        res = self.app.post_json_api(self.url, private_project_payload, auth=self.user.auth)
        assert not mock_on_preprint_updated.called
Exemplo n.º 52
0
 def setUp(self):
     super(TestMustHaveAddonDecorator, self).setUp()
     self.project = ProjectFactory()
Exemplo n.º 53
0
 def admin_node(self, creator, contrib):
     node = ProjectFactory(creator=creator)
     node.add_contributor(contrib, permissions=permissions.ADMIN, save=True)
     return node
Exemplo n.º 54
0
class TestMustBeContributorOrPublicButNotAnonymizedDecorator(AuthAppTestCase):
    def setUp(self):
        super(TestMustBeContributorOrPublicButNotAnonymizedDecorator,
              self).setUp()
        self.contrib = AuthUserFactory()
        self.non_contrib = AuthUserFactory()
        admin = UserFactory()
        self.public_project = ProjectFactory(is_public=True)
        self.public_project.add_contributor(
            admin,
            auth=Auth(self.public_project.creator),
            permissions=['read', 'write', 'admin'])
        self.private_project = ProjectFactory(is_public=False)
        self.private_project.add_contributor(
            admin,
            auth=Auth(self.private_project.creator),
            permissions=['read', 'write', 'admin'])
        self.public_project.add_contributor(self.contrib,
                                            auth=Auth(
                                                self.public_project.creator))
        self.private_project.add_contributor(self.contrib,
                                             auth=Auth(
                                                 self.private_project.creator))
        self.public_project.save()
        self.private_project.save()
        self.anonymized_link_to_public_project = PrivateLinkFactory(
            anonymous=True)
        self.anonymized_link_to_private_project = PrivateLinkFactory(
            anonymous=True)
        self.anonymized_link_to_public_project.nodes.add(self.public_project)
        self.anonymized_link_to_public_project.save()
        self.anonymized_link_to_private_project.nodes.add(self.private_project)
        self.anonymized_link_to_private_project.save()
        self.flaskapp = Flask('Testing decorator')

        @self.flaskapp.route('/project/<pid>/')
        @must_be_contributor_or_public_but_not_anonymized
        def project_get(**kwargs):
            return 'success', 200

        self.app = WebtestApp(self.flaskapp)

    def test_must_be_contributor_when_user_is_contributor_and_public_project(
            self):
        result = view_that_needs_contributor_or_public_but_not_anonymized(
            pid=self.public_project._primary_key, user=self.contrib)
        assert_equal(result, self.public_project)

    def test_must_be_contributor_when_user_is_not_contributor_and_public_project(
            self):
        result = view_that_needs_contributor_or_public_but_not_anonymized(
            pid=self.public_project._primary_key, user=self.non_contrib)
        assert_equal(result, self.public_project)

    def test_must_be_contributor_when_user_is_contributor_and_private_project(
            self):
        result = view_that_needs_contributor_or_public_but_not_anonymized(
            pid=self.private_project._primary_key, user=self.contrib)
        assert_equal(result, self.private_project)

    def test_must_be_contributor_when_user_is_not_contributor_and_private_project_raise_error(
            self):
        with assert_raises(HTTPError):
            view_that_needs_contributor_or_public_but_not_anonymized(
                pid=self.private_project._primary_key, user=self.non_contrib)

    def test_must_be_contributor_no_user_and_public_project(self):
        res = view_that_needs_contributor_or_public_but_not_anonymized(
            pid=self.public_project._primary_key,
            user=None,
        )
        assert_equal(res, self.public_project)

    def test_must_be_contributor_no_user_and_private_project(self):
        res = view_that_needs_contributor_or_public_but_not_anonymized(
            pid=self.private_project._primary_key,
            user=None,
        )
        assert_is_redirect(res)
        # redirects to login url
        redirect_url = res.headers['Location']
        login_url = cas.get_login_url(service_url='http://localhost/')
        assert_equal(redirect_url, login_url)

    def test_must_be_contributor_parent_admin_and_public_project(self):
        user = UserFactory()
        node = NodeFactory(parent=self.public_project, creator=user)
        res = view_that_needs_contributor_or_public_but_not_anonymized(
            pid=self.public_project._id,
            nid=node._id,
            user=self.public_project.creator,
        )
        assert_equal(res, node)

    def test_must_be_contributor_parent_admin_and_private_project(self):
        user = UserFactory()
        node = NodeFactory(parent=self.private_project, creator=user)
        res = view_that_needs_contributor_or_public_but_not_anonymized(
            pid=self.private_project._id,
            nid=node._id,
            user=self.private_project.creator,
        )
        assert_equal(res, node)

    def test_must_be_contributor_parent_write_public_project(self):
        user = UserFactory()
        node = NodeFactory(parent=self.public_project, creator=user)
        self.public_project.set_permissions(self.public_project.creator,
                                            ['read', 'write'])
        self.public_project.save()
        with assert_raises(HTTPError) as exc_info:
            view_that_needs_contributor_or_public_but_not_anonymized(
                pid=self.public_project._id,
                nid=node._id,
                user=self.public_project.creator,
            )
        assert_equal(exc_info.exception.code, 403)

    def test_must_be_contributor_parent_write_private_project(self):
        user = UserFactory()
        node = NodeFactory(parent=self.private_project, creator=user)
        self.private_project.set_permissions(self.private_project.creator,
                                             ['read', 'write'])
        self.private_project.save()
        with assert_raises(HTTPError) as exc_info:
            view_that_needs_contributor_or_public_but_not_anonymized(
                pid=self.private_project._id,
                nid=node._id,
                user=self.private_project.creator,
            )
        assert_equal(exc_info.exception.code, 403)

    @mock.patch('website.project.decorators.Auth.from_kwargs')
    def test_decorator_does_allow_anonymous_link_public_project(
            self, mock_from_kwargs):
        mock_from_kwargs.return_value = Auth(user=None)
        res = self.app.get(
            '/project/{0}'.format(self.public_project._primary_key),
            {'view_only': self.anonymized_link_to_public_project.key})
        res = res.follow()
        assert_equal(res.status_code, 200)

    @mock.patch('website.project.decorators.Auth.from_kwargs')
    def test_decorator_does_not_allow_anonymous_link_private_project(
            self, mock_from_kwargs):
        mock_from_kwargs.return_value = Auth(user=None)
        res = self.app.get(
            '/project/{0}'.format(self.private_project._primary_key),
            {'view_only': self.anonymized_link_to_private_project.key})
        res = res.follow(expect_errors=True)
        assert_equal(res.status_code, 500)
Exemplo n.º 55
0
 def no_perm_node(self, creator):
     return ProjectFactory(creator=creator)
Exemplo n.º 56
0
class TestClaiming(OsfTestCase):
    def setUp(self):
        super(TestClaiming, self).setUp()
        self.referrer = AuthUserFactory()
        self.project = ProjectFactory(creator=self.referrer, is_public=True)

    def test_correct_name_shows_in_contributor_list(self):
        name1, email = fake.name(), fake_email()
        UnregUserFactory(fullname=name1, email=email)
        name2, email = fake.name(), fake_email()
        # Added with different name
        self.project.add_unregistered_contributor(fullname=name2,
                                                  email=email,
                                                  auth=Auth(self.referrer))
        self.project.save()

        res = self.app.get(self.project.url, auth=self.referrer.auth)
        # Correct name is shown
        assert_in_html(name2, res)
        assert_not_in(name1, res)

    def test_user_can_set_password_on_claim_page(self):
        name, email = fake.name(), fake_email()
        new_user = self.project.add_unregistered_contributor(
            email=email, fullname=name, auth=Auth(self.referrer))
        self.project.save()
        claim_url = new_user.get_claim_url(self.project._primary_key)
        res = self.app.get(claim_url)
        self.project.reload()
        assert_in('Set Password', res)
        form = res.forms['setPasswordForm']
        #form['username'] = new_user.username #Removed as long as E-mail can't be updated.
        form['password'] = '******'
        form['password2'] = 'killerqueen'
        res = form.submit().follow()
        new_user.reload()
        assert_true(new_user.check_password('killerqueen'))

    def test_sees_is_redirected_if_user_already_logged_in(self):
        name, email = fake.name(), fake_email()
        new_user = self.project.add_unregistered_contributor(
            email=email, fullname=name, auth=Auth(self.referrer))
        self.project.save()
        existing = AuthUserFactory()
        claim_url = new_user.get_claim_url(self.project._primary_key)
        # a user is already logged in
        res = self.app.get(claim_url, auth=existing.auth, expect_errors=True)
        assert_equal(res.status_code, 302)

    def test_unregistered_users_names_are_project_specific(self):
        name1, name2, email = fake.name(), fake.name(), fake_email()
        project2 = ProjectFactory(creator=self.referrer)
        # different projects use different names for the same unreg contributor
        self.project.add_unregistered_contributor(email=email,
                                                  fullname=name1,
                                                  auth=Auth(self.referrer))
        self.project.save()
        project2.add_unregistered_contributor(email=email,
                                              fullname=name2,
                                              auth=Auth(self.referrer))
        project2.save()
        self.app.authenticate(*self.referrer.auth)
        # Each project displays a different name in the contributor list
        res = self.app.get(self.project.url)
        assert_in_html(name1, res)

        res2 = self.app.get(project2.url)
        assert_in_html(name2, res2)

    @unittest.skip("as long as E-mails cannot be changed")
    def test_cannot_set_email_to_a_user_that_already_exists(self):
        reg_user = UserFactory()
        name, email = fake.name(), fake_email()
        new_user = self.project.add_unregistered_contributor(
            email=email, fullname=name, auth=Auth(self.referrer))
        self.project.save()
        # Goes to claim url and successfully claims account
        claim_url = new_user.get_claim_url(self.project._primary_key)
        res = self.app.get(claim_url)
        self.project.reload()
        assert_in('Set Password', res)
        form = res.forms['setPasswordForm']
        # Fills out an email that is the username of another user
        form['username'] = reg_user.username
        form['password'] = '******'
        form['password2'] = 'killerqueen'
        res = form.submit().maybe_follow(expect_errors=True)
        assert_in(language.ALREADY_REGISTERED.format(email=reg_user.username),
                  res)

    def test_correct_display_name_is_shown_at_claim_page(self):
        original_name = fake.name()
        unreg = UnregUserFactory(fullname=original_name)

        different_name = fake.name()
        new_user = self.project.add_unregistered_contributor(
            email=unreg.username,
            fullname=different_name,
            auth=Auth(self.referrer),
        )
        self.project.save()
        claim_url = new_user.get_claim_url(self.project._primary_key)
        res = self.app.get(claim_url)
        # Correct name (different_name) should be on page
        assert_in_html(different_name, res)
Exemplo n.º 57
0
class TestExplorePublicActivity(OsfTestCase):
    def setUp(self):
        super(TestExplorePublicActivity, self).setUp()
        self.project = ProjectFactory(is_public=True)
        self.registration = RegistrationFactory(project=self.project)
        self.private_project = ProjectFactory(title="Test private project")
        self.popular_project = ProjectFactory(is_public=True)
        self.popular_registration = RegistrationFactory(project=self.project,
                                                        is_public=True)

        # Add project to new and noteworthy projects
        self.new_and_noteworthy_links_node = ProjectFactory(is_public=True)
        self.new_and_noteworthy_links_node._id = settings.NEW_AND_NOTEWORTHY_LINKS_NODE
        self.new_and_noteworthy_links_node.add_pointer(
            self.project,
            auth=Auth(self.new_and_noteworthy_links_node.creator),
            save=True)

        # Set up popular projects and registrations
        self.popular_links_node = ProjectFactory(is_public=True)
        settings.POPULAR_LINKS_NODE = self.popular_links_node._id
        self.popular_links_node.add_pointer(
            self.popular_project,
            auth=Auth(self.popular_links_node.creator),
            save=True)

        self.popular_links_registrations = ProjectFactory(is_public=True)
        settings.POPULAR_LINKS_REGISTRATIONS = self.popular_links_registrations._id
        self.popular_links_registrations.add_pointer(
            self.popular_registration,
            auth=Auth(self.popular_links_registrations.creator),
            save=True)

    def test_explore_page_loads_when_settings_not_configured(self):

        old_settings_values = settings.POPULAR_LINKS_NODE, settings.NEW_AND_NOTEWORTHY_LINKS_NODE, settings.POPULAR_LINKS_REGISTRATIONS

        settings.POPULAR_LINKS_NODE = 'notanode'
        settings.NEW_AND_NOTEWORTHY_LINKS_NODE = 'alsototallywrong'
        settings.POPULAR_LINKS_REGISTRATIONS = 'nopenope'

        url = self.project.web_url_for('activity')
        res = self.app.get(url)
        assert_equal(res.status_code, 200)

        settings.POPULAR_LINKS_NODE, settings.NEW_AND_NOTEWORTHY_LINKS_NODE, settings.POPULAR_LINKS_REGISTRATIONS = old_settings_values

    def test_new_and_noteworthy_and_popular_nodes_show_in_explore_activity(
            self):

        url = self.project.web_url_for('activity')
        res = self.app.get(url)
        assert_equal(res.status_code, 200)

        # New and Noteworthy
        assert_in(str(self.project.title), res)
        assert_in(str(self.project.created.date()), res)
        assert_in(str(self.registration.title), res)
        assert_in(str(self.registration.registered_date.date()), res)
        assert_not_in(str(self.private_project.title), res)

        # Popular Projects and Registrations
        assert_in(str(self.popular_project.title), res)
        assert_in(str(self.popular_project.created.date()), res)
        assert_in(str(self.popular_registration.title), res)
        assert_in(str(self.popular_registration.registered_date.date()), res)
Exemplo n.º 58
0
    def setUp(self):
        super(RegistrationsTestBase, self).setUp()

        self.user = AuthUserFactory()
        self.auth = Auth(self.user)
        self.node = ProjectFactory(creator=self.user)
        self.non_admin = AuthUserFactory()
        self.node.add_contributor(
            self.non_admin,
            permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS,
            auth=self.auth,
            save=True
        )
        self.non_contrib = AuthUserFactory()
        self.group_mem = AuthUserFactory()
        self.group = OSFGroupFactory(creator=self.group_mem)
        self.node.add_osf_group(self.group, permissions.ADMIN)

        self.meta_schema = RegistrationSchema.objects.get(name='Open-Ended Registration', schema_version=2)

        self.draft = DraftRegistrationFactory(
            initiator=self.user,
            branched_from=self.node,
            registration_schema=self.meta_schema,
            registration_metadata={
                'summary': {'value': 'Some airy'}
            }
        )

        current_month = timezone.now().strftime('%B')
        current_year = timezone.now().strftime('%Y')

        valid_date = timezone.now() + dt.timedelta(days=180)
        self.embargo_payload = {
            'data': {
                'attributes': {
                    'children': [self.node._id],
                    'draft_registration': self.draft._id,
                    'lift_embargo': unicode(valid_date.strftime('%a, %d, %B %Y %H:%M:%S')) + u' GMT',
                    'registration_choice': 'embargo',
                },
                'type': 'registrations',
            },
        }
        self.invalid_embargo_date_payload = copy.deepcopy(self.embargo_payload)
        self.invalid_embargo_date_payload['data']['attributes']['lift_embargo'] = u'Thu, 01 {month} {year} 05:00:00 GMT'.format(
            month=current_month,
            year=str(int(current_year) - 1)
        )

        self.immediate_payload = {
            'data': {
                'attributes': {
                    'children': [self.node._id],
                    'draft_registration': self.draft._id,
                    'registration_choice': 'immediate',
                },
                'type': 'registrations',
            },
        }
        self.invalid_payload = copy.deepcopy(self.immediate_payload)
        self.invalid_payload['data']['attributes']['registration_choice'] = 'foobar'
Exemplo n.º 59
0
 def setUp(self):
     super(TestClaiming, self).setUp()
     self.referrer = AuthUserFactory()
     self.project = ProjectFactory(creator=self.referrer, is_public=True)
Exemplo n.º 60
0
 def valid_preprint_node(self, user):
     return ProjectFactory(creator=user)