Beispiel #1
0
class TestHookMigration(OsfTestCase):

    def setUp(self):
        super(TestHookMigration, self).setUp()
        self.project = ProjectFactory()
        self.project.creator.add_addon('github')
        self.user_addon = self.project.creator.get_addon('github')
        self.project.add_addon('github', None)
        self.node_addon = self.project.get_addon('github')
        self.node_addon.hook_id = 1
        self.node_addon.user_settings = self.user_addon
        self.node_addon.save()

    @mock.patch('addons.github.utils.make_hook_secret')
    @mock.patch('addons.github.api.GitHub.repo')
    def test_update_hook(self, mock_repo, mock_make_secret):
        mock_make_secret.return_value = 'shh'
        update_hook(self.node_addon)
        self.node_addon.reload()
        assert_equal(self.node_addon.hook_secret, 'shh')

    def test_get_targets(self):
        AddonGitHubNodeSettings.remove()
        addons = [
            AddonGitHubNodeSettings(),
            AddonGitHubNodeSettings(hook_id=1),
            AddonGitHubNodeSettings(user_settings=self.user_addon),
            AddonGitHubNodeSettings(hook_id=1, user_settings=self.user_addon),
        ]
        for addon in addons:
            addon.save()
        targets = get_targets()
        assert_equal(targets.count(), 1)
        assert_equal(targets[0]._id, addons[-1]._id)
Beispiel #2
0
class TestUtils(OsfTestCase):

    def setUp(self):
        OsfTestCase.setUp(self)
        self.project = ProjectFactory()

    def test_prepare_file_name(self):
        name, content, content_type, size = prepare_file(make_file_like(
            name='file')
        )
        assert_equal(name, 'file')

    def test_prepare_file_name_missing(self):
        name, content, content_type, size = prepare_file(
            make_file_like(name='ü')
        )
        assert_equal(name, settings.MISSING_FILE_NAME)

    def test_get_current_file_version(self):
        self.project.add_file(Auth(self.project.creator), 'foo', 'somecontent', 128, 'rst')
        result = get_latest_version_number('foo', node=self.project)
        assert_equal(result, 0)
        # Update the file
        self.project.add_file(Auth(self.project.creator), 'foo', 'newcontent', 128, 'rst')
        result = get_latest_version_number('foo', node=self.project)
        assert_equal(result, 1)

    def test_get_current_file_raises_error_when_file_not_found(self):
        with assert_raises(FileNotFoundError):
            get_latest_version_number('notfound', node=self.project)
class TestDatasetMigration(OsfTestCase):

    def setUp(self):
        super(TestDatasetMigration, self).setUp()
        self.project = ProjectFactory()
        self.project.creator.add_addon('dataverse')
        self.user_addon = self.project.creator.get_addon('dataverse')
        self.project.add_addon('dataverse', None)
        self.node_addon = self.project.get_addon('dataverse')
        self.node_addon.study_hdl = 'doi:12.3456/DVN/00003'
        self.node_addon.study = 'Example (DVN/00003)'
        self.node_addon.user_settings = self.user_addon
        self.node_addon.save()

    def test_migration(self):

        do_migration([self.node_addon], dry=False)
        self.node_addon.reload()

        assert_equal(self.node_addon.dataset_doi, 'doi:12.3456/DVN/00003')
        assert_equal(self.node_addon.dataset, 'Example (DVN/00003)')

    def test_get_targets(self):
        AddonDataverseNodeSettings.remove()
        addons = [
            AddonDataverseNodeSettings(),
            AddonDataverseNodeSettings(study_hdl='foo'),
            AddonDataverseNodeSettings(user_settings=self.user_addon),
            AddonDataverseNodeSettings(study_hdl='foo', user_settings=self.user_addon),
        ]
        for addon in addons:
            addon.save()
        targets = get_targets()
        assert_equal(targets.count(), 1)
        assert_equal(targets[0]._id, addons[-1]._id)
Beispiel #4
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.append(self.public_project)
        self.anonymized_link_to_public_project.save()
        self.anonymized_link_to_private_project.nodes.append(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 = TestApp(self.flaskapp)
Beispiel #5
0
class TestViewsAuth(OsfTestCase):

    def setUp(self):

        super(TestViewsAuth, self).setUp()

        self.user = AuthUserFactory()
        self.consolidated_auth = Auth(user=self.user)
        self.auth = ('test', self.user.api_keys[0]._primary_key)
        self.project = ProjectFactory(creator=self.user)

        self.non_authenticator = AuthUserFactory()
        self.project.add_contributor(
            contributor=self.non_authenticator,
            auth=Auth(self.project.creator),
        )

        self.project.add_addon('figshare', auth=self.consolidated_auth)
        self.project.creator.add_addon('figshare')
        self.node_settings = self.project.get_addon('figshare')
        self.user_settings = self.project.creator.get_addon('figshare')
        self.node_settings.user_settings = self.user_settings
        self.node_settings.figshare_id = '436'
        self.node_settings.figshare_type = 'project'
        self.node_settings.save()

    @unittest.skip('finish this')
    def test_oauth_fail(self):
        url = '/api/v1/project/{0}/figshare/oauth/'.format(self.project._id)
        self.app.get(url, auth=self.user.auth)

    @unittest.skip('finish this')
    def test_oauth_bad_token(self):
        pass
Beispiel #6
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
Beispiel #7
0
class TestGoogleDriveHgridViews(OsfTestCase):

    def setUp(self):
        super(TestGoogleDriveHgridViews, self).setUp()
        self.user = AuthUserFactory()
        self.user.add_addon('googledrive')
        self.project = ProjectFactory(creator=self.user)
        self.project.add_addon('googledrive', Auth(self.user))
        self.node_settings = self.project.get_addon('googledrive')
        self.user_settings = self.user.get_addon('googledrive')
        self.node_settings.user_settings = self.user_settings
        self.user_settings.save()
        self.node_settings.save()
        # Log user in
        self.app.authenticate(*self.user.auth)

    @mock.patch('website.addons.googledrive.views.hgrid.GoogleDriveClient.folders')
    def test_googledrive_folders(self, mock_drive_client_folders):
        folderId = '12345'
        mock_drive_client_folders.return_value = mock_folders['items']
        url = api_url_for('googledrive_folders', pid=self.project._primary_key, folderId=folderId)
        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.status_code, 200)
        assert_equal(len(res.json), len(mock_folders['items']))

    @mock.patch('website.addons.googledrive.views.hgrid.GoogleDriveClient.about')
    def test_googledrive_folders_returns_only_root(self, mock_about):
        mock_about.return_value = {'rootFolderId': '24601'}

        url = self.project.api_url_for('googledrive_folders')
        res = self.app.get(url, auth=self.user.auth)

        assert_equal(len(res.json), 1)
        assert_equal(res.status_code, 200)
        assert_equal(res.json[0]['id'], '24601')
Beispiel #8
0
    def setUp(self):
        super(TestNodeTags, self).setUp()
        self.user = AuthUserFactory()
        self.admin = AuthUserFactory()
        self.user_two = AuthUserFactory()
        self.read_only_contributor = AuthUserFactory()

        self.public_project = ProjectFactory(title="Project One", is_public=True, creator=self.user)
        self.public_project.add_contributor(self.user, permissions=permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS, save=True)
        self.private_project = ProjectFactory(title="Project Two", is_public=False, creator=self.user)
        self.private_project.add_contributor(self.user, permissions=permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS, save=True)
        self.private_project.add_contributor(self.admin, permissions=permissions.CREATOR_PERMISSIONS, save=True)
        self.public_url = '/{}nodes/{}/'.format(API_BASE, self.public_project._id)
        self.private_url = '/{}nodes/{}/'.format(API_BASE, self.private_project._id)

        self.one_new_tag_json = {
            'data': {
                'id': self.public_project._id,
                'type': 'nodes',
                'attributes': {
                    'tags': ['new-tag']
                }
            }
        }
        self.private_payload = {
            'data': {
                'id': self.private_project._id,
                'type': 'nodes',
                'attributes': {
                    'tags': ['new-tag']
                }
            }
        }
Beispiel #9
0
class TestSearchExceptions(OsfTestCase):
    """
    Verify that the correct exception is thrown when the connection is lost
    """

    @classmethod
    def setUpClass(cls):
        logging.getLogger('website.project.model').setLevel(logging.CRITICAL)
        super(TestSearchExceptions, cls).setUpClass()
        if settings.SEARCH_ENGINE == 'elastic':
            cls._es = search.search_engine.es
            search.search_engine.es = None

    @classmethod
    def tearDownClass(cls):
        super(TestSearchExceptions, cls).tearDownClass()
        if settings.SEARCH_ENGINE == 'elastic':
            search.search_engine.es = cls._es

    def test_connection_error(self):
        # Ensures that saving projects/users doesn't break as a result of connection errors
        self.user = UserFactory(usename='Doug Bogie')
        self.project = ProjectFactory(
            title="Tom Sawyer",
            creator=self.user,
            is_public=True,
        )
        self.user.save()
        self.project.save()
    def test_populate_new_and_noteworthy(self):
        self.popular_links_node = ProjectFactory(creator=self.user)
        self.popular_links_node._id = POPULAR_LINKS_NODE
        self.popular_links_node.save()
        self.new_and_noteworthy_links_node = ProjectFactory()
        self.new_and_noteworthy_links_node._id = NEW_AND_NOTEWORTHY_LINKS_NODE
        self.new_and_noteworthy_links_node.save()

        popular_nodes = [self.pop1, self.pop2, self.pop3, self.pop4, self.pop5]

        for node in popular_nodes:
            self.popular_links_node.add_pointer(node, auth=Auth(self.user), save=True)

        assert_equal(len(self.popular_links_node.nodes), 5)
        assert_equal(len(self.new_and_noteworthy_links_node.nodes), 0)


        script.main(dry_run=False)
        self.popular_links_node.reload()
        self.new_and_noteworthy_links_node.reload()

        assert_equal(len(self.popular_links_node.nodes), 0)  # verifies remove pointer is working
        assert_equal(len(self.new_and_noteworthy_links_node.nodes), 5)

        script.main(dry_run=False)

        self.popular_links_node.reload()
        self.new_and_noteworthy_links_node.reload()

        popular_node_links = [pointer.node._id for pointer in self.popular_links_node.nodes]
        assert_equal(popular_node_links, [])

        new_and_noteworthy_node_links = {pointer.node._id for pointer in self.new_and_noteworthy_links_node.nodes}

        assert_equal(set(new_and_noteworthy_node_links), {self.nn1._id, self.nn2._id, self.nn3._id, self.nn4._id, self.nn5._id})
    def test_POST_register_embargo_does_not_make_project_or_children_public(self, mock_enqueue):
        public_project = ProjectFactory(creator=self.user, is_public=True)
        component = NodeFactory(creator=self.user, parent=public_project, title="Component", is_public=True)
        subproject = ProjectFactory(creator=self.user, parent=public_project, title="Subproject", is_public=True)
        subproject_component = NodeFactory(creator=self.user, parent=subproject, title="Subcomponent", is_public=True)
        res = self.app.post(
            public_project.api_url_for("node_register_template_page_post", template=u"Open-Ended_Registration"),
            self.valid_embargo_payload,
            content_type="application/json",
            auth=self.user.auth,
        )
        public_project.reload()
        assert_equal(res.status_code, 201)

        # Last node directly registered from self.project
        registration = Node.load(public_project.node__registrations[-1])

        assert_true(registration.is_registration)
        assert_false(registration.is_public)
        assert_true(registration.is_pending_embargo_for_existing_registration)
        assert_is_not_none(registration.embargo)

        for node in registration.get_descendants_recursive():
            assert_true(node.is_registration)
            assert_false(node.is_public)
Beispiel #12
0
class TestCheckAuth(OsfTestCase):

    def setUp(self):
        super(TestCheckAuth, self).setUp()
        self.user = AuthUserFactory()
        self.node = ProjectFactory(creator=self.user)

    def test_has_permission(self):
        res = views.check_access(self.node, self.user, 'upload')
        assert_true(res)

    def test_not_has_permission_read_public(self):
        self.node.is_public = True
        self.node.save()
        res = views.check_access(self.node, None, 'download')

    def test_not_has_permission_read_has_link(self):
        link = new_private_link('red-special', self.user, [self.node], anonymous=False)
        res = views.check_access(self.node, None, 'download', key=link.key)

    def test_not_has_permission_logged_in(self):
        user2 = AuthUserFactory()
        with assert_raises(HTTPError) as exc_info:
            views.check_access(self.node, user2, 'download')
        assert_equal(exc_info.exception.code, 403)

    def test_not_has_permission_not_logged_in(self):
        with assert_raises(HTTPError) as exc_info:
            views.check_access(self.node, None, 'download')
        assert_equal(exc_info.exception.code, 401)
Beispiel #13
0
    def setUp(self):
        super(TestNodeTags, self).setUp()
        self.user = AuthUserFactory()
        self.admin = AuthUserFactory()
        self.user_two = AuthUserFactory()
        self.read_only_contributor = AuthUserFactory()

        self.public_project = ProjectFactory(title="Project One", is_public=True, creator=self.user)
        self.public_project.add_contributor(
            self.user, permissions=permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS, save=True
        )
        self.private_project = ProjectFactory(title="Project Two", is_public=False, creator=self.user)
        self.private_project.add_contributor(
            self.user, permissions=permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS, save=True
        )
        self.private_project.add_contributor(self.admin, permissions=permissions.CREATOR_PERMISSIONS, save=True)
        self.public_url = "/{}nodes/{}/".format(API_BASE, self.public_project._id)
        self.private_url = "/{}nodes/{}/".format(API_BASE, self.private_project._id)

        self.one_new_tag_json = {
            "data": {"id": self.public_project._id, "type": "nodes", "attributes": {"tags": ["new-tag"]}}
        }
        self.private_payload = {
            "data": {"id": self.private_project._id, "type": "nodes", "attributes": {"tags": ["new-tag"]}}
        }
Beispiel #14
0
class TestUserGet(AdminTestCase):
    def setUp(self):
        super(TestUserGet, self).setUp()
        User.remove()
        self.user_1 = AuthUserFactory()
        self.auth = Auth(user=self.user_1)
        self.project = ProjectFactory(creator=self.user_1)
        self.project.add_unregistered_contributor(
            email='*****@*****.**',
            fullname='Weezy F. Baby',
            auth=self.auth
        )
        self.user_3 = AuthUserFactory()
        self.user_3.date_confirmed = None
        self.user_3.save()
        self.user_4 = AuthUserFactory()

    def test_get_all_user_count(self):
        time_now = datetime.utcnow()
        count = get_all_user_count(time_now)
        nt.assert_equal(count, 4)

    def test_get_unregistered_users(self):
        count = get_unregistered_users()
        nt.assert_equal(count, 1)
Beispiel #15
0
 def test_project_dashboard_shows_no_wiki_content_text(self):
     # Regression test for:
     # https://github.com/CenterForOpenScience/openscienceframework.org/issues/1104
     project = ProjectFactory(creator=self.user)
     url = project.web_url_for('view_project')
     res = self.app.get(url, auth=self.user.auth)
     assert_in('No wiki content', res)
Beispiel #16
0
class TestNodeSettings(OsfTestCase):
    def setUp(self):
        super(TestNodeSettings, self).setUp()
        self.user = AuthUserFactory()
        self.project = ProjectFactory(creator=self.user)

        self.project.add_addon('figshare', auth=Auth(self.user))
        self.project.creator.add_addon('figshare')
        self.node_settings = self.project.get_addon('figshare')
        self.user_settings = self.project.creator.get_addon('figshare')
        self.user_settings.oauth_access_token = 'legittoken'
        self.user_settings.oauth_access_token_secret = 'legittoken'
        self.user_settings.save()
        self.node_settings.user_settings = self.user_settings
        self.node_settings.figshare_id = '123456'
        self.node_settings.figshare_type = 'project'
        self.node_settings.figshare_title = 'singlefile'
        self.node_settings.save()

    def test_complete_true(self):
        assert_true(self.node_settings.has_auth)
        assert_true(self.node_settings.complete)

    def test_complete_false(self):
        self.node_settings.figshare_id = None

        assert_true(self.node_settings.has_auth)
        assert_false(self.node_settings.complete)

    def test_complete_auth_false(self):
        self.node_settings.user_settings = None

        assert_false(self.node_settings.has_auth)
        assert_false(self.node_settings.complete)
Beispiel #17
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(project.creator), save=True)

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

        embargo = project._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)
Beispiel #18
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)
Beispiel #19
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)
Beispiel #20
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)

        self.log = self.node.logs[0]
        self.log_add_contributor = self.node.logs[1]

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

        self.public_log = self.public_node.logs[0]
        self.public_log_add_contributor = self.public_node.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)
Beispiel #21
0
class TestNodeSettings(OsfTestCase):
    def setUp(self):
        super(TestNodeSettings, self).setUp()
        self.user = UserFactory()
        self.project = ProjectFactory(creator=self.user)

        self.user.add_addon('s3')
        self.project.add_addon('s3', auth=Auth(self.user))

        self.user_settings = self.user.get_addon('s3')
        self.node_settings = self.project.get_addon('s3')

        self.user_settings.access_key = 'We-Will-Rock-You'
        self.user_settings.secret_key = 'Idontknowanyqueensongs'
        self.user_settings.save()

        self.node_settings.bucket = 'Sheer-Heart-Attack'
        self.node_settings.user_settings = self.user_settings
        self.node_settings.save()

    def test_complete_true(self):
        assert_true(self.node_settings.has_auth)
        assert_true(self.node_settings.complete)

    def test_complete_false(self):
        self.node_settings.bucket = None

        assert_true(self.node_settings.has_auth)
        assert_false(self.node_settings.complete)

    def test_complete_auth_false(self):
        self.node_settings.user_settings = None

        assert_false(self.node_settings.has_auth)
        assert_false(self.node_settings.complete)
Beispiel #22
0
 def test_cant_see_make_private_button_if_not_admin(self):
     # User is a contributor on a project
     project = ProjectFactory(is_public=True)
     project.add_contributor(self.user, permissions=["read", "write"], save=True)
     # User goes to the project page
     res = self.app.get(project.url, auth=self.auth).maybe_follow()
     assert_not_in("Make Private", res)
Beispiel #23
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 = SpamUserDeleteView()
     self.view = setup_log_view(self.view, self.request, guid=self.user._id)
    def test_migration(self):
        BoxUserSettings.remove()

        user = UserFactory()
        node = ProjectFactory(creator=user)
        account = BoxAccountFactory()

        user.external_accounts = [account]

        user.add_addon('box', auth=Auth(user))
        user_addon = user.get_addon('box')
        user_addon.save()


        node.add_addon('box', auth=Auth(user))
        node_addon = node.get_addon('box')
        node_addon.foreign_user_settings = user_addon
        node_addon.folder_id = 'abcdef0'
        node_addon.folder_path = '/'
        node_addon.folder_name = '/ (Full Box)'
        node_addon.save()

        assert_equal(node_addon.external_account, None)
        assert_equal(node_addon.folder_id, 'abcdef0')

        do_migration()
        node_addon.reload()

        assert_equal(node_addon.external_account, account)
        assert_equal(node_addon.folder_id, 'abcdef0')
        assert_equal(node_addon.folder_path, '/')
        assert_equal(node_addon.folder_name, '/ (Full Box)')
Beispiel #25
0
class TestDisableSpamUser(AdminTestCase):
    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 = SpamUserDeleteView()
        self.view = setup_log_view(self.view, self.request, guid=self.user._id)

    def test_get_object(self):
        obj = self.view.get_object()
        nt.assert_is_instance(obj, User)

    def test_get_context(self):
        res = self.view.get_context_data(object=self.user)
        nt.assert_in('guid', res)
        nt.assert_equal(res.get('guid'), self.user._id)

    def test_disable_spam_user(self):
        settings.ENABLE_EMAIL_SUBSCRIPTIONS = False
        count = OSFLogEntry.objects.count()
        self.view.delete(self.request)
        self.user.reload()
        self.public_node.reload()
        nt.assert_true(self.user.is_disabled)
        nt.assert_false(self.public_node.is_public)
        nt.assert_equal(OSFLogEntry.objects.count(), count + 3)

    def test_no_user(self):
        view = setup_view(UserDeleteView(), self.request, guid='meh')
        with nt.assert_raises(Http404):
            view.delete(self.request)
Beispiel #26
0
class TestCreateBucket(OsfTestCase):

    def setUp(self):

        super(TestCreateBucket, self).setUp()

        self.user = AuthUserFactory()
        self.consolidated_auth = Auth(user=self.user)
        self.auth = ('test', self.user.api_keys[0]._primary_key)
        self.project = ProjectFactory(creator=self.user)

        self.project.add_addon('s3', auth=self.consolidated_auth)
        self.project.creator.add_addon('s3')

        self.user_settings = self.user.get_addon('s3')
        self.user_settings.access_key = 'We-Will-Rock-You'
        self.user_settings.secret_key = 'Idontknowanyqueensongs'
        self.user_settings.save()

        self.node_settings = self.project.get_addon('s3')
        self.node_settings.bucket = 'Sheer-Heart-Attack'
        self.node_settings.user_settings = self.project.creator.get_addon('s3')

        self.node_settings.save()

    def test_bad_names(self):
        assert_false(validate_bucket_name('bogus naMe'))
        assert_false(validate_bucket_name(''))
        assert_false(validate_bucket_name('no'))
        assert_false(validate_bucket_name('.cantstartwithp'))
        assert_false(validate_bucket_name('or.endwith.'))
        assert_false(validate_bucket_name('..nodoubles'))
        assert_false(validate_bucket_name('no_unders_in'))

    def test_names(self):
        assert_true(validate_bucket_name('imagoodname'))
        assert_true(validate_bucket_name('still.passing'))
        assert_true(validate_bucket_name('can-have-dashes'))
        assert_true(validate_bucket_name('kinda.name.spaced'))

    @mock.patch('website.addons.s3.views.crud.create_bucket')
    @mock.patch('website.addons.s3.utils.get_bucket_drop_down')
    def test_create_bucket_pass(self, mock_make, mock_dropdown):
        mock_make.return_value = True
        mock_dropdown.return_value = ['mybucket']
        url = self.project.api_url_for('create_new_bucket')
        ret = self.app.post_json(url, {'bucket_name': 'doesntevenmatter'}, auth=self.user.auth)

        assert_equals(ret.status_int, http.OK)

    @mock.patch('website.addons.s3.views.crud.create_bucket')
    def test_create_bucket_fail(self, mock_make):
        error = S3ResponseError(418, 'because Im a test')
        error.message = 'This should work'
        mock_make.side_effect = error

        url = "/api/v1/project/{0}/s3/newbucket/".format(self.project._id)
        ret = self.app.post_json(url, {'bucket_name': 'doesntevenmatter'}, auth=self.user.auth, expect_errors=True)

        assert_equals(ret.body, '{"message": "This should work", "title": "Problem connecting to S3"}')
Beispiel #27
0
class TestNodeDeleteView(AdminTestCase):
    def setUp(self):
        super(TestNodeDeleteView, self).setUp()
        self.node = ProjectFactory()
        self.request = RequestFactory().post('/fake_path')
        self.view = NodeDeleteView()
        self.view = setup_log_view(self.view, self.request,
                                   guid=self.node._id)

    def test_get_object(self):
        obj = self.view.get_object()
        nt.assert_is_instance(obj, Node)

    def test_get_context(self):
        res = self.view.get_context_data(object=self.node)
        nt.assert_in('guid', res)
        nt.assert_equal(res.get('guid'), self.node._id)

    def test_remove_node(self):
        count = OSFLogEntry.objects.count()
        self.view.delete(self.request)
        self.node.reload()
        nt.assert_true(self.node.is_deleted)
        nt.assert_equal(OSFLogEntry.objects.count(), count + 1)

    def test_restore_node(self):
        self.view.delete(self.request)
        nt.assert_true(self.node.is_deleted)
        count = OSFLogEntry.objects.count()
        self.view.delete(self.request)
        self.node.reload()
        nt.assert_false(self.node.is_deleted)
        nt.assert_equal(OSFLogEntry.objects.count(), count + 1)
Beispiel #28
0
    def setUp(self):
        super(TestNodeLicense, self).setUp()
        self.user = AuthUserFactory()
        self.admin = AuthUserFactory()
        self.user_two = AuthUserFactory()
        self.read_only_contributor = AuthUserFactory()

        self.public_project = ProjectFactory(title="Project One", is_public=True, creator=self.user)
        self.public_project.add_contributor(self.user, permissions=permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS, save=True)
        self.private_project = ProjectFactory(title="Project Two", is_public=False, creator=self.user)
        self.private_project.add_contributor(self.user, permissions=permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS, save=True)
        self.private_project.add_contributor(self.admin, permissions=permissions.CREATOR_PERMISSIONS, save=True)
        self.public_url = '/{}nodes/{}/'.format(API_BASE, self.public_project._id)
        self.private_url = '/{}nodes/{}/'.format(API_BASE, self.private_project._id)
        ensure_licenses()
        self.LICENSE_NAME = 'MIT License'
        self.node_license = NodeLicense.find_one(
            Q('name', 'eq', self.LICENSE_NAME)
        )
        self.YEAR = '2105'
        self.COPYRIGHT_HOLDERS = ['Foo', 'Bar']
        self.public_project.node_license = NodeLicenseRecordFactory(
            node_license=self.node_license,
            year=self.YEAR,
            copyright_holders=self.COPYRIGHT_HOLDERS
        )
        self.public_project.save()
        self.private_project.node_license = NodeLicenseRecordFactory(
            node_license=self.node_license,
            year=self.YEAR,
            copyright_holders=self.COPYRIGHT_HOLDERS
        )
        self.private_project.save()
    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 = FolderFactory()
        self.dashboard = DashboardFactory()

        self.url = "/{}registrations/".format(API_BASE)
Beispiel #30
0
class TestClaimingAsARegisteredUser(OsfTestCase):
    def setUp(self):
        super(TestClaimingAsARegisteredUser, self).setUp()
        self.referrer = AuthUserFactory()
        self.project = ProjectFactory(creator=self.referrer, is_public=True)
        name, email = fake.name(), fake.email()
        self.user = self.project.add_unregistered_contributor(fullname=name, email=email, auth=Auth(user=self.referrer))
        self.project.save()

    def test_claim_user_registered_with_correct_password(self):
        reg_user = AuthUserFactory()  # NOTE: AuthUserFactory sets password as 'password'
        url = self.user.get_claim_url(self.project._primary_key)
        # Follow to password re-enter page
        res = self.app.get(url, auth=reg_user.auth).follow(auth=reg_user.auth)

        # verify that the "Claim Account" form is returned
        assert_in("Claim Contributor", res.body)

        form = res.forms["claimContributorForm"]
        form["password"] = "******"
        res = form.submit(auth=reg_user.auth).follow(auth=reg_user.auth)

        self.project.reload()
        self.user.reload()
        # user is now a contributor to the project
        assert_in(reg_user._primary_key, self.project.contributors)

        # the unregistered user (self.user) is removed as a contributor, and their
        assert_not_in(self.user._primary_key, self.project.contributors)

        # unclaimed record for the project has been deleted
        assert_not_in(self.project._primary_key, self.user.unclaimed_records)
Beispiel #31
0
class TestAddonLogs(OsfTestCase):
    def setUp(self):
        super(TestAddonLogs, self).setUp()
        self.user = AuthUserFactory()
        self.auth_obj = Auth(user=self.user)
        self.node = ProjectFactory(creator=self.user)
        self.session = Session(data={'auth_user_id': self.user._id})
        self.session.save()
        self.cookie = itsdangerous.Signer(settings.SECRET_KEY).sign(
            self.session._id)
        self.configure_addon()

    def configure_addon(self):
        self.user.add_addon('github')
        self.user_addon = self.user.get_addon('github')
        self.oauth_settings = GitHubAccountFactory(display_name='john')
        self.oauth_settings.save()
        self.user.external_accounts.append(self.oauth_settings)
        self.user.save()
        self.node.add_addon('github', self.auth_obj)
        self.node_addon = self.node.get_addon('github')
        self.node_addon.user = '******'
        self.node_addon.repo = 'youre-my-best-friend'
        self.node_addon.user_settings = self.user_addon
        self.node_addon.external_account = self.oauth_settings
        self.node_addon.save()

    def build_payload(self, metadata, **kwargs):
        options = dict(
            auth={'id': self.user._id},
            action='create',
            provider=self.node_addon.config.short_name,
            metadata=metadata,
            time=time.time() + 1000,
        )
        options.update(kwargs)
        options = {
            key: value
            for key, value in options.iteritems() if value is not None
        }
        message, signature = signing.default_signer.sign_payload(options)
        return {
            'payload': message,
            'signature': signature,
        }

    @mock.patch('website.notifications.events.files.FileAdded.perform')
    def test_add_log(self, mock_perform):
        path = 'pizza'
        url = self.node.api_url_for('create_waterbutler_log')
        payload = self.build_payload(metadata={'path': path})
        nlogs = len(self.node.logs)
        self.app.put_json(url,
                          payload,
                          headers={'Content-Type': 'application/json'})
        self.node.reload()
        assert_equal(len(self.node.logs), nlogs + 1)
        # # Mocking form_message and perform so that the payload need not be exact.
        # assert_true(mock_form_message.called, "form_message not called")
        assert_true(mock_perform.called, "perform not called")

    def test_add_log_missing_args(self):
        path = 'pizza'
        url = self.node.api_url_for('create_waterbutler_log')
        payload = self.build_payload(metadata={'path': path}, auth=None)
        nlogs = len(self.node.logs)
        res = self.app.put_json(
            url,
            payload,
            headers={'Content-Type': 'application/json'},
            expect_errors=True,
        )
        assert_equal(res.status_code, 400)
        self.node.reload()
        assert_equal(len(self.node.logs), nlogs)

    def test_add_log_no_user(self):
        path = 'pizza'
        url = self.node.api_url_for('create_waterbutler_log')
        payload = self.build_payload(metadata={'path': path},
                                     auth={'id': None})
        nlogs = len(self.node.logs)
        res = self.app.put_json(
            url,
            payload,
            headers={'Content-Type': 'application/json'},
            expect_errors=True,
        )
        assert_equal(res.status_code, 400)
        self.node.reload()
        assert_equal(len(self.node.logs), nlogs)

    def test_add_log_no_addon(self):
        path = 'pizza'
        node = ProjectFactory(creator=self.user)
        url = node.api_url_for('create_waterbutler_log')
        payload = self.build_payload(metadata={'path': path})
        nlogs = len(node.logs)
        res = self.app.put_json(
            url,
            payload,
            headers={'Content-Type': 'application/json'},
            expect_errors=True,
        )
        assert_equal(res.status_code, 400)
        self.node.reload()
        assert_equal(len(node.logs), nlogs)

    def test_add_log_bad_action(self):
        path = 'pizza'
        url = self.node.api_url_for('create_waterbutler_log')
        payload = self.build_payload(metadata={'path': path}, action='dance')
        nlogs = len(self.node.logs)
        res = self.app.put_json(
            url,
            payload,
            headers={'Content-Type': 'application/json'},
            expect_errors=True,
        )
        assert_equal(res.status_code, 400)
        self.node.reload()
        assert_equal(len(self.node.logs), nlogs)

    def test_action_file_rename(self):
        url = self.node.api_url_for('create_waterbutler_log')
        payload = self.build_payload(
            action='rename',
            metadata={
                'path': 'foo',
            },
            source={
                'materialized': 'foo',
                'provider': 'github',
                'node': {
                    '_id': self.node._id
                },
                'name': 'new.txt',
                'kind': 'file',
            },
            destination={
                'path': 'foo',
                'materialized': 'foo',
                'provider': 'github',
                'node': {
                    '_id': self.node._id
                },
                'name': 'old.txt',
                'kind': 'file',
            },
        )
        self.app.put_json(url,
                          payload,
                          headers={'Content-Type': 'application/json'})
        self.node.reload()

        assert_equal(
            self.node.logs[-1].action,
            'github_addon_file_renamed',
        )
Beispiel #32
0
 def test_get_or_create_node_exists(self):
     node = ProjectFactory()
     fetched, created = utils.get_or_create_node(node.title, node.creator)
     assert_false(created)
     assert_equal(node._id, fetched._id)
Beispiel #33
0
class TestRegistrationFiltering(ApiTestCase):
    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 = BookmarkCollectionFactory()

        self.url = "/{}registrations/".format(API_BASE)

    def tearDown(self):
        super(TestRegistrationFiltering, self).tearDown()
        Node.remove()

    def test_filtering_by_category(self):
        url = '/{}registrations/?filter[category]=hypothesis'.format(API_BASE)
        res = self.app.get(url, auth=self.user_one.auth)
        registration_json = res.json['data']
        ids = [each['id'] for each in registration_json]

        assert_in(self.project_one_reg._id, ids)
        assert_not_in(self.project_two_reg._id, ids)
        assert_not_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

    def test_filtering_by_public(self):
        url = '/{}registrations/?filter[public]=false'.format(API_BASE)
        res = self.app.get(url, auth=self.user_one.auth)
        reg_json = res.json['data']

        # No public projects returned
        assert_false(any([each['attributes']['public'] for each in reg_json]))

        ids = [each['id'] for each in reg_json]
        assert_not_in(self.project_one_reg._id, ids)
        assert_not_in(self.project_two_reg._id, ids)

        url = '/{}registrations/?filter[public]=true'.format(API_BASE)
        res = self.app.get(url, auth=self.user_one.auth)
        reg_json = res.json['data']

        # No private projects returned
        assert_true(all([each['attributes']['public'] for each in reg_json]))

        ids = [each['id'] for each in reg_json]
        assert_in(self.project_one_reg._id, ids)
        assert_in(self.project_two_reg._id, ids)
        assert_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

    def test_filtering_tags(self):

        # both project_one and project_two have tag1
        url = '/{}registrations/?filter[tags]={}'.format(API_BASE, 'tag1')

        res = self.app.get(url, auth=self.project_one.creator.auth)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_in(self.project_one_reg._id, ids)
        assert_in(self.project_two_reg._id, ids)
        assert_not_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

        # filtering two tags
        # project_one has both tags; project_two only has one
        url = '/{}registrations/?filter[tags]={}&filter[tags]={}'.format(
            API_BASE, 'tag1', 'tag2')

        res = self.app.get(url, auth=self.project_one.creator.auth)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_in(self.project_one_reg._id, ids)
        assert_not_in(self.project_two_reg._id, ids)
        assert_not_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

    def test_get_all_registrations_with_no_filter_logged_in(self):
        res = self.app.get(self.url, auth=self.user_one.auth)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_in(self.project_one_reg._id, ids)
        assert_in(self.project_two_reg._id, ids)
        assert_in(self.project_three_reg._id, ids)
        assert_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

        assert_not_in(self.project_one._id, ids)
        assert_not_in(self.project_two._id, ids)
        assert_not_in(self.project_three._id, ids)
        assert_not_in(self.private_project_user_one._id, ids)
        assert_not_in(self.private_project_user_two._id, ids)
        assert_not_in(self.folder._id, ids)
        assert_not_in(self.bookmark_collection._id, ids)

    def test_get_all_registrations_with_no_filter_not_logged_in(self):
        res = self.app.get(self.url)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_in(self.project_one_reg._id, ids)
        assert_in(self.project_two_reg._id, ids)
        assert_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

        assert_not_in(self.project_one._id, ids)
        assert_not_in(self.project_two._id, ids)
        assert_not_in(self.project_three._id, ids)
        assert_not_in(self.private_project_user_one._id, ids)
        assert_not_in(self.private_project_user_two._id, ids)
        assert_not_in(self.folder._id, ids)
        assert_not_in(self.bookmark_collection._id, ids)

    def test_get_one_registration_with_exact_filter_logged_in(self):
        url = "/{}registrations/?filter[title]=Project%20One".format(API_BASE)

        res = self.app.get(url, auth=self.user_one.auth)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_in(self.project_one_reg._id, ids)
        assert_not_in(self.project_two_reg._id, ids)
        assert_not_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

        assert_not_in(self.folder._id, ids)
        assert_not_in(self.bookmark_collection._id, ids)

    def test_get_one_registration_with_exact_filter_not_logged_in(self):
        url = "/{}registrations/?filter[title]=Private%20Project%20User%20One".format(
            API_BASE)

        res = self.app.get(url)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_not_in(self.project_one_reg._id, ids)
        assert_not_in(self.project_two_reg._id, ids)
        assert_not_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

        assert_not_in(self.folder._id, ids)
        assert_not_in(self.bookmark_collection._id, ids)

    def test_get_some_registrations_with_substring_logged_in(self):
        url = "/{}registrations/?filter[title]=Two".format(API_BASE)

        res = self.app.get(url, auth=self.user_one.auth)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_not_in(self.project_one_reg._id, ids)
        assert_in(self.project_two_reg._id, ids)
        assert_not_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

        assert_not_in(self.folder._id, ids)
        assert_not_in(self.bookmark_collection._id, ids)

    def test_get_some_registrations_with_substring_not_logged_in(self):
        url = "/{}registrations/?filter[title]=One".format(API_BASE)

        res = self.app.get(url)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_in(self.project_one_reg._id, ids)
        assert_not_in(self.project_two_reg._id, ids)
        assert_not_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

        assert_not_in(self.folder._id, ids)
        assert_not_in(self.bookmark_collection._id, ids)

    def test_get_only_public_or_my_registrations_with_filter_logged_in(self):
        url = "/{}registrations/?filter[title]=Project".format(API_BASE)

        res = self.app.get(url, auth=self.user_one.auth)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_in(self.project_one_reg._id, ids)
        assert_in(self.project_two_reg._id, ids)
        assert_not_in(self.project_three_reg._id, ids)
        assert_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

        assert_not_in(self.folder._id, ids)
        assert_not_in(self.bookmark_collection._id, ids)

    def test_get_only_public_registrations_with_filter_not_logged_in(self):
        url = "/{}registrations/?filter[title]=Project".format(API_BASE)

        res = self.app.get(url)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_in(self.project_one_reg._id, ids)
        assert_in(self.project_two_reg._id, ids)
        assert_not_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

        assert_not_in(self.folder._id, ids)
        assert_not_in(self.bookmark_collection._id, ids)

    def test_alternate_filtering_field_logged_in(self):
        url = "/{}registrations/?filter[description]=Three".format(API_BASE)

        res = self.app.get(url, auth=self.user_one.auth)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_not_in(self.project_one_reg._id, ids)
        assert_in(self.project_two_reg._id, ids)
        assert_not_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

        assert_not_in(self.folder._id, ids)
        assert_not_in(self.bookmark_collection._id, ids)

    def test_alternate_filtering_field_not_logged_in(self):
        url = "/{}registrations/?filter[description]=Two".format(API_BASE)

        res = self.app.get(url)
        reg_json = res.json['data']

        ids = [each['id'] for each in reg_json]
        assert_in(self.project_one_reg._id, ids)
        assert_not_in(self.project_two_reg._id, ids)
        assert_not_in(self.project_three_reg._id, ids)
        assert_not_in(self.private_project_user_one_reg._id, ids)
        assert_not_in(self.private_project_user_two_reg._id, ids)

        assert_not_in(self.folder._id, ids)
        assert_not_in(self.bookmark_collection._id, ids)

    def test_incorrect_filtering_field_not_logged_in(self):
        url = '/{}registrations/?filter[notafield]=bogus'.format(API_BASE)

        res = self.app.get(url, expect_errors=True)
        assert_equal(res.status_code, 400)
        errors = res.json['errors']
        assert_equal(len(errors), 1)
        assert_equal(errors[0]['detail'],
                     "'notafield' is not a valid field for this endpoint.")
Beispiel #34
0
class TestAddonAuth(OsfTestCase):
    def setUp(self):
        super(TestAddonAuth, self).setUp()
        self.user = AuthUserFactory()
        self.auth_obj = Auth(user=self.user)
        self.node = ProjectFactory(creator=self.user)
        self.session = Session(data={'auth_user_id': self.user._id})
        self.session.save()
        self.cookie = itsdangerous.Signer(settings.SECRET_KEY).sign(
            self.session._id)
        self.configure_addon()
        self.JWE_KEY = jwe.kdf(settings.WATERBUTLER_JWE_SECRET.encode('utf-8'),
                               settings.WATERBUTLER_JWE_SALT.encode('utf-8'))

    def configure_addon(self):
        self.user.add_addon('github')
        self.user_addon = self.user.get_addon('github')
        self.oauth_settings = GitHubAccountFactory(display_name='john')
        self.oauth_settings.save()
        self.user.external_accounts.append(self.oauth_settings)
        self.user.save()
        self.node.add_addon('github', self.auth_obj)
        self.node_addon = self.node.get_addon('github')
        self.node_addon.user = '******'
        self.node_addon.repo = 'youre-my-best-friend'
        self.node_addon.user_settings = self.user_addon
        self.node_addon.external_account = self.oauth_settings
        self.node_addon.save()

    def build_url(self, **kwargs):
        options = {
            'payload':
            jwe.encrypt(
                jwt.encode(
                    {
                        'data':
                        dict(
                            dict(
                                action='download',
                                nid=self.node._id,
                                provider=self.node_addon.config.short_name,
                            ), **kwargs),
                        'exp':
                        datetime.datetime.utcnow() + datetime.timedelta(
                            seconds=settings.WATERBUTLER_JWT_EXPIRATION),
                    },
                    settings.WATERBUTLER_JWT_SECRET,
                    algorithm=settings.WATERBUTLER_JWT_ALGORITHM),
                self.JWE_KEY)
        }
        return api_url_for('get_auth', **options)

    def test_auth_download(self):
        url = self.build_url()
        res = self.app.get(url, auth=self.user.auth)
        data = jwt.decode(jwe.decrypt(res.json['payload'].encode('utf-8'),
                                      self.JWE_KEY),
                          settings.WATERBUTLER_JWT_SECRET,
                          algorithm=settings.WATERBUTLER_JWT_ALGORITHM)['data']
        assert_equal(data['auth'], views.make_auth(self.user))
        assert_equal(data['credentials'],
                     self.node_addon.serialize_waterbutler_credentials())
        assert_equal(data['settings'],
                     self.node_addon.serialize_waterbutler_settings())
        expected_url = furl.furl(
            self.node.api_url_for('create_waterbutler_log', _absolute=True))
        observed_url = furl.furl(data['callback_url'])
        observed_url.port = expected_url.port
        assert_equal(expected_url, observed_url)

    def test_auth_missing_args(self):
        url = self.build_url(cookie=None)
        res = self.app.get(url, expect_errors=True)
        assert_equal(res.status_code, 401)

    def test_auth_bad_cookie(self):
        url = self.build_url(cookie=self.cookie)
        res = self.app.get(url, expect_errors=True)
        assert_equal(res.status_code, 200)
        data = jwt.decode(jwe.decrypt(res.json['payload'].encode('utf-8'),
                                      self.JWE_KEY),
                          settings.WATERBUTLER_JWT_SECRET,
                          algorithm=settings.WATERBUTLER_JWT_ALGORITHM)['data']
        assert_equal(data['auth'], views.make_auth(self.user))
        assert_equal(data['credentials'],
                     self.node_addon.serialize_waterbutler_credentials())
        assert_equal(data['settings'],
                     self.node_addon.serialize_waterbutler_settings())
        expected_url = furl.furl(
            self.node.api_url_for('create_waterbutler_log', _absolute=True))
        observed_url = furl.furl(data['callback_url'])
        observed_url.port = expected_url.port
        assert_equal(expected_url, observed_url)

    def test_auth_cookie(self):
        url = self.build_url(cookie=self.cookie[::-1])
        res = self.app.get(url, expect_errors=True)
        assert_equal(res.status_code, 401)

    def test_auth_missing_addon(self):
        url = self.build_url(provider='queenhub')
        res = self.app.get(url, expect_errors=True, auth=self.user.auth)
        assert_equal(res.status_code, 400)

    @mock.patch('website.addons.base.views.cas.get_client')
    def test_auth_bad_bearer_token(self, mock_cas_client):
        mock_cas_client.return_value = mock.Mock(profile=mock.Mock(
            return_value=cas.CasResponse(authenticated=False)))
        url = self.build_url()
        res = self.app.get(
            url,
            headers={'Authorization': 'Bearer invalid_access_token'},
            expect_errors=True)
        assert_equal(res.status_code, 403)
Beispiel #35
0
class TestAddonFileViews(OsfTestCase):
    @classmethod
    def setUpClass(cls):
        super(TestAddonFileViews, cls).setUpClass()
        PROVIDER_MAP['github'] = [TestFolder, TestFile, TestFileNode]
        TestFileNode.provider = 'github'

    def setUp(self):
        super(TestAddonFileViews, self).setUp()
        self.user = AuthUserFactory()
        self.project = ProjectFactory(creator=self.user)

        self.user.add_addon('github')
        self.project.add_addon('github', auth=Auth(self.user))

        self.user_addon = self.user.get_addon('github')
        self.node_addon = self.project.get_addon('github')
        self.oauth = GitHubAccountFactory()
        self.oauth.save()

        self.user.external_accounts.append(self.oauth)
        self.user.save()

        self.node_addon.user_settings = self.user_addon
        self.node_addon.external_account = self.oauth
        self.node_addon.repo = 'Truth'
        self.node_addon.user = '******'
        self.node_addon.save()

    @classmethod
    def tearDownClass(cls):
        super(TestAddonFileViews, cls).tearDownClass()
        PROVIDER_MAP['github'] = [
            models.GithubFolder, models.GithubFile, models.GithubFileNode
        ]
        del PROVIDER_MAP['test_addons']
        TrashedFileNode.remove()

    def get_test_file(self):
        version = models.FileVersion(identifier='1')
        version.save()
        versions = [version]
        ret = TestFile(name='Test',
                       node=self.project,
                       path='/test/Test',
                       materialized_path='/test/Test',
                       versions=versions)
        ret.save()
        return ret

    def get_second_test_file(self):
        version = models.FileVersion(identifier='1')
        version.save()
        ret = TestFile(name='Test2',
                       node=self.project,
                       path='/test/Test2',
                       materialized_path='/test/Test2',
                       versions=[version])
        ret.save()
        return ret

    def get_mako_return(self):
        ret = serialize_node(self.project, Auth(self.user), primary=True)
        ret.update({
            'error': '',
            'provider': '',
            'file_path': '',
            'sharejs_uuid': '',
            'private': '',
            'urls': {
                'files': '',
                'render': '',
                'sharejs': '',
                'mfr': '',
                'gravatar': '',
                'external': '',
                'archived_from': '',
            },
            'size': '',
            'extra': '',
            'file_name': '',
            'materialized_path': '',
            'file_id': '',
        })
        ret.update(rubeus.collect_addon_assets(self.project))
        return ret

    def test_redirects_to_guid(self):
        file_node = self.get_test_file()
        guid = file_node.get_guid(create=True)

        resp = self.app.get(self.project.web_url_for(
            'addon_view_or_download_file',
            path=file_node.path.strip('/'),
            provider='github'),
                            auth=self.user.auth)

        assert_equals(resp.status_code, 302)
        assert_equals(resp.location,
                      'http://*****:*****@mock.patch('website.addons.base.views.addon_view_file')
    def test_action_view_calls_view_file(self, mock_view_file):
        self.user.reload()
        self.project.reload()

        file_node = self.get_test_file()
        guid = file_node.get_guid(create=True)

        mock_view_file.return_value = self.get_mako_return()

        self.app.get('/{}/?action=view'.format(guid._id), auth=self.user.auth)

        args, kwargs = mock_view_file.call_args
        assert_equals(kwargs, {})
        assert_equals(args[0].user._id, self.user._id)
        assert_equals(args[1], self.project)
        assert_equals(args[2], file_node)
        assert_true(isinstance(args[3], file_node.touch(None).__class__))

    @mock.patch('website.addons.base.views.addon_view_file')
    def test_no_action_calls_view_file(self, mock_view_file):
        self.user.reload()
        self.project.reload()

        file_node = self.get_test_file()
        guid = file_node.get_guid(create=True)

        mock_view_file.return_value = self.get_mako_return()

        self.app.get('/{}/'.format(guid._id), auth=self.user.auth)

        args, kwargs = mock_view_file.call_args
        assert_equals(kwargs, {})
        assert_equals(args[0].user._id, self.user._id)
        assert_equals(args[1], self.project)
        assert_equals(args[2], file_node)
        assert_true(isinstance(args[3], file_node.touch(None).__class__))

    def test_download_create_guid(self):
        file_node = self.get_test_file()
        assert_is(file_node.get_guid(), None)

        self.app.get(self.project.web_url_for(
            'addon_view_or_download_file',
            path=file_node.path.strip('/'),
            provider='github',
        ),
                     auth=self.user.auth)

        assert_true(file_node.get_guid())

    def test_view_file_does_not_delete_file_when_requesting_invalid_version(
            self):
        with mock.patch(
                'website.addons.github.model.GitHubNodeSettings.is_private',
                new_callable=mock.PropertyMock) as mock_is_private:
            mock_is_private.return_value = False

            file_node = self.get_test_file()
            assert_is(file_node.get_guid(), None)

            url = self.project.web_url_for(
                'addon_view_or_download_file',
                path=file_node.path.strip('/'),
                provider='github',
            )
            # First view generated GUID
            self.app.get(url, auth=self.user.auth)

            self.app.get(url + '?version=invalid',
                         auth=self.user.auth,
                         expect_errors=True)

            assert_is_not_none(StoredFileNode.load(file_node._id))
            assert_is_none(TrashedFileNode.load(file_node._id))

    def test_unauthorized_addons_raise(self):
        path = 'cloudfiles'
        self.node_addon.user_settings = None
        self.node_addon.save()

        resp = self.app.get(self.project.web_url_for(
            'addon_view_or_download_file',
            path=path,
            provider='github',
            action='download'),
                            auth=self.user.auth,
                            expect_errors=True)

        assert_equals(resp.status_code, 401)

    def test_nonstorage_addons_raise(self):
        resp = self.app.get(self.project.web_url_for(
            'addon_view_or_download_file',
            path='sillywiki',
            provider='wiki',
            action='download'),
                            auth=self.user.auth,
                            expect_errors=True)

        assert_equals(resp.status_code, 400)

    def test_head_returns_url(self):
        file_node = self.get_test_file()
        guid = file_node.get_guid(create=True)

        resp = self.app.head('/{}/'.format(guid._id), auth=self.user.auth)
        location = furl.furl(resp.location)
        assert_urls_equal(
            location.url,
            file_node.generate_waterbutler_url(direct=None, version=None))

    def test_head_returns_url_with_version(self):
        file_node = self.get_test_file()
        guid = file_node.get_guid(create=True)

        resp = self.app.head('/{}/?revision=1&foo=bar'.format(guid._id),
                             auth=self.user.auth)
        location = furl.furl(resp.location)
        # Note: version is added but us but all other url params are added as well
        assert_urls_equal(
            location.url,
            file_node.generate_waterbutler_url(direct=None,
                                               revision=1,
                                               version=None,
                                               foo='bar'))

    def test_nonexistent_addons_raise(self):
        path = 'cloudfiles'
        self.project.delete_addon('github', Auth(self.user))
        self.project.save()

        resp = self.app.get(self.project.web_url_for(
            'addon_view_or_download_file',
            path=path,
            provider='github',
            action='download'),
                            auth=self.user.auth,
                            expect_errors=True)

        assert_equals(resp.status_code, 400)

    def test_unauth_addons_raise(self):
        path = 'cloudfiles'
        self.node_addon.user_settings = None
        self.node_addon.save()

        resp = self.app.get(self.project.web_url_for(
            'addon_view_or_download_file',
            path=path,
            provider='github',
            action='download'),
                            auth=self.user.auth,
                            expect_errors=True)

        assert_equals(resp.status_code, 401)

    def test_delete_action_creates_trashed_file_node(self):
        file_node = self.get_test_file()
        payload = {
            'provider': file_node.provider,
            'metadata': {
                'path': '/test/Test',
                'materialized': '/test/Test'
            }
        }
        views.addon_delete_file_node(self=None,
                                     node=self.project,
                                     user=self.user,
                                     event_type='file_removed',
                                     payload=payload)
        assert_false(StoredFileNode.load(file_node._id))
        assert_true(TrashedFileNode.load(file_node._id))

    def test_delete_action_for_folder_deletes_subfolders_and_creates_trashed_file_nodes(
            self):
        file_node = self.get_test_file()
        subfolder = TestFolder(name='folder',
                               node=self.project,
                               path='/test/folder/',
                               materialized_path='/test/folder/',
                               versions=[])
        subfolder.save()
        payload = {
            'provider': file_node.provider,
            'metadata': {
                'path': '/test/',
                'materialized': '/test/'
            }
        }
        views.addon_delete_file_node(self=None,
                                     node=self.project,
                                     user=self.user,
                                     event_type='file_removed',
                                     payload=payload)
        assert_false(StoredFileNode.load(file_node._id))
        assert_true(TrashedFileNode.load(file_node._id))
        assert_false(StoredFileNode.load(subfolder._id))

    @mock.patch('website.archiver.tasks.archive')
    def test_archived_from_url(self, mock_archive):
        file_node = self.get_test_file()
        second_file_node = self.get_second_test_file()
        file_node.copied_from = second_file_node

        registered_node = self.project.register_node(
            schema=get_default_metaschema(),
            auth=Auth(self.user),
            data=None,
        )

        archived_from_url = views.get_archived_from_url(
            registered_node, file_node)
        view_url = self.project.web_url_for('addon_view_or_download_file',
                                            provider=file_node.provider,
                                            path=file_node.copied_from._id)
        assert_true(archived_from_url)
        assert_urls_equal(archived_from_url, view_url)

    @mock.patch('website.archiver.tasks.archive')
    def test_archived_from_url_without_copied_from(self, mock_archive):
        file_node = self.get_test_file()

        registered_node = self.project.register_node(
            schema=get_default_metaschema(),
            auth=Auth(self.user),
            data=None,
        )
        archived_from_url = views.get_archived_from_url(
            registered_node, file_node)
        assert_false(archived_from_url)

    @mock.patch('website.archiver.tasks.archive')
    def test_copied_from_id_trashed(self, mock_archive):
        file_node = self.get_test_file()
        second_file_node = self.get_second_test_file()
        file_node.copied_from = second_file_node
        self.project.register_node(
            schema=get_default_metaschema(),
            auth=Auth(self.user),
            data=None,
        )
        trashed_node = second_file_node.delete()
        assert_false(trashed_node.copied_from)
Beispiel #36
0
 def setUp(self):
     super(TestCheckOAuth, self).setUp()
     self.user = AuthUserFactory()
     self.node = ProjectFactory(creator=self.user)
Beispiel #37
0
class TestCheckAuth(OsfTestCase):
    def setUp(self):
        super(TestCheckAuth, self).setUp()
        self.user = AuthUserFactory()
        self.node = ProjectFactory(creator=self.user)

    def test_has_permission(self):
        res = views.check_access(self.node, Auth(user=self.user), 'upload',
                                 None)
        assert_true(res)

    def test_not_has_permission_read_public(self):
        self.node.is_public = True
        self.node.save()
        res = views.check_access(self.node, Auth(), 'download', None)

    def test_not_has_permission_read_has_link(self):
        link = new_private_link('red-special',
                                self.user, [self.node],
                                anonymous=False)
        res = views.check_access(self.node, Auth(private_key=link.key),
                                 'download', None)

    def test_not_has_permission_logged_in(self):
        user2 = AuthUserFactory()
        with assert_raises(HTTPError) as exc_info:
            views.check_access(self.node, Auth(user=user2), 'download', None)
        assert_equal(exc_info.exception.code, 403)

    def test_not_has_permission_not_logged_in(self):
        with assert_raises(HTTPError) as exc_info:
            views.check_access(self.node, Auth(), 'download', None)
        assert_equal(exc_info.exception.code, 401)

    def test_has_permission_on_parent_node_copyto_pass_if_registration(self):
        component_admin = AuthUserFactory()
        component = ProjectFactory(creator=component_admin, parent=self.node)
        component.is_registration = True

        assert_false(component.has_permission(self.user, 'write'))
        res = views.check_access(component, Auth(user=self.user), 'copyto',
                                 None)
        assert_true(res)

    def test_has_permission_on_parent_node_metadata_pass_if_registration(self):
        component_admin = AuthUserFactory()
        component = ProjectFactory(creator=component_admin,
                                   parent=self.node,
                                   is_public=False)

        component_registration = RegistrationFactory(project=component,
                                                     creator=component_admin)

        assert_false(component_registration.has_permission(self.user, 'read'))
        res = views.check_access(component_registration, Auth(user=self.user),
                                 'metadata', None)
        assert_true(res)

    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)

    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)
Beispiel #38
0
 def test_before_fork(self):
     node = ProjectFactory()
     message = self.node_settings.before_fork(node, self.user)
     assert_true(message)
Beispiel #39
0
class TestFileGuid(OsfTestCase):
    def setUp(self):
        super(OsfTestCase, self).setUp()
        self.user = UserFactory()
        self.project = ProjectFactory(creator=self.user)
        self.project.add_addon('dropbox', auth=Auth(self.user))
        self.node_addon = self.project.get_addon('dropbox')
        self.node_addon.folder = '/baz'
        self.node_addon.save()

    def test_provider(self):
        assert_equal('dropbox', DropboxFile().provider)

    def test_correct_path(self):
        guid = DropboxFile(node=self.project, path='baz/foo/bar')

        assert_equals(guid.path, 'baz/foo/bar')
        assert_equals(guid.waterbutler_path, '/foo/bar')

    def test_path_doesnt_crash_without_addon(self):
        guid = DropboxFile(node=self.project, path='baz/foo/bar')
        self.project.delete_addon('dropbox', Auth(self.user))

        assert_is(self.project.get_addon('dropbox'), None)

        assert_true(guid.path)
        assert_true(guid.waterbutler_path)

    def test_path_doesnt_crash_nonconfig_addon(self):
        guid = DropboxFile(node=self.project, path='baz/foo/bar')
        self.node_addon.folder = None
        self.node_addon.save()
        self.node_addon.reload()

        assert_true(guid.path)
        assert_true(guid.waterbutler_path)

    @mock.patch('website.addons.base.requests.get')
    def test_unique_identifier(self, mock_get):
        mock_response = mock.Mock(ok=True, status_code=200)
        mock_get.return_value = mock_response
        mock_response.json.return_value = {
            'data': {
                'name': 'Morty',
                'extra': {
                    'revisionId': 'Ricksy'
                }
            }
        }

        guid = DropboxFile(node=self.project, path='/foo/bar')

        guid.enrich()
        assert_equals('Ricksy', guid.unique_identifier)

    def test_node_addon_get_or_create(self):
        guid, created = self.node_addon.find_or_create_file_guid('/foo/bar')

        assert_true(created)
        assert_equal(guid.path, 'baz/foo/bar')
        assert_equal(guid.waterbutler_path, '/foo/bar')

    def test_node_addon_get_or_create_finds(self):
        guid1, created1 = self.node_addon.find_or_create_file_guid('/foo/bar')
        guid2, created2 = self.node_addon.find_or_create_file_guid('/foo/bar')

        assert_true(created1)
        assert_false(created2)
        assert_equals(guid1, guid2)

    def test_node_addon_get_or_create_finds_changed(self):
        guid1, created1 = self.node_addon.find_or_create_file_guid('/foo/bar')

        self.node_addon.folder = '/baz/foo'
        self.node_addon.save()
        self.node_addon.reload()
        guid2, created2 = self.node_addon.find_or_create_file_guid('/bar')

        assert_true(created1)
        assert_false(created2)
        assert_equals(guid1, guid2)
Beispiel #40
0
class TestLegacyViews(OsfTestCase):
    def setUp(self):
        super(TestLegacyViews, self).setUp()
        self.path = 'mercury.png'
        self.user = AuthUserFactory()
        self.project = ProjectFactory(creator=self.user)
        self.node_addon = self.project.get_addon('osfstorage')
        file_record = self.node_addon.get_root().append_file(self.path)
        self.expected_path = file_record._id
        self.node_addon.save()
        file_record.save()

    def test_view_file_redirect(self):
        url = '/{0}/osffiles/{1}/'.format(self.project._id, self.path)
        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.status_code, 301)
        expected_url = self.project.web_url_for(
            'addon_view_or_download_file',
            action='view',
            path=self.expected_path,
            provider='osfstorage',
        )
        assert_urls_equal(res.location, expected_url)

    def test_download_file_redirect(self):
        url = '/{0}/osffiles/{1}/download/'.format(self.project._id, self.path)
        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.status_code, 301)
        expected_url = self.project.web_url_for(
            'addon_view_or_download_file',
            path=self.expected_path,
            action='download',
            provider='osfstorage',
        )
        assert_urls_equal(res.location, expected_url)

    def test_download_file_version_redirect(self):
        url = '/{0}/osffiles/{1}/version/3/download/'.format(
            self.project._id,
            self.path,
        )
        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.status_code, 301)
        expected_url = self.project.web_url_for(
            'addon_view_or_download_file',
            version=3,
            path=self.expected_path,
            action='download',
            provider='osfstorage',
        )
        assert_urls_equal(res.location, expected_url)

    def test_api_download_file_redirect(self):
        url = '/api/v1/project/{0}/osffiles/{1}/'.format(
            self.project._id, self.path)
        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.status_code, 301)
        expected_url = self.project.web_url_for(
            'addon_view_or_download_file',
            path=self.expected_path,
            action='download',
            provider='osfstorage',
        )
        assert_urls_equal(res.location, expected_url)

    def test_api_download_file_version_redirect(self):
        url = '/api/v1/project/{0}/osffiles/{1}/version/3/'.format(
            self.project._id,
            self.path,
        )
        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.status_code, 301)
        expected_url = self.project.web_url_for(
            'addon_view_or_download_file',
            version=3,
            path=self.expected_path,
            action='download',
            provider='osfstorage',
        )
        assert_urls_equal(res.location, expected_url)

    def test_no_provider_name(self):
        url = '/{0}/files/{1}'.format(
            self.project._id,
            self.path,
        )
        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.status_code, 301)
        expected_url = self.project.web_url_for(
            'addon_view_or_download_file',
            action='view',
            path=self.expected_path,
            provider='osfstorage',
        )
        assert_urls_equal(res.location, expected_url)

    def test_action_as_param(self):
        url = '/{}/osfstorage/files/{}/?action=download'.format(
            self.project._id,
            self.path,
        )
        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.status_code, 301)
        expected_url = self.project.web_url_for(
            'addon_view_or_download_file',
            path=self.expected_path,
            action='download',
            provider='osfstorage',
        )
        assert_urls_equal(res.location, expected_url)

    def test_other_addon_redirect(self):
        url = '/project/{0}/mycooladdon/files/{1}/'.format(
            self.project._id,
            self.path,
        )
        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.status_code, 301)
        expected_url = self.project.web_url_for(
            'addon_view_or_download_file',
            action='view',
            path=self.path,
            provider='mycooladdon',
        )
        assert_urls_equal(res.location, expected_url)

    def test_other_addon_redirect_download(self):
        url = '/project/{0}/mycooladdon/files/{1}/download/'.format(
            self.project._id,
            self.path,
        )
        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.status_code, 301)
        expected_url = self.project.web_url_for(
            'addon_view_or_download_file',
            path=self.path,
            action='download',
            provider='mycooladdon',
        )
        assert_urls_equal(res.location, expected_url)
Beispiel #41
0
 def test_after_fork_authenticator(self):
     fork = ProjectFactory()
     clone, message = self.node_settings.after_fork(self.project, fork,
                                                    self.project.creator)
     assert_equal(self.node_settings.user_settings, clone.user_settings)
Beispiel #42
0
 def test_after_fork_by_authorized_dropbox_user(self):
     fork = ProjectFactory()
     clone, message = self.node_settings.after_fork(
         node=self.project, fork=fork, user=self.user_settings.owner)
     assert_equal(clone.user_settings, self.user_settings)
Beispiel #43
0
class TestCallbacks(OsfTestCase):
    def setUp(self):

        super(TestCallbacks, self).setUp()

        self.user = AuthUserFactory()
        self.consolidated_auth = Auth(user=self.user)
        self.auth = ('test', self.user.api_keys[0]._primary_key)
        self.project = ProjectFactory(creator=self.user)

        self.non_authenticator = AuthUserFactory()
        self.project.add_contributor(
            contributor=self.non_authenticator,
            auth=Auth(self.project.creator),
        )

        self.project.add_addon('figshare', auth=self.consolidated_auth)
        self.project.creator.add_addon('figshare')
        self.node_settings = self.project.get_addon('figshare')
        self.user_settings = self.project.creator.get_addon('figshare')
        self.user_settings.oauth_access_token = 'legittoken'
        self.user_settings.oauth_access_token_secret = 'legittoken'
        self.user_settings.save()
        self.node_settings.user_settings = self.user_settings
        self.node_settings.figshare_id = '123456'
        self.node_settings.figshare_type = 'project'
        self.node_settings.figshare_title = 'singlefile'
        self.node_settings.save()

    def test_update_fields_project(self):
        num_logs = len(self.project.logs)
        # try updating fields
        newfields = {'type': 'project', 'id': '313131', 'name': 'A PROJECT'}
        self.node_settings.update_fields(newfields, self.project,
                                         Auth(self.project.creator))
        #check for updated
        assert_equals(self.node_settings.figshare_id, '313131')
        assert_equals(self.node_settings.figshare_type, 'project')
        assert_equals(self.node_settings.figshare_title, 'A PROJECT')
        # check for log added
        assert_equals(len(self.project.logs), num_logs + 1)

    def test_update_fields_fileset(self):
        num_logs = len(self.project.logs)
        # try updating fields
        newfields = {'type': 'fileset', 'id': '313131', 'name': 'A FILESET'}
        self.node_settings.update_fields(newfields, self.project,
                                         Auth(self.project.creator))
        #check for updated
        assert_equals(self.node_settings.figshare_id, '313131')
        assert_equals(self.node_settings.figshare_type, 'fileset')
        assert_equals(self.node_settings.figshare_title, 'A FILESET')
        # check for log added
        assert_equals(len(self.project.logs), num_logs + 1)

    def test_update_fields_some_missing(self):
        num_logs = len(self.project.logs)
        # try updating fields
        newfields = {'type': 'project', 'id': '313131', 'name': 'A PROJECT'}
        self.node_settings.update_fields(newfields, self.project,
                                         Auth(self.project.creator))
        #check for updated
        assert_equals(self.node_settings.figshare_id, '313131')
        assert_equals(self.node_settings.figshare_title, 'A PROJECT')
        # check for log added
        assert_equals(len(self.project.logs), num_logs + 1)

    def test_update_fields_invalid(self):
        num_logs = len(self.project.logs)
        # try updating fields
        newfields = {
            'adad': 131313,
            'i1513': '313131',
            'titladad': 'A PROJECT'
        }
        self.node_settings.update_fields(newfields, self.project,
                                         Auth(self.project.creator))
        #check for updated
        assert_equals(self.node_settings.figshare_id, '123456')
        assert_equals(self.node_settings.figshare_type, 'project')
        assert_equals(self.node_settings.figshare_title, 'singlefile')
        # check for log added
        assert_equals(len(self.project.logs), num_logs)

    def test_api_url_no_user(self):
        self.node_settings.user_settings = None
        self.node_settings.save()
        assert_equal(self.node_settings.api_url, figshare_settings.API_URL)

    def test_api_url(self):
        assert_equal(self.node_settings.api_url,
                     figshare_settings.API_OAUTH_URL)

    def test_before_register_linked_content(self):
        assert_false(
            self.node_settings.before_register(self.project,
                                               self.project.creator) is None)

    def test_before_register_no_linked_content(self):
        self.node_settings.figshare_id = None
        assert_true(
            self.node_settings.before_register(self.project,
                                               self.project.creator) is None)

    def test_before_remove_contributor_authenticator(self):
        message = self.node_settings.before_remove_contributor(
            self.project, self.project.creator)
        assert_true(message)

    def test_before_remove_contributor_not_authenticator(self):
        message = self.node_settings.before_remove_contributor(
            self.project, self.non_authenticator)
        assert_false(message)

    def test_after_remove_contributor_authenticator_not_self(self):
        auth = Auth(user=self.non_authenticator)
        msg = self.node_settings.after_remove_contributor(
            self.project, self.project.creator, auth)

        assert_in(self.project.project_or_component, msg)
        assert_equal(self.node_settings.user_settings, None)
        assert_in("You can re-authenticate", msg)

    def test_after_remove_contributor_authenticator_self(self):
        msg = self.node_settings.after_remove_contributor(
            self.project, self.project.creator, self.consolidated_auth)

        assert_in(self.project.title, msg)
        assert_equal(self.node_settings.user_settings, None)
        assert_not_in("You can re-authenticate", msg)

    def test_after_fork_authenticator(self):
        fork = ProjectFactory()
        clone, message = self.node_settings.after_fork(
            self.project,
            fork,
            self.project.creator,
        )
        assert_equal(
            self.node_settings.user_settings,
            clone.user_settings,
        )

    def test_after_fork_not_authenticator(self):
        fork = ProjectFactory()
        clone, message = self.node_settings.after_fork(
            self.project,
            fork,
            self.non_authenticator,
        )
        assert_equal(
            clone.user_settings,
            None,
        )

    def test_after_delete(self):
        self.project.remove_node(Auth(user=self.project.creator))
        # Ensure that changes to node settings have been saved
        self.node_settings.reload()
        assert_true(self.node_settings.user_settings is None)
        assert_true(self.node_settings.figshare_id is None)
        assert_true(self.node_settings.figshare_type is None)
        assert_true(self.node_settings.figshare_title is None)

    @mock.patch('website.archiver.tasks.archive.si')
    @mock.patch(
        'website.addons.figshare.model.AddonFigShareNodeSettings.archive_errors'
    )
    def test_does_not_get_copied_to_registrations(self, mock_errors,
                                                  mock_archive):
        registration = self.project.register_node(
            schema=None,
            auth=Auth(user=self.project.creator),
            template='Template1',
            data='hodor')
        assert_false(registration.has_addon('figshare'))
Beispiel #44
0
class TestDropboxNodeSettingsModel(OsfTestCase):
    def setUp(self):
        super(TestDropboxNodeSettingsModel, self).setUp()
        self.user = UserFactory()
        self.user.add_addon('dropbox')
        self.user.save()
        self.user_settings = self.user.get_addon('dropbox')
        self.project = ProjectFactory()
        self.node_settings = DropboxNodeSettingsFactory(
            user_settings=self.user_settings, owner=self.project)

    def test_complete_true(self):
        self.node_settings.user_settings.access_token = 'seems legit'

        assert_true(self.node_settings.has_auth)
        assert_true(self.node_settings.complete)

    def test_complete_false(self):
        self.node_settings.user_settings.access_token = 'seems legit'
        self.node_settings.folder = None

        assert_true(self.node_settings.has_auth)
        assert_false(self.node_settings.complete)

    def test_complete_auth_false(self):
        self.node_settings.user_settings = None

        assert_false(self.node_settings.has_auth)
        assert_false(self.node_settings.complete)

    def test_fields(self):
        node_settings = DropboxNodeSettings(user_settings=self.user_settings)
        node_settings.save()
        assert_true(node_settings.user_settings)
        assert_equal(node_settings.user_settings.owner, self.user)
        assert_true(hasattr(node_settings, 'folder'))
        assert_true(hasattr(node_settings, 'registration_data'))

    def test_folder_defaults_to_none(self):
        node_settings = DropboxNodeSettings(user_settings=self.user_settings)
        node_settings.save()
        assert_is_none(node_settings.folder)

    def test_has_auth(self):
        settings = DropboxNodeSettings(user_settings=self.user_settings)
        settings.save()
        assert_false(settings.has_auth)

        settings.user_settings.access_token = '123abc'
        settings.user_settings.save()
        assert_true(settings.has_auth)

    def test_to_json(self):
        settings = self.node_settings
        user = UserFactory()
        result = settings.to_json(user)
        assert_equal(result['addon_short_name'], 'dropbox')

    def test_delete(self):
        assert_true(self.node_settings.user_settings)
        assert_true(self.node_settings.folder)
        old_logs = self.project.logs
        self.node_settings.delete()
        self.node_settings.save()
        assert_is(self.node_settings.user_settings, None)
        assert_is(self.node_settings.folder, None)
        assert_true(self.node_settings.deleted)
        assert_equal(self.project.logs, old_logs)

    def test_deauthorize(self):
        assert_true(self.node_settings.user_settings)
        assert_true(self.node_settings.folder)
        self.node_settings.deauthorize(auth=Auth(self.user))
        self.node_settings.save()
        assert_is(self.node_settings.user_settings, None)
        assert_is(self.node_settings.folder, None)

        last_log = self.project.logs[-1]
        assert_equal(last_log.action, 'dropbox_node_deauthorized')
        params = last_log.params
        assert_in('node', params)
        assert_in('project', params)
        assert_in('folder', params)

    def test_set_folder(self):
        folder_name = 'queen/freddie'
        self.node_settings.set_folder(folder_name, auth=Auth(self.user))
        self.node_settings.save()
        # Folder was set
        assert_equal(self.node_settings.folder, folder_name)
        # Log was saved
        last_log = self.project.logs[-1]
        assert_equal(last_log.action, 'dropbox_folder_selected')

    def test_set_user_auth(self):
        node_settings = DropboxNodeSettingsFactory()
        user_settings = DropboxUserSettingsFactory()

        node_settings.set_user_auth(user_settings)
        node_settings.save()

        assert_true(node_settings.has_auth)
        assert_equal(node_settings.user_settings, user_settings)
        # A log was saved
        last_log = node_settings.owner.logs[-1]
        assert_equal(last_log.action, 'dropbox_node_authorized')
        log_params = last_log.params
        assert_equal(log_params['folder'], node_settings.folder)
        assert_equal(log_params['node'], node_settings.owner._primary_key)
        assert_equal(last_log.user, user_settings.owner)

    def test_serialize_credentials(self):
        self.user_settings.access_token = 'secret'
        self.user_settings.save()
        credentials = self.node_settings.serialize_waterbutler_credentials()
        expected = {'token': self.node_settings.user_settings.access_token}
        assert_equal(credentials, expected)

    def test_serialize_credentials_not_authorized(self):
        self.node_settings.user_settings = None
        self.node_settings.save()
        with assert_raises(exceptions.AddonError):
            self.node_settings.serialize_waterbutler_credentials()

    def test_serialize_settings(self):
        settings = self.node_settings.serialize_waterbutler_settings()
        expected = {'folder': self.node_settings.folder}
        assert_equal(settings, expected)

    def test_serialize_settings_not_configured(self):
        self.node_settings.folder = None
        self.node_settings.save()
        with assert_raises(exceptions.AddonError):
            self.node_settings.serialize_waterbutler_settings()

    def test_create_log(self):
        action = 'file_added'
        path = 'pizza.nii'
        self.node_settings.folder = '/SomeOddPath'
        self.node_settings.save()
        nlog = len(self.project.logs)
        self.node_settings.create_waterbutler_log(
            auth=Auth(user=self.user),
            action=action,
            metadata={'path': path},
        )
        self.project.reload()
        assert_equal(len(self.project.logs), nlog + 1)
        assert_equal(
            self.project.logs[-1].action,
            'dropbox_{0}'.format(action),
        )
        assert_equal(
            self.project.logs[-1].params['path'],
            path,
        )

    @mock.patch('website.archiver.tasks.archive')
    def test_does_not_get_copied_to_registrations(self, mock_archive):
        registration = self.project.register_node(
            schema=None,
            auth=Auth(user=self.project.creator),
            template='Template1',
            data='hodor')
        assert_false(registration.has_addon('dropbox'))
Beispiel #45
0
class TestGoogleDriveUserSettings(OsfTestCase):
    def setUp(self):
        super(TestGoogleDriveUserSettings, self).setUp()
        self.node = ProjectFactory()
        self.user = self.node.creator

        self.external_account = GoogleDriveAccountFactory()

        self.user.external_accounts.append(self.external_account)
        self.user.save()

        self.user_settings = self.user.get_or_add_addon('googledrive')

    def tearDown(self):
        super(TestGoogleDriveUserSettings, self).tearDown()
        self.user_settings.remove()
        self.external_account.remove()
        self.node.remove()
        self.user.remove()

    def test_grant_oauth_access_no_metadata(self):
        self.user_settings.grant_oauth_access(
            node=self.node,
            external_account=self.external_account,
        )
        self.user_settings.save()

        assert_equal(
            self.user_settings.oauth_grants,
            {self.node._id: {
                self.external_account._id: {}
            }},
        )

    def test_grant_oauth_access_metadata(self):
        self.user_settings.grant_oauth_access(
            node=self.node,
            external_account=self.external_account,
            metadata={'folder': 'fake_folder_id'})
        self.user_settings.save()

        assert_equal(
            self.user_settings.oauth_grants, {
                self.node._id: {
                    self.external_account._id: {
                        'folder': 'fake_folder_id'
                    }
                },
            })

    def test_verify_oauth_access_no_metadata(self):
        self.user_settings.grant_oauth_access(
            node=self.node,
            external_account=self.external_account,
        )
        self.user_settings.save()

        account_has_access = self.user_settings.verify_oauth_access(
            node=self.node, external_account=self.external_account)

        factory_account_has_access = self.user_settings.verify_oauth_access(
            node=self.node, external_account=GoogleDriveAccountFactory())

        assert_true(account_has_access)
        assert_false(factory_account_has_access)

    def test_verify_oauth_access_metadata(self):
        self.user_settings.grant_oauth_access(
            node=self.node,
            external_account=self.external_account,
            metadata={'folder': 'fake_folder_id'})
        self.user_settings.save()

        correct_meta_access = self.user_settings.verify_oauth_access(
            node=self.node,
            external_account=self.external_account,
            metadata={'folder': 'fake_folder_id'})

        incorrect_meta_no_access = self.user_settings.verify_oauth_access(
            node=self.node,
            external_account=self.external_account,
            metadata={'folder': 'another_folder_id'})

        assert_true(correct_meta_access)
        assert_false(incorrect_meta_no_access)
Beispiel #46
0
 def setUp(self):
     super(OsfTestCase, self).setUp()
     self.user = UserFactory()
     self.project = ProjectFactory(creator=self.user)
     self.project.add_addon('s3', auth=Auth(self.user))
     self.node_addon = self.project.get_addon('s3')
Beispiel #47
0
class MendeleyViewsTestCase(OsfTestCase):

    def setUp(self):
        super(MendeleyViewsTestCase, self).setUp()
        self.account = MendeleyAccountFactory()
        self.user = AuthUserFactory(external_accounts=[self.account])
        self.account.display_name = self.user.fullname
        self.account.save()
        self.user_addon = MendeleyUserSettingsFactory(owner=self.user, external_account=self.account)
        self.project = ProjectFactory(creator=self.user)
        self.node_addon = MendeleyNodeSettingsFactory(owner=self.project)
        self.node_addon.set_auth(external_account=self.account, user=self.user)
        #self.user_addon.grant_oauth_access(self.node_addon, self.account, metadata={'lists': 'list'})
        self.node = MockNode()
        self.node.addon = self.node_addon
        self.id_patcher = mock.patch('website.addons.mendeley.model.Mendeley.client_id')
        self.secret_patcher = mock.patch('website.addons.mendeley.model.Mendeley.client_secret')
        self.id_patcher.__get__ = mock.Mock(return_value='1234567890asdf')
        self.secret_patcher.__get__ = mock.Mock(return_value='1234567890asdf')
        self.id_patcher.start()
        self.secret_patcher.start()

    def tearDown(self):
        self.id_patcher.stop()
        self.secret_patcher.stop()

    def test_serialize_settings_authorizer(self):
        #"""dict: a serialized version of user-specific addon settings"""
        res = self.app.get(
            self.project.api_url_for('mendeley_get_config'),
            auth=self.user.auth,
        )
        result = res.json['result']
        assert_true(result['nodeHasAuth'])
        assert_true(result['userHasAuth'])
        assert_true(result['userIsOwner'])
        assert_equal(result['folder'], {'name': ''})
        assert_equal(result['ownerName'], self.user.fullname)
        assert_true(result['urls']['auth'])
        assert_true(result['urls']['config'])
        assert_true(result['urls']['deauthorize'])
        assert_true(result['urls']['folders'])
        assert_true(result['urls']['importAuth'])
        assert_true(result['urls']['settings'])

    def test_serialize_settings_non_authorizer(self):
        #"""dict: a serialized version of user-specific addon settings"""
        non_authorizing_user = AuthUserFactory()
        self.project.add_contributor(non_authorizing_user, save=True)
        res = self.app.get(
            self.project.api_url_for('mendeley_get_config'),
            auth=non_authorizing_user.auth,
        )
        result = res.json['result']
        assert_true(result['nodeHasAuth'])
        assert_false(result['userHasAuth'])
        assert_false(result['userIsOwner'])
        assert_equal(result['folder'], {'name': ''})
        assert_equal(result['ownerName'], self.user.fullname)
        assert_true(result['urls']['auth'])
        assert_true(result['urls']['config'])
        assert_true(result['urls']['deauthorize'])
        assert_true(result['urls']['folders'])
        assert_true(result['urls']['importAuth'])
        assert_true(result['urls']['settings'])

    def test_set_auth(self):

        res = self.app.put_json(
            self.project.api_url_for('mendeley_add_user_auth'),
            {
                'external_account_id': self.account._id,
            },
            auth=self.user.auth,
        )

        assert_equal(
            res.status_code,
            200
        )

        assert_true(res.json['result']['userHasAuth'])

        assert_equal(
            self.node_addon.user_settings,
            self.user_addon
        )
        assert_equal(
            self.node_addon.external_account,
            self.account
        )

    def test_remove_user_auth(self):
        self.node_addon.set_auth(self.account, self.user)

        res = self.app.delete_json(
            self.project.api_url_for('mendeley_remove_user_auth'),
            {
                'external_account_id': self.account._id,
            },
            auth=self.user.auth,
        )

        assert_equal(
            res.status_code,
            200
        )

        self.node_addon.reload()

        assert_is_none(self.node_addon.user_settings)
        assert_is_none(self.node_addon.external_account)

    @mock.patch('website.addons.mendeley.model.Mendeley._folder_metadata')
    def test_set_config_owner(self, mock_metadata):
        mock_metadata.return_value = MockFolder(name='Fake Folder')
        # Settings config updates node settings
        self.node_addon.associated_user_settings = []
        self.node_addon.save()
        res = self.app.put_json(
            self.project.api_url_for('mendeley_set_config'),
            {
                'external_account_id': self.account._id,
                'external_list_id': 'list',
            },
            auth=self.user.auth,
        )
        self.node_addon.reload()
        assert_equal(self.user_addon, self.node_addon.user_settings)
        serializer = MendeleySerializer(node_settings=self.node_addon, user_settings=self.user_addon)
        expected = {
            'result': serializer.serialized_node_settings
        }
        assert_equal(res.json, expected)

    @mock.patch('website.addons.mendeley.model.Mendeley._folder_metadata')
    def test_set_config_not_owner(self, mock_metadata):
        mock_metadata.return_value = MockFolder(name='Fake Folder')
        user = AuthUserFactory()
        user.add_addon('mendeley')
        self.project.add_contributor(user)
        self.project.save()
        res = self.app.put_json(
            self.project.api_url_for('mendeley_set_config'),
            {
                'external_account_id': self.account._id,
                'external_list_id': 'list',
            },
            auth=user.auth,
        )
        self.node_addon.reload()
        assert_equal(self.user_addon, self.node_addon.user_settings)
        serializer = MendeleySerializer(node_settings=self.node_addon, user_settings=None)
        expected = {
            'result': serializer.serialized_node_settings
        }
        assert_equal(res.json, expected)

    def test_mendeley_widget_view_complete(self):
        # JSON: everything a widget needs
        assert_false(self.node_addon.complete)
        assert_equal(self.node_addon.mendeley_list_id, None)
        self.node_addon.set_target_folder('ROOT-ID', 'ROOT', auth=Auth(user=self.user))
        url = self.project.api_url_for('mendeley_widget')
        res = self.app.get(url, auth=self.user.auth).json

        assert_true(res['complete'])
        assert_equal(res['list_id'], 'ROOT-ID')

    def test_widget_view_incomplete(self):
        # JSON: tell the widget when it hasn't been configured
        assert_false(self.node_addon.complete)
        assert_equal(self.node_addon.mendeley_list_id, None)
        url = self.project.api_url_for('mendeley_widget')
        res = self.app.get(url, auth=self.user.auth).json

        assert_false(res['complete'])
        assert_is_none(res['list_id'])

    @httpretty.activate
    def test_mendeley_citation_list_root(self):

        httpretty.register_uri(
            httpretty.GET,
            urlparse.urljoin(API_URL, 'folders'),
            body=mock_responses['folders'],
            content_type='application/json'
        )

        res = self.app.get(
            self.project.api_url_for('mendeley_citation_list'),
            auth=self.user.auth
        )
        root = res.json['contents'][0]
        assert_equal(root['kind'], 'folder')
        assert_equal(root['id'], 'ROOT')
        assert_equal(root['parent_list_id'], '__')

    @httpretty.activate
    def test_mendeley_citation_list_non_root(self):

        httpretty.register_uri(
            httpretty.GET,
            urlparse.urljoin(API_URL, 'folders'),
            body=mock_responses['folders'],
            content_type='application/json'
        )

        httpretty.register_uri(
            httpretty.GET,
            urlparse.urljoin(API_URL, 'documents'),
            body=mock_responses['documents'],
            content_type='application/json'
        )

        res = self.app.get(
            self.project.api_url_for('mendeley_citation_list', mendeley_list_id='ROOT'),
            auth=self.user.auth
        )

        children = res.json['contents']
        assert_equal(len(children), 7)
        assert_equal(children[0]['kind'], 'folder')
        assert_equal(children[1]['kind'], 'file')
        assert_true(children[1].get('csl') is not None)

    @httpretty.activate
    def test_mendeley_citation_list_non_linked_or_child_non_authorizer(self):

        non_authorizing_user = AuthUserFactory()
        self.project.add_contributor(non_authorizing_user, save=True)

        self.node_addon.mendeley_list_id = 'e843da05-8818-47c2-8c37-41eebfc4fe3f'
        self.node_addon.save()

        httpretty.register_uri(
            httpretty.GET,
            urlparse.urljoin(API_URL, 'folders'),
            body=mock_responses['folders'],
            content_type='application/json'
        )

        httpretty.register_uri(
            httpretty.GET,
            urlparse.urljoin(API_URL, 'documents'),
            body=mock_responses['documents'],
            content_type='application/json'
        )

        res = self.app.get(
            self.project.api_url_for('mendeley_citation_list', mendeley_list_id='ROOT'),
            auth=non_authorizing_user.auth,
            expect_errors=True
        )
        assert_equal(res.status_code, 403)
Beispiel #48
0
class TestFileGuid(OsfTestCase):
    def setUp(self):
        super(OsfTestCase, self).setUp()
        self.user = AuthUserFactory()
        self.project = ProjectFactory(creator=self.user)
        self.project.add_addon('figshare', auth=Auth(self.user))
        self.node_addon = self.project.get_addon('figshare')
        self.node_addon.figshare_id = 8
        self.node_addon.figshare_type = 'project'
        self.node_addon.save()

    def test_provider(self):
        assert_equal('figshare', model.FigShareGuidFile().provider)

    def test_path_doesnt_crash_without_addon(self):
        guid = model.FigShareGuidFile(node=self.project, path='/baz/foo/bar')
        self.project.delete_addon('figshare', Auth(self.user))

        assert_is(self.project.get_addon('figshare'), None)

        assert_true(guid.path)
        assert_true(guid.waterbutler_path)

    def test_path_doesnt_crash_nonconfig_addon(self):
        guid = model.FigShareGuidFile(node=self.project, path='/baz/foo/bar')
        self.node_addon.figshare_type = None
        self.node_addon.figshare_id = None
        self.node_addon.save()
        self.node_addon.reload()

        assert_true(guid.path)
        assert_true(guid.waterbutler_path)

    def test_mfr_test_path(self):
        self.node_addon.figshare_type = 'fileset'
        self.node_addon.save()
        self.node_addon.reload()

        guid = model.FigShareGuidFile(file_id=2,
                                      article_id=4,
                                      node=self.project)
        assert_equal(guid.waterbutler_path, '/2')

    def test_correct_path_project(self):
        guid = model.FigShareGuidFile(file_id=2,
                                      article_id=4,
                                      node=self.project)
        assert_equal(guid.waterbutler_path, '/4/2')

    def test_unique_identifier(self):
        guid = model.FigShareGuidFile(file_id=2, article_id=4)
        assert_equal(guid.unique_identifier, '42')

    def test_exception_from_response(self):
        mock_response = mock.Mock()
        mock_response.json.return_value = {
            'data': {
                'name': 'Morty',
                'extra': {
                    'status': 'drafts'
                }
            }
        }
        guid = model.FigShareGuidFile(file_id=2, article_id=4)

        with assert_raises(exceptions.FigshareIsDraftError):
            guid._exception_from_response(mock_response)

        assert_equal(guid.name, 'Morty')

    @mock.patch('website.addons.base.requests.get')
    def test_enrich_raises(self, mock_get):
        mock_response = mock.Mock(ok=True, status_code=200)
        mock_get.return_value = mock_response
        mock_response.json.return_value = {
            'data': {
                'name': 'Morty',
                'extra': {
                    'status': 'drafts'
                }
            }
        }

        guid = model.FigShareGuidFile(file_id=2,
                                      article_id=4,
                                      node=self.project)

        with assert_raises(exceptions.FigshareIsDraftError):
            guid.enrich()

        assert_equal(guid.name, 'Morty')

    @mock.patch('website.addons.base.requests.get')
    def test_enrich_works(self, mock_get):
        mock_response = mock.Mock(ok=True, status_code=200)
        mock_get.return_value = mock_response
        mock_response.json.return_value = {
            'data': {
                'name': 'Morty',
                'extra': {
                    'status': 'Rick'
                }
            }
        }

        guid = model.FigShareGuidFile(file_id=2,
                                      article_id=4,
                                      node=self.project)

        guid.enrich()

        assert_equal(guid.name, 'Morty')

    def test_node_addon_get_or_create(self):
        guid, _ = self.node_addon.find_or_create_file_guid('/4/2')
        assert_equal(guid.waterbutler_path, '/4/2')
        assert_equal(guid.file_id, '2')
        assert_equal(guid.article_id, '4')

    def test_node_addon_get_or_create_finds(self):
        guid, created = self.node_addon.find_or_create_file_guid('/4/2')
        assert_true(created)

        other, other_created = self.node_addon.find_or_create_file_guid('/4/2')
        assert_false(other_created)
        assert_equal(guid, other)
Beispiel #49
0
class TestRemoveContributor(AdminTestCase):
    def setUp(self):
        super(TestRemoveContributor, self).setUp()
        self.user = AuthUserFactory()
        self.node = ProjectFactory(creator=self.user)
        self.user_2 = AuthUserFactory()
        self.node.add_contributor(self.user_2)
        self.node.save()
        self.view = NodeRemoveContributorView
        self.request = RequestFactory().post('/fake_path')
        self.url = reverse('nodes:remove_user',
                           kwargs={
                               'node_id': self.node._id,
                               'user_id': self.user._id
                           })

    def test_get_object(self):
        view = setup_log_view(self.view(),
                              self.request,
                              node_id=self.node._id,
                              user_id=self.user._id)
        node, user = view.get_object()
        nt.assert_is_instance(node, Node)
        nt.assert_is_instance(user, OSFUser)

    @mock.patch('admin.nodes.views.Node.remove_contributor')
    def test_remove_contributor(self, mock_remove_contributor):
        user_id = self.user_2._id
        node_id = self.node._id
        view = setup_log_view(self.view(),
                              self.request,
                              node_id=node_id,
                              user_id=user_id)
        view.delete(self.request)
        mock_remove_contributor.assert_called_with(self.user_2,
                                                   None,
                                                   log=False)

    def test_integration_remove_contributor(self):
        nt.assert_in(self.user_2, self.node.contributors)
        view = setup_log_view(self.view(),
                              self.request,
                              node_id=self.node._id,
                              user_id=self.user_2._id)
        count = AdminLogEntry.objects.count()
        view.delete(self.request)
        nt.assert_not_in(self.user_2, self.node.contributors)
        nt.assert_equal(AdminLogEntry.objects.count(), count + 1)

    def test_do_not_remove_last_admin(self):
        nt.assert_equal(
            len(list(self.node.get_admin_contributors(
                self.node.contributors))), 1)
        view = setup_log_view(self.view(),
                              self.request,
                              node_id=self.node._id,
                              user_id=self.user._id)
        count = AdminLogEntry.objects.count()
        view.delete(self.request)
        self.node.reload()  # Reloads instance to show that nothing was removed
        nt.assert_equal(len(list(self.node.contributors)), 2)
        nt.assert_equal(
            len(list(self.node.get_admin_contributors(
                self.node.contributors))), 1)
        nt.assert_equal(AdminLogEntry.objects.count(), count)

    def test_no_log(self):
        view = setup_log_view(self.view(),
                              self.request,
                              node_id=self.node._id,
                              user_id=self.user_2._id)
        view.delete(self.request)
        nt.assert_not_equal(self.node.logs.latest().action,
                            NodeLog.CONTRIB_REMOVED)

    def test_no_user_permissions_raises_error(self):
        guid = self.node._id
        request = RequestFactory().get(self.url)
        request.user = self.user

        with nt.assert_raises(PermissionDenied):
            self.view.as_view()(request, node_id=guid, user_id=self.user)

    def test_correct_view_permissions(self):
        change_permission = Permission.objects.get(codename='change_node')
        view_permission = Permission.objects.get(codename='view_node')
        self.user.user_permissions.add(change_permission)
        self.user.user_permissions.add(view_permission)
        self.user.save()

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

        response = self.view.as_view()(request,
                                       node_id=self.node._id,
                                       user_id=self.user._id)
        nt.assert_equal(response.status_code, 200)
Beispiel #50
0
class TestGoogleDriveNodeSettings(OsfTestCase):
    def setUp(self):
        super(TestGoogleDriveNodeSettings, self).setUp()
        self.node = ProjectFactory()
        self.node_settings = model.GoogleDriveNodeSettings(owner=self.node)
        self.node_settings.save()
        self.user = self.node.creator
        self.user_settings = self.user.get_or_add_addon('googledrive')

    def tearDown(self):
        super(TestGoogleDriveNodeSettings, self).tearDown()
        self.user_settings.remove()
        self.node_settings.remove()
        self.node.remove()
        self.user.remove()

    @mock.patch('website.addons.googledrive.model.GoogleDriveProvider')
    def test_api_not_cached(self, mock_gdp):
        # The first call to .api returns a new object
        api = self.node_settings.api
        mock_gdp.assert_called_once()
        assert_equal(api, mock_gdp())

    @mock.patch('website.addons.googledrive.model.GoogleDriveProvider')
    def test_api_cached(self, mock_gdp):
        # Repeated calls to .api returns the same object
        self.node_settings._api = 'testapi'
        api = self.node_settings.api
        assert_false(mock_gdp.called)
        assert_equal(api, 'testapi')

    def test_set_auth(self):
        external_account = GoogleDriveAccountFactory()
        self.user.external_accounts.append(external_account)
        self.user.save()

        # this should be reset after the call
        self.node_settings.folder_id = 'anything'

        self.node_settings.set_auth(external_account=external_account,
                                    user=self.user)

        # this instance is updated
        assert_equal(self.node_settings.external_account, external_account)
        assert_equal(self.node_settings.user_settings, self.user_settings)
        assert_is_none(self.node_settings.folder_id)

        set_auth_gives_access = self.user_settings.verify_oauth_access(
            node=self.node,
            external_account=external_account,
        )

        assert_true(set_auth_gives_access)

    def test_set_auth_wrong_user(self):
        external_account = GoogleDriveAccountFactory()
        self.user.external_accounts.append(external_account)
        self.user.save()

        with assert_raises(PermissionsError):
            self.node_settings.set_auth(external_account=external_account,
                                        user=UserFactory())

    def test_clear_auth(self):
        self.node_settings.external_account = GoogleDriveAccountFactory()
        self.node_settings.folder_id = 'something'
        self.node_settings.user_settings = self.user_settings
        self.node_settings.save()

        self.node_settings.clear_auth()

        assert_is_none(self.node_settings.external_account)
        assert_is_none(self.node_settings.folder_id)
        assert_is_none(self.node_settings.user_settings)
        assert_is_none(self.node_settings.folder_path)
        assert_is_none(self.node_settings.folder_name)

    def test_set_target_folder(self):

        folder = {
            'id': 'fake-folder-id',
            'name': 'fake-folder-name',
            'path': 'fake_path'
        }

        external_account = GoogleDriveAccountFactory()
        self.user.external_accounts.append(external_account)
        self.user.save()

        self.node_settings.set_auth(
            external_account=external_account,
            user=self.user,
        )

        assert_is_none(self.node_settings.folder_id)

        self.node_settings.set_target_folder(
            folder,
            auth=Auth(user=self.user),
        )

        # instance was updated
        assert_equal(
            self.node_settings.folder_id,
            'fake-folder-id',
        )

        has_access = self.user_settings.verify_oauth_access(
            node=self.node,
            external_account=external_account,
            metadata={'folder': 'fake-folder-id'})

        # user_settings was updated
        assert_true(has_access)

        log = self.node.logs[-1]
        assert_equal(log.action, 'googledrive_folder_selected')
        assert_equal(log.params['folder'], folder['path'])

    def test_has_auth_false(self):
        external_account = GoogleDriveAccountFactory()

        assert_false(self.node_settings.has_auth)

        # both external_account and user_settings must be set to have auth
        self.node_settings.external_account = external_account
        assert_false(self.node_settings.has_auth)

        self.node_settings.external_account = None
        self.node_settings.user_settings = self.user_settings
        assert_false(self.node_settings.has_auth)

        # set_auth must be called to have auth
        self.node_settings.external_account = external_account
        self.node_settings.user_settings = self.user_settings
        assert_false(self.node_settings.has_auth)

    def test_has_auth_true(self):
        external_account = GoogleDriveAccountFactory()
        self.user.external_accounts.append(external_account)

        self.node_settings.set_auth(external_account, self.user)

        self.node_settings.folder_id = None
        assert_true(self.node_settings.has_auth)

        self.node_settings.folder_id = 'totally fake ID'
        assert_true(self.node_settings.has_auth)

    def test_selected_folder_name_root(self):
        self.node_settings.folder_id = 'root'

        assert_equal(self.node_settings.selected_folder_name,
                     "Full Google Drive")

    def test_selected_folder_name_empty(self):
        self.node_settings.folder_id = None

        assert_equal(self.node_settings.selected_folder_name, '')

    def test_selected_folder_name(self):
        self.node_settings.folder_id = 'fake-id'
        self.node_settings.folder_path = 'fake-folder-name'
        self.node_settings.save()
        assert_equal(self.node_settings.selected_folder_name,
                     'fake-folder-name')

    def test_serialize_credentials(self):
        external_account = GoogleDriveAccountFactory()
        self.user.external_accounts.append(external_account)
        self.node_settings.set_auth(external_account, self.user)
        credentials = self.node_settings.serialize_waterbutler_credentials()
        expected = {'token': self.node_settings.fetch_access_token()}
        assert_equal(credentials, expected)

    def test_serialize_credentials_not_authorized(self):
        external_account = GoogleDriveAccountFactory()
        self.node_settings.external_account = external_account
        with assert_raises(exceptions.AddonError):
            self.node_settings.serialize_waterbutler_credentials()

    def test_serialize_settings(self):
        self.node_settings.folder_id = 'fake-id'
        self.node_settings.folder_path = 'fake-folder-name'
        self.node_settings.save()

        settings = self.node_settings.serialize_waterbutler_settings()

        expected = {
            'folder': {
                'id': 'fake-id',
                'name': 'fake-folder-name',
                'path': 'fake-folder-name',
            }
        }

        assert_equal(settings, expected)

    def test_serialize_settings_not_configured(self):
        self.node_settings.folder_id = None
        self.node_settings.save()

        with assert_raises(exceptions.AddonError):
            self.node_settings.serialize_waterbutler_settings()

    def test_fetch_access_token_with_token_not_expired(self):
        external_account = GoogleDriveAccountFactory()
        self.user.external_accounts.append(external_account)
        external_account.expires_at = datetime.utcnow(
        ) + relativedelta.relativedelta(minutes=6)
        external_account.oauth_key = 'fake-token'
        external_account.save()
        self.node_settings.set_auth(external_account, self.user)
        assert_equal(self.node_settings.fetch_access_token(), 'fake-token')

    @mock.patch.object(GoogleAuthClient, 'refresh')
    def test_fetch_access_token_with_token_expired(self, mock_refresh):
        external_account = GoogleDriveAccountFactory()
        self.user.external_accounts.append(external_account)
        external_account.expires_at = datetime.utcnow(
        ) + relativedelta.relativedelta(minutes=4)
        external_account.oauth_key = 'fake-token'
        external_account.refresh_token = 'refresh-fake-token'
        external_account.save()

        fake_token = {
            'access_token': 'new-access-token',
            'refresh_token': 'new-refresh-token',
            'expires_at': 1234.5
        }
        mock_refresh.return_value = fake_token
        self.node_settings.set_auth(external_account, self.user)
        self.node_settings.fetch_access_token()
        mock_refresh.assert_called_once()
        assert_equal(external_account.oauth_key, 'new-access-token')
        assert_equal(external_account.refresh_token, 'new-refresh-token')
        assert_equal(external_account.expires_at,
                     datetime.utcfromtimestamp(1234.5))
Beispiel #51
0
class TestOsfStorageCheckout(StorageTestCase):
    def setUp(self):
        super(TestOsfStorageCheckout, self).setUp()
        self.user = factories.AuthUserFactory()
        self.node = ProjectFactory(creator=self.user)
        self.osfstorage = self.node.get_addon('osfstorage')
        self.root_node = self.osfstorage.get_root()
        self.file = self.root_node.append_file('3005')

    def test_checkout_logs(self):
        non_admin = factories.AuthUserFactory()
        self.node.add_contributor(non_admin, permissions=['read', 'write'])
        self.node.save()
        self.file.check_in_or_out(non_admin, non_admin, save=True)
        self.file.reload()
        self.node.reload()
        assert_equal(self.file.checkout, non_admin)
        assert_equal(self.node.logs.latest().action, 'checked_out')
        assert_equal(self.node.logs.latest().user, non_admin)

        self.file.check_in_or_out(self.user, None, save=True)
        self.file.reload()
        self.node.reload()
        assert_equal(self.file.checkout, None)
        assert_equal(self.node.logs.latest().action, 'checked_in')
        assert_equal(self.node.logs.latest().user, self.user)

        self.file.check_in_or_out(self.user, self.user, save=True)
        self.file.reload()
        self.node.reload()
        assert_equal(self.file.checkout, self.user)
        assert_equal(self.node.logs.latest().action, 'checked_out')
        assert_equal(self.node.logs.latest().user, self.user)

        with assert_raises(FileNodeCheckedOutError):
            self.file.check_in_or_out(non_admin, None, save=True)

        with assert_raises(FileNodeCheckedOutError):
            self.file.check_in_or_out(non_admin, non_admin, save=True)

    def test_delete_checked_out_file(self):
        self.file.check_in_or_out(self.user, self.user, save=True)
        self.file.reload()
        assert_equal(self.file.checkout, self.user)
        with assert_raises(FileNodeCheckedOutError):
            self.file.delete()

    def test_delete_folder_with_checked_out_file(self):
        folder = self.root_node.append_folder('folder')
        self.file.move_under(folder)
        self.file.check_in_or_out(self.user, self.user, save=True)
        self.file.reload()
        assert_equal(self.file.checkout, self.user)
        with assert_raises(FileNodeCheckedOutError):
            folder.delete()

    def test_move_checked_out_file(self):
        self.file.check_in_or_out(self.user, self.user, save=True)
        self.file.reload()
        assert_equal(self.file.checkout, self.user)
        folder = self.root_node.append_folder('folder')
        with assert_raises(FileNodeCheckedOutError):
            self.file.move_under(folder)

    def test_checked_out_merge(self):
        user = factories.AuthUserFactory()
        node = ProjectFactory(creator=user)
        osfstorage = node.get_addon('osfstorage')
        root_node = osfstorage.get_root()
        file = root_node.append_file('test_file')
        user_merge_target = factories.AuthUserFactory()
        file.check_in_or_out(user, user, save=True)
        file.reload()
        assert_equal(file.checkout, user)
        user_merge_target.merge_user(user)
        file.reload()
        assert_equal(user_merge_target.id, file.checkout.id)

    def test_remove_contributor_with_checked_file(self):
        user = factories.AuthUserFactory()
        Contributor.objects.create(
            node=self.node,
            user=user,
            admin=True,
            write=True,
            read=True,
            visible=True
        )
        self.file.check_in_or_out(self.user, self.user, save=True)
        self.file.reload()
        assert_equal(self.file.checkout, self.user)
        self.file.node.remove_contributors([self.user], save=True)
        self.file.reload()
        assert_equal(self.file.checkout, None)
Beispiel #52
0
class TestNodeDeleteView(AdminTestCase):
    def setUp(self):
        super(TestNodeDeleteView, self).setUp()
        self.node = ProjectFactory()
        self.request = RequestFactory().post('/fake_path')
        self.plain_view = NodeDeleteView
        self.view = setup_log_view(self.plain_view(),
                                   self.request,
                                   guid=self.node._id)

        self.url = reverse('nodes:remove', kwargs={'guid': self.node._id})

    def test_get_object(self):
        obj = self.view.get_object()
        nt.assert_is_instance(obj, Node)

    def test_get_context(self):
        res = self.view.get_context_data(object=self.node)
        nt.assert_in('guid', res)
        nt.assert_equal(res.get('guid'), self.node._id)

    def test_remove_node(self):
        count = AdminLogEntry.objects.count()
        self.view.delete(self.request)
        self.node.refresh_from_db()
        nt.assert_true(self.node.is_deleted)
        nt.assert_equal(AdminLogEntry.objects.count(), count + 1)

    def test_restore_node(self):
        self.view.delete(self.request)
        self.node.refresh_from_db()
        nt.assert_true(self.node.is_deleted)
        count = AdminLogEntry.objects.count()
        self.view.delete(self.request)
        self.node.reload()
        nt.assert_false(self.node.is_deleted)
        nt.assert_equal(AdminLogEntry.objects.count(), count + 1)

    def test_no_user_permissions_raises_error(self):
        user = AuthUserFactory()
        guid = self.node._id
        request = RequestFactory().get(self.url)
        request.user = user

        with nt.assert_raises(PermissionDenied):
            self.plain_view.as_view()(request, guid=guid)

    def test_correct_view_permissions(self):
        user = AuthUserFactory()
        guid = self.node._id

        change_permission = Permission.objects.get(codename='delete_node')
        view_permission = Permission.objects.get(codename='view_node')
        user.user_permissions.add(change_permission)
        user.user_permissions.add(view_permission)
        user.save()

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

        response = self.plain_view.as_view()(request, guid=guid)
        nt.assert_equal(response.status_code, 200)
Beispiel #53
0
 def setUp(self):
     super(TestProject, self).setUp()
     search.delete_index(elastic_search.INDEX)
     search.create_index(elastic_search.INDEX)
     self.user = UserFactory(fullname='John Deacon')
     self.project = ProjectFactory(title='Red Special', creator=self.user)
Beispiel #54
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, public=True)
        self.public_project.add_contributor(self.other_user, permissions=[permissions.DEFAULT_CONTRIBUTOR_PERMISSIONS], save=True)
        self.subject = SubjectFactory()

        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.subject._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_with_tags(self):
        public_project_payload = build_preprint_create_payload(self.public_project._id, self.subject._id, self.file_one_public_project._id)
        public_project_payload['data']['attributes']['tags'] = ['newtag', 'bluetag']
        res = self.app.post_json_api(self.url, public_project_payload, auth=self.user.auth)

        assert_equal(res.status_code, 201)

        self.public_project.reload()
        assert_in('newtag', self.public_project.tags)
        assert_in('bluetag', self.public_project.tags)
        assert_not_in('tag_added', [l.action for l in self.public_project.logs])

    def test_create_preprint_from_private_project(self):
        private_project_payload = build_preprint_create_payload(self.private_project._id, self.subject._id, self.file_one_private_project._id)
        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.subject._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.subject._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.subject._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(self):
        preprint = PreprintFactory(creator=self.user)
        file_one_preprint = test_utils.create_test_file(preprint, self.user, 'openupthatwindow.pdf')

        already_preprint_payload = build_preprint_create_payload(preprint._id, self.subject._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_equal(res.json['errors'][0]['detail'], 'This node already stored as a preprint, use the update method instead.')

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

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

        already_preprint_payload = build_preprint_create_payload(preprint._id, self.subject._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.subject._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 primary_file to create a preprint.')

    def test_invalid_primary_file(self):
        invalid_file_payload = build_preprint_create_payload(self.public_project._id, self.subject._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 primary_file to create a preprint.')

    def test_no_subjects_given(self):
        no_subjects_payload = build_preprint_create_payload(self.public_project._id, self.subject._id, self.file_one_public_project._id)
        del no_subjects_payload['data']['attributes']['subjects']
        res = self.app.post_json_api(self.url, no_subjects_payload, auth=self.user.auth, expect_errors=True)

        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'], 'You must specify at least one subject to create a preprint.')

    def test_invalid_subjects_given(self):
        wrong_subjects_payload = build_preprint_create_payload(self.public_project._id, self.subject._id, self.file_one_public_project._id)
        wrong_subjects_payload['data']['attributes']['subjects'] = ['jobbers']

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

        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'], 'Subject with id <jobbers> could not be found.')

    def test_request_id_does_not_match_request_url_id(self):
        public_project_payload = build_preprint_create_payload(self.private_project._id, self.subject._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.provider = 'github'
        github_file.save()
        public_project_payload = build_preprint_create_payload(self.public_project._id, self.subject._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_sent_on_creation(self):
        with capture_signals() as mock_signals:
            public_project_payload = build_preprint_create_payload(self.public_project._id, self.subject._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_equal(mock_signals.signals_sent(), set([project_signals.contributor_added]))

    def test_preprint_contributor_signal_not_sent_one_contributor(self):
        with capture_signals() as mock_signals:
            private_project_payload = build_preprint_create_payload(self.private_project._id, self.subject._id,
                                                                   self.file_one_private_project._id)
            res = self.app.post_json_api(self.url, private_project_payload, auth=self.user.auth)
            assert_equal(res.status_code, 201)
            assert_not_equal(mock_signals.signals_sent(), set([project_signals.contributor_added]))
Beispiel #55
0
class TestAddonAuth(OsfTestCase):

    def setUp(self):
        super(TestAddonAuth, self).setUp()
        self.flask_app = SetEnvironMiddleware(self.app.app, REMOTE_ADDR='127.0.0.1')
        self.test_app = webtest.TestApp(self.flask_app)
        self.user = AuthUserFactory()
        self.auth_obj = Auth(user=self.user)
        self.node = ProjectFactory(creator=self.user)
        self.session = Session(data={'auth_user_id': self.user._id})
        self.session.save()
        self.cookie = itsdangerous.Signer(settings.SECRET_KEY).sign(self.session._id)
        self.configure_addon()

    def configure_addon(self):
        self.user.add_addon('github')
        self.user_addon = self.user.get_addon('github')
        self.oauth_settings = AddonGitHubOauthSettings(github_user_id='john')
        self.oauth_settings.save()
        self.user_addon.oauth_settings = self.oauth_settings
        self.user_addon.oauth_access_token = 'secret'
        self.user_addon.save()
        self.node.add_addon('github', self.auth_obj)
        self.node_addon = self.node.get_addon('github')
        self.node_addon.user = '******'
        self.node_addon.repo = 'youre-my-best-friend'
        self.node_addon.user_settings = self.user_addon
        self.node_addon.save()

    def build_url(self, **kwargs):
        options = dict(
            action='download',
            cookie=self.cookie,
            nid=self.node._id,
            provider=self.node_addon.config.short_name,
        )
        options.update(kwargs)
        return api_url_for('get_auth', **options)

    def test_auth_download(self):
        url = self.build_url()
        res = self.test_app.get(url)
        assert_equal(res.json['auth'], views.make_auth(self.user))
        assert_equal(res.json['credentials'], self.node_addon.serialize_waterbutler_credentials())
        assert_equal(res.json['settings'], self.node_addon.serialize_waterbutler_settings())
        expected_url = furl.furl(self.node.api_url_for('create_waterbutler_log', _absolute=True))
        observed_url = furl.furl(res.json['callback_url'])
        observed_url.port = expected_url.port
        assert_equal(expected_url, observed_url)

    def test_auth_missing_args(self):
        url = self.build_url(cookie=None)
        res = self.test_app.get(url, expect_errors=True)
        assert_equal(res.status_code, 401)

    def test_auth_bad_cookie(self):
        url = self.build_url(cookie=self.cookie[::-1])
        res = self.test_app.get(url, expect_errors=True)
        assert_equal(res.status_code, 401)

    def test_auth_missing_addon(self):
        url = self.build_url(provider='queenhub')
        res = self.test_app.get(url, expect_errors=True)
        assert_equal(res.status_code, 400)

    def test_auth_bad_ip(self):
        flask_app = SetEnvironMiddleware(self.app.app, REMOTE_ADDR='192.168.1.1')
        test_app = webtest.TestApp(flask_app)
        url = self.build_url()
        res = test_app.get(url, expect_errors=True)
        assert_equal(res.status_code, 403)
Beispiel #56
0
class TestPublicNodes(SearchTestCase):
    def setUp(self):
        super(TestPublicNodes, self).setUp()
        self.user = UserFactory(usename='Doug Bogie')
        self.title = 'Red Special'
        self.consolidate_auth = Auth(user=self.user)
        self.project = ProjectFactory(
            title=self.title,
            creator=self.user,
            is_public=True,
        )
        self.component = NodeFactory(project=self.project,
                                     title=self.title,
                                     creator=self.user,
                                     is_public=True)
        self.registration = ProjectFactory(title=self.title,
                                           creator=self.user,
                                           is_public=True,
                                           is_registration=True)

    def test_make_private(self):
        """Make project public, then private, and verify that it is not present
        in search.
        """
        self.project.set_privacy('private')
        docs = query('category:project AND ' + self.title)['results']
        assert_equal(len(docs), 0)

        self.component.set_privacy('private')
        docs = query('category:component AND ' + self.title)['results']
        assert_equal(len(docs), 0)

        self.registration.set_privacy('private')
        docs = query('category:registration AND ' + self.title)['results']
        assert_equal(len(docs), 0)

    def test_public_parent_title(self):
        self.project.set_title('hello &amp; world', self.consolidate_auth)
        self.project.save()
        docs = query('category:component AND ' + self.title)['results']
        assert_equal(len(docs), 1)
        assert_equal(docs[0]['parent_title'], 'hello & world')
        assert_true(docs[0]['parent_url'])

    def test_make_parent_private(self):
        """Make parent of component, public, then private, and verify that the
        component still appears but doesn't link to the parent in search.
        """
        self.project.set_privacy('private')
        docs = query('category:component AND ' + self.title)['results']
        assert_equal(len(docs), 1)
        assert_equal(docs[0]['parent_title'], '-- private project --')
        assert_false(docs[0]['parent_url'])

    def test_delete_project(self):
        """

        """
        self.component.remove_node(self.consolidate_auth)
        docs = query('category:component AND ' + self.title)['results']
        assert_equal(len(docs), 0)

        self.project.remove_node(self.consolidate_auth)
        docs = query('category:project AND ' + self.title)['results']
        assert_equal(len(docs), 0)

    def test_change_title(self):
        """

        """
        title_original = self.project.title
        self.project.set_title('Blue Ordinary',
                               self.consolidate_auth,
                               save=True)

        docs = query('category:project AND ' + title_original)['results']
        assert_equal(len(docs), 0)

        docs = query('category:project AND ' + self.project.title)['results']
        assert_equal(len(docs), 1)

    def test_add_tags(self):

        tags = ['stonecoldcrazy', 'just a poor boy', 'from-a-poor-family']

        for tag in tags:
            docs = query('tags:"{}"'.format(tag))['results']
            assert_equal(len(docs), 0)
            self.project.add_tag(tag, self.consolidate_auth, save=True)

        for tag in tags:
            docs = query('tags:"{}"'.format(tag))['results']
            assert_equal(len(docs), 1)

    def test_remove_tag(self):

        tags = ['stonecoldcrazy', 'just a poor boy', 'from-a-poor-family']

        for tag in tags:
            self.project.add_tag(tag, self.consolidate_auth, save=True)
            self.project.remove_tag(tag, self.consolidate_auth, save=True)
            docs = query('tags:"{}"'.format(tag))['results']
            assert_equal(len(docs), 0)

    def test_update_wiki(self):
        """Add text to a wiki page, then verify that project is found when
        searching for wiki text.

        """
        wiki_content = {'home': 'Hammer to fall', 'swag': '#YOLO'}
        for key, value in wiki_content.items():
            docs = query(value)['results']
            assert_equal(len(docs), 0)
            self.project.update_node_wiki(
                key,
                value,
                self.consolidate_auth,
            )
            docs = query(value)['results']
            assert_equal(len(docs), 1)

    def test_clear_wiki(self):
        """Add wiki text to page, then delete, then verify that project is not
        found when searching for wiki text.

        """
        wiki_content = 'Hammer to fall'
        self.project.update_node_wiki(
            'home',
            wiki_content,
            self.consolidate_auth,
        )
        self.project.update_node_wiki('home', '', self.consolidate_auth)

        docs = query(wiki_content)['results']
        assert_equal(len(docs), 0)

    def test_add_contributor(self):
        """Add a contributor, then verify that project is found when searching
        for contributor.

        """
        user2 = UserFactory(fullname='Adam Lambert')

        docs = query('category:project AND "{}"'.format(
            user2.fullname))['results']
        assert_equal(len(docs), 0)

        self.project.add_contributor(user2, save=True)

        docs = query('category:project AND "{}"'.format(
            user2.fullname))['results']
        assert_equal(len(docs), 1)

    def test_remove_contributor(self):
        """Add and remove a contributor, then verify that project is not found
        when searching for contributor.

        """
        user2 = UserFactory(fullname='Brian May')

        self.project.add_contributor(user2, save=True)
        self.project.remove_contributor(user2, self.consolidate_auth)

        docs = query('category:project AND "{}"'.format(
            user2.fullname))['results']
        assert_equal(len(docs), 0)

    def test_hide_contributor(self):
        user2 = UserFactory(fullname='Brian May')
        self.project.add_contributor(user2)
        self.project.set_visible(user2, False, save=True)
        docs = query('category:project AND "{}"'.format(
            user2.fullname))['results']
        assert_equal(len(docs), 0)
        self.project.set_visible(user2, True, save=True)
        docs = query('category:project AND "{}"'.format(
            user2.fullname))['results']
        assert_equal(len(docs), 1)

    def test_wrong_order_search(self):
        title_parts = self.title.split(' ')
        title_parts.reverse()
        title_search = ' '.join(title_parts)

        docs = query(title_search)['results']
        assert_equal(len(docs), 3)

    def test_tag_aggregation(self):
        tags = ['stonecoldcrazy', 'just a poor boy', 'from-a-poor-family']

        for tag in tags:
            self.project.add_tag(tag, self.consolidate_auth, save=True)

        docs = query(self.title)['tags']
        assert len(docs) == 3
        for doc in docs:
            assert doc['key'] in tags

    def test_count_aggregation(self):
        docs = query("*")['counts']
        assert_equal(docs['total'], 4)
        assert_equal(docs['project'], 1)
        assert_equal(docs['component'], 1)
        assert_equal(docs['registration'], 1)
Beispiel #57
0
class TestAddonLogs(OsfTestCase):

    def setUp(self):
        super(TestAddonLogs, self).setUp()
        self.flask_app = SetEnvironMiddleware(self.app.app, REMOTE_ADDR='127.0.0.1')
        self.test_app = webtest.TestApp(self.flask_app)
        self.user = AuthUserFactory()
        self.auth_obj = Auth(user=self.user)
        self.node = ProjectFactory(creator=self.user)
        self.session = Session(data={'auth_user_id': self.user._id})
        self.session.save()
        self.cookie = itsdangerous.Signer(settings.SECRET_KEY).sign(self.session._id)
        self.configure_addon()

    def configure_addon(self):
        self.user.add_addon('github')
        self.user_addon = self.user.get_addon('github')
        self.oauth_settings = AddonGitHubOauthSettings(github_user_id='john')
        self.oauth_settings.save()
        self.user_addon.oauth_settings = self.oauth_settings
        self.user_addon.oauth_access_token = 'secret'
        self.user_addon.save()
        self.node.add_addon('github', self.auth_obj)
        self.node_addon = self.node.get_addon('github')
        self.node_addon.user = '******'
        self.node_addon.repo = 'youre-my-best-friend'
        self.node_addon.user_settings = self.user_addon
        self.node_addon.save()

    def build_payload(self, metadata, **kwargs):
        options = dict(
            auth={'id': self.user._id},
            action='create',
            provider=self.node_addon.config.short_name,
            metadata=metadata,
            time=time.time() + 1000,
        )
        options.update(kwargs)
        options = {
            key: value
            for key, value in options.iteritems()
            if value is not None
        }
        message, signature = signing.default_signer.sign_payload(options)
        return {
            'payload': message,
            'signature': signature,
        }

    def test_add_log(self):
        path = 'pizza'
        url = self.node.api_url_for('create_waterbutler_log')
        payload = self.build_payload(metadata={'path': path})
        nlogs = len(self.node.logs)
        self.test_app.put_json(url, payload, headers={'Content-Type': 'application/json'})
        self.node.reload()
        assert_equal(len(self.node.logs), nlogs + 1)

    def test_add_log_missing_args(self):
        path = 'pizza'
        url = self.node.api_url_for('create_waterbutler_log')
        payload = self.build_payload(metadata={'path': path}, auth=None)
        nlogs = len(self.node.logs)
        res = self.test_app.put_json(
            url,
            payload,
            headers={'Content-Type': 'application/json'},
            expect_errors=True,
        )
        assert_equal(res.status_code, 400)
        self.node.reload()
        assert_equal(len(self.node.logs), nlogs)

    def test_add_log_no_user(self):
        path = 'pizza'
        url = self.node.api_url_for('create_waterbutler_log')
        payload = self.build_payload(metadata={'path': path}, auth={'id': None})
        nlogs = len(self.node.logs)
        res = self.test_app.put_json(
            url,
            payload,
            headers={'Content-Type': 'application/json'},
            expect_errors=True,
        )
        assert_equal(res.status_code, 400)
        self.node.reload()
        assert_equal(len(self.node.logs), nlogs)

    def test_add_log_no_addon(self):
        path = 'pizza'
        node = ProjectFactory(creator=self.user)
        url = node.api_url_for('create_waterbutler_log')
        payload = self.build_payload(metadata={'path': path})
        nlogs = len(node.logs)
        res = self.test_app.put_json(
            url,
            payload,
            headers={'Content-Type': 'application/json'},
            expect_errors=True,
        )
        assert_equal(res.status_code, 400)
        self.node.reload()
        assert_equal(len(node.logs), nlogs)

    def test_add_log_bad_action(self):
        path = 'pizza'
        url = self.node.api_url_for('create_waterbutler_log')
        payload = self.build_payload(metadata={'path': path}, action='dance')
        nlogs = len(self.node.logs)
        res = self.test_app.put_json(
            url,
            payload,
            headers={'Content-Type': 'application/json'},
            expect_errors=True,
        )
        assert_equal(res.status_code, 400)
        self.node.reload()
        assert_equal(len(self.node.logs), nlogs)
Beispiel #58
0
class TestAddonCount(OsfTestCase):
    def setUp(self):
        super(TestAddonCount, self).setUp()
        self.user = AuthUserFactory()
        self.node = ProjectFactory(creator=self.user)
        self.user.add_addon('github')
        self.user_addon = self.user.get_addon('github')

        self.external_account = GitHubAccountFactory(display_name='hmoco1')

        self.user_settings = self.user.get_or_add_addon('github')

        self.user_settings.save()
        self.user.external_accounts.append(self.external_account)
        self.user.save()
        self.node.add_addon('github', Auth(self.user))
        self.node_addon = self.node.get_addon('github')
        self.node_addon.user = self.user.fullname
        self.node_addon.repo = '29 #Strafford APTS'
        self.node_addon.user_settings = self.user_addon
        self.node_addon.external_account = self.external_account
        self.node_addon.save()

        self.user_settings.grant_oauth_access(
            node=self.node,
            external_account=self.external_account,
        )

    def tearDown(self):
        GitHubNodeSettings.remove()
        GitHubUserSettings.remove()
        GoogleDriveNodeSettings.remove()
        GoogleDriveUserSettings.remove()

    def test_run_for_all_addon(self):
        results = AddonSnapshot().get_events()
        names = [res['provider']['name'] for res in results]
        for addon in ADDONS_AVAILABLE:
            assert_in(addon.short_name, names)

    def test_one_user_one_node_one_addon(self):
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['users']['enabled'], 1)
        assert_equal(github_res['nodes']['total'], 1)

    def test_one_user_one_node_one_addon_one_node_linked(self):
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['users']['enabled'], 1)
        assert_equal(github_res['nodes']['total'], 1)

    def test_one_user_with_multiple_githubs(self):
        oauth_settings2 = GitHubAccountFactory(display_name='hmoco2')
        oauth_settings2.save()
        self.user.external_accounts.append(oauth_settings2)
        self.user.save()
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['users']['enabled'], 1)

    def test_one_user_with_multiple_addons(self):
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        googledrive_res = [
            res for res in results if res['provider']['name'] == 'googledrive'
        ][0]
        assert_equal(github_res['users']['enabled'], 1)
        assert_equal(googledrive_res['users']['enabled'], 0)

        self.user.add_addon('googledrive')
        oauth_settings = GoogleDriveAccountFactory()
        oauth_settings.save()
        self.user.external_accounts.append(oauth_settings)
        self.user.save()
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        googledrive_res = [
            res for res in results if res['provider']['name'] == 'googledrive'
        ][0]
        assert_equal(github_res['users']['enabled'], 1)
        assert_equal(googledrive_res['users']['enabled'], 1)

    def test_many_users_each_with_a_different_github(self):
        user = AuthUserFactory()
        user.add_addon('github')
        oauth_settings2 = GitHubAccountFactory(display_name='hmoco2')
        oauth_settings2.save()
        user.external_accounts.append(oauth_settings2)
        user.save()
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['users']['enabled'], 2)
        assert_equal(github_res['users']['authorized'], 1)
        assert_equal(github_res['users']['linked'], 1)

    def test_many_users_each_with_the_same_github_enabled(self):
        user = AuthUserFactory()
        user.add_addon('github')
        user.external_accounts.append(self.external_account)
        user.save()
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['users']['enabled'], 2)

    def test_github_enabled_not_linked_or_authorized(self):
        user = AuthUserFactory()
        user.add_addon('github')
        user.external_accounts.append(self.external_account)
        user.save()
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['users']['enabled'], 2)
        assert_equal(github_res['users']['authorized'], 1)
        assert_equal(github_res['users']['linked'], 1)

    def test_one_node_with_multiple_addons(self):
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        googledrive_res = [
            res for res in results if res['provider']['name'] == 'googledrive'
        ][0]
        assert_equal(github_res['nodes']['total'], 1)
        assert_equal(googledrive_res['nodes']['total'], 0)

        self.user.add_addon('googledrive')
        user_addon = self.user.get_addon('googledrive')
        oauth_settings = GoogleDriveAccountFactory()
        oauth_settings.save()
        self.user.external_accounts.append(oauth_settings)
        self.user.save()
        self.node.add_addon('googledrive', Auth(self.user))
        node_addon = self.node.get_addon('googledrive')
        node_addon.user = self.user.fullname
        node_addon.user_settings = user_addon
        node_addon.external_account = oauth_settings
        node_addon.save()
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        googledrive_res = [
            res for res in results if res['provider']['name'] == 'googledrive'
        ][0]
        assert_equal(github_res['nodes']['total'], 1)
        assert_equal(googledrive_res['nodes']['total'], 1)

    def test_many_nodes_with_one_addon(self):
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['nodes']['total'], 1)

        node = ProjectFactory(creator=self.user)
        node.add_addon('github', Auth(self.user))
        node_addon = node.get_addon('github')
        node_addon.user = self.user.fullname
        node_addon.repo = '8 (circle)'
        node_addon.user_settings = self.user_addon
        node_addon.external_account = self.external_account
        node_addon.save()
        node.save()

        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['nodes']['total'], 2)

    def test_node_count_deleted_addon(self):
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['nodes']['deleted'], 0)

        node = ProjectFactory(creator=self.user)
        node.add_addon('github', Auth(self.user))
        node_addon = node.get_addon('github')
        node_addon.delete()

        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['nodes']['deleted'], 1)

    def test_node_count_disconected_addon(self):
        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['nodes']['disconnected'], 0)

        node = ProjectFactory(creator=self.user)
        node.add_addon('github', Auth(self.user))
        node_addon = node.get_addon('github')
        node_addon.external_account = None
        node_addon.save()

        results = AddonSnapshot().get_events()
        github_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(github_res['nodes']['disconnected'], 1)

    def test_all_users_have_wiki_osfstorage_enabled(self):
        all_user_count = User.find().count()
        results = AddonSnapshot().get_events()
        osfstorage_res = [
            res for res in results if res['provider']['name'] == 'osfstorage'
        ][0]
        wiki_res = [
            res for res in results if res['provider']['name'] == 'osfstorage'
        ][0]

        assert_equal(osfstorage_res['users']['enabled'], all_user_count)
        assert_equal(wiki_res['users']['enabled'], all_user_count)

    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)

    def test_node_settings_has_no_owner_not_connected(self):
        self.node_addon.owner = None
        self.node_addon.save()

        results = AddonSnapshot().get_events()
        storage_res = [
            res for res in results if res['provider']['name'] == 'github'
        ][0]
        assert_equal(storage_res['nodes']['connected'], 0)

    def test_bookmark_collection_not_counted(self):
        all_node_count = Node.find().count()

        results = AddonSnapshot().get_events()
        storage_res = [
            res for res in results if res['provider']['name'] == 'osfstorage'
        ][0]
        assert_equal(storage_res['nodes']['connected'], all_node_count - 1)
Beispiel #59
0
class RegistrationEmbargoViewsTestCase(OsfTestCase):
    def setUp(self):
        super(RegistrationEmbargoViewsTestCase, self).setUp()
        ensure_schemas()
        self.user = AuthUserFactory()
        self.project = ProjectFactory(creator=self.user)
        self.registration = RegistrationFactory(project=self.project,
                                                creator=self.user)

        current_month = datetime.datetime.now().strftime("%B")
        current_year = datetime.datetime.now().strftime("%Y")

        self.valid_make_public_payload = json.dumps({
            u'embargoEndDate':
            u'Fri, 01, {month} {year} 00:00:00 GMT'.format(month=current_month,
                                                           year=current_year),
            u'registrationChoice':
            'immediate',
            u'summary':
            unicode(fake.sentence())
        })
        valid_date = datetime.datetime.now() + datetime.timedelta(days=180)
        self.valid_embargo_payload = json.dumps({
            u'embargoEndDate':
            unicode(valid_date.strftime('%a, %d, %B %Y %H:%M:%S')) + u' GMT',
            u'registrationChoice':
            'embargo',
            u'summary':
            unicode(fake.sentence())
        })
        self.invalid_embargo_date_payload = json.dumps({
            u'embargoEndDate':
            u"Thu, 01 {month} {year} 05:00:00 GMT".format(
                month=current_month, year=str(int(current_year) - 1)),
            u'registrationChoice':
            'embargo',
            u'summary':
            unicode(fake.sentence())
        })

    @mock.patch('framework.tasks.handlers.enqueue_task')
    def test_POST_register_make_public_immediately_creates_registration_approval(
            self, mock_enqueue):
        res = self.app.post(self.project.api_url_for(
            'node_register_template_page_post',
            template=u'Open-Ended_Registration'),
                            self.valid_make_public_payload,
                            content_type='application/json',
                            auth=self.user.auth)
        assert_equal(res.status_code, 201)

        registration = Node.find().sort('-registered_date')[0]

        assert_true(registration.is_registration)
        assert_not_equal(registration.registration_approval, None)

    @mock.patch('framework.tasks.handlers.enqueue_task')
    def test_POST_register_make_public_does_not_make_children_public(
            self, mock_enqueue):
        component = NodeFactory(creator=self.user,
                                parent=self.project,
                                title='Component')
        subproject = ProjectFactory(creator=self.user,
                                    parent=self.project,
                                    title='Subproject')
        subproject_component = NodeFactory(creator=self.user,
                                           parent=subproject,
                                           title='Subcomponent')

        res = self.app.post(self.project.api_url_for(
            'node_register_template_page_post',
            template=u'Open-Ended_Registration'),
                            self.valid_make_public_payload,
                            content_type='application/json',
                            auth=self.user.auth)
        self.project.reload()
        # Last node directly registered from self.project
        registration = Node.load(self.project.node__registrations[-1])
        assert_false(registration.is_public)
        for node in registration.get_descendants_recursive():
            assert_true(node.is_registration)
            assert_false(node.is_public)

    @mock.patch('framework.tasks.handlers.enqueue_task')
    def test_POST_register_embargo_is_not_public(self, mock_enqueue):
        res = self.app.post(self.project.api_url_for(
            'node_register_template_page_post',
            template=u'Open-Ended_Registration'),
                            self.valid_embargo_payload,
                            content_type='application/json',
                            auth=self.user.auth)

        assert_equal(res.status_code, 201)

        registration = Node.find().sort('-registered_date')[0]

        assert_true(registration.is_registration)
        assert_false(registration.is_public)
        assert_true(registration.is_pending_embargo_for_existing_registration)
        assert_is_not_none(registration.embargo)

    @mock.patch('framework.tasks.handlers.enqueue_task')
    def test_POST_invalid_embargo_end_date_returns_HTTPBad_Request(
            self, mock_enqueue):
        res = self.app.post(self.project.api_url_for(
            'node_register_template_page_post',
            template=u'Open-Ended_Registration'),
                            self.invalid_embargo_date_payload,
                            content_type='application/json',
                            auth=self.user.auth,
                            expect_errors=True)

        assert_equal(res.status_code, 400)

    @mock.patch('framework.tasks.handlers.enqueue_task')
    def test_valid_POST_embargo_adds_to_parent_projects_log(
            self, mock_enquque):
        initial_project_logs = len(self.project.logs)
        res = self.app.post(self.project.api_url_for(
            'node_register_template_page_post',
            template=u'Open-Ended_Registration'),
                            self.valid_embargo_payload,
                            content_type='application/json',
                            auth=self.user.auth)
        self.project.reload()
        # Logs: Created, registered, embargo initiated
        assert_equal(len(self.project.logs), initial_project_logs + 1)

    def test_non_contributor_GET_approval_returns_HTTPError(self):
        non_contributor = AuthUserFactory()
        self.registration.embargo_registration(
            self.user,
            datetime.datetime.utcnow() + datetime.timedelta(days=10))
        self.registration.save()
        assert_true(self.registration.is_pending_embargo)

        approval_token = self.registration.embargo.approval_state[
            self.user._id]['approval_token']
        approval_url = self.registration.web_url_for('view_project',
                                                     token=approval_token)

        res = self.app.get(approval_url,
                           auth=non_contributor.auth,
                           expect_errors=True)
        assert_equal(http.FORBIDDEN, res.status_code)
        assert_true(self.registration.is_pending_embargo)
        assert_false(self.registration.embargo_end_date)

    def test_non_contributor_GET_disapproval_returns_HTTPError(self):
        non_contributor = AuthUserFactory()
        self.registration.embargo_registration(
            self.user,
            datetime.datetime.utcnow() + datetime.timedelta(days=10))
        self.registration.save()
        assert_true(self.registration.is_pending_embargo)

        rejection_token = self.registration.embargo.approval_state[
            self.user._id]['rejection_token']
        approval_url = self.registration.web_url_for('view_project',
                                                     token=rejection_token)

        res = self.app.get(approval_url,
                           auth=non_contributor.auth,
                           expect_errors=True)
        assert_equal(http.FORBIDDEN, res.status_code)
        assert_true(self.registration.is_pending_embargo)
        assert_false(self.registration.embargo_end_date)
Beispiel #60
0
class TestAddonFileViews(OsfTestCase):

    def setUp(self):
        super(TestAddonFileViews, self).setUp()
        self.user = AuthUserFactory()
        self.project = ProjectFactory(creator=self.user)

        self.user.add_addon('github')
        self.project.add_addon('github', auth=Auth(self.user))

        self.user_addon = self.user.get_addon('github')
        self.node_addon = self.project.get_addon('github')
        self.oauth = AddonGitHubOauthSettings(
            github_user_id='denbarell',
            oauth_access_token='Truthy'
        )

        self.oauth.save()

        self.user_addon.oauth_settings = self.oauth
        self.user_addon.save()

        self.node_addon.user_settings = self.user_addon
        self.node_addon.save()

        # self.node_addon.user_settings = 'Truthy'
        # setattr(self.node_addon, 'has_auth', True)

    def get_mako_return(self):
        ret = serialize_node(self.project, Auth(self.user), primary=True)
        ret.update({
            'extra': '',
            'provider': '',
            'rendered': '',
            'file_path': '',
            'files_url': '',
            'file_name': '',
            'render_url': '',
            'materialized_path': '',
        })
        ret.update(rubeus.collect_addon_assets(self.project))
        return ret

    def test_redirects_to_guid(self):
        path = 'bigdata'
        guid, _ = self.node_addon.find_or_create_file_guid('/' + path)

        resp = self.app.get(
            self.project.web_url_for(
                'addon_view_or_download_file',
                path=path,
                provider='github'
            ),
            auth=self.user.auth
        )

        assert_equals(resp.status_code, 302)
        assert_equals(resp.headers['Location'], 'http://*****:*****@mock.patch('website.addons.base.request')
    def test_public_download_url_includes_view_only(self, mock_request):
        view_only = 'justworkplease'
        mock_request.args = {
            'view_only': view_only
        }

        path = 'cloudfiles'
        guid, _ = self.node_addon.find_or_create_file_guid('/' + path)

        assert_in('view_only={}'.format(view_only), guid.public_download_url)

    @mock.patch('website.addons.base.views.addon_view_file')
    def test_action_view_calls_view_file(self, mock_view_file):
        self.user.reload()
        self.project.reload()

        path = 'cloudfiles'
        mock_view_file.return_value = self.get_mako_return()
        guid, _ = self.node_addon.find_or_create_file_guid('/' + path)

        self.app.get(guid.guid_url + '?action=view', auth=self.user.auth)

        args, kwargs = mock_view_file.call_args
        assert_equals(kwargs, {})
        assert_equals(args[-1], {'action': 'view'})
        assert_equals(args[1], self.project)
        assert_equals(args[0].user, self.user)
        assert_equals(args[2], self.node_addon)

    @mock.patch('website.addons.base.views.addon_view_file')
    def test_no_action_calls_view_file(self, mock_view_file):
        self.user.reload()
        self.project.reload()

        path = 'cloudfiles'
        mock_view_file.return_value = self.get_mako_return()
        guid, _ = self.node_addon.find_or_create_file_guid('/' + path)

        self.app.get(guid.guid_url, auth=self.user.auth)

        args, kwargs = mock_view_file.call_args
        assert_equals(kwargs, {})
        assert_equals(args[-1], {})
        assert_equals(args[1], self.project)
        assert_equals(args[0].user, self.user)
        assert_equals(args[2], self.node_addon)

    def test_download_create_guid(self):
        path = 'cloudfiles'

        self.app.get(
            self.project.web_url_for(
                'addon_view_or_download_file',
                path=path,
                provider='github',
                action='download'
            ),
            auth=self.user.auth
        )

        guid, created = self.node_addon.find_or_create_file_guid('/' + path)

        assert_true(guid)
        assert_false(created)
        assert_equals(guid.waterbutler_path, '/' + path)

    def test_unauthorized_addons_raise(self):
        path = 'cloudfiles'
        self.node_addon.user_settings = None
        self.node_addon.save()

        resp = self.app.get(
            self.project.web_url_for(
                'addon_view_or_download_file',
                path=path,
                provider='github',
                action='download'
            ),
            auth=self.user.auth,
            expect_errors=True
        )

        assert_equals(resp.status_code, 403)

    def test_head_returns_url(self):
        path = 'the little engine that couldnt'
        guid, _ = self.node_addon.find_or_create_file_guid('/' + path)

        download_url = furl.furl(guid.download_url)
        download_url.args['accept_url'] = 'false'

        resp = self.app.head(guid.guid_url, auth=self.user.auth)

        assert_urls_equal(resp.headers['Location'], download_url.url)

    def test_nonexistent_addons_raise(self):
        path = 'cloudfiles'
        self.project.delete_addon('github', Auth(self.user))
        self.project.save()

        resp = self.app.get(
            self.project.api_url_for(
                'addon_render_file',
                path=path,
                provider='github',
                action='download'
            ),
            auth=self.user.auth,
            expect_errors=True
        )

        assert_equals(resp.status_code, 400)

    def test_unauth_addons_raise(self):
        path = 'cloudfiles'
        self.node_addon.user_settings = None
        self.node_addon.save()

        resp = self.app.get(
            self.project.api_url_for(
                'addon_render_file',
                path=path,
                provider='github',
                action='download'
            ),
            auth=self.user.auth,
            expect_errors=True
        )

        assert_equals(resp.status_code, 401)

    def test_unconfigured_addons_raise(self):
        path = 'cloudfiles'
        self.node_addon.repo = None
        self.node_addon.save()

        resp = self.app.get(
            self.project.api_url_for(
                'addon_render_file',
                path=path,
                provider='github',
                action='download'
            ),
            auth=self.user.auth,
            expect_errors=True
        )

        assert_equals(resp.status_code, 400)