Beispiel #1
0
class TestViews(OsfTestCase):
    @mock.patch('website.addons.twofactor.models.push_status_message')
    def setUp(self, mocked):
        super(TestViews, self).setUp()
        self.user = AuthUserFactory()
        self.user.add_addon('twofactor')
        self.user_settings = self.user.get_addon('twofactor')

    def test_confirm_code(self):
        # Send a valid code to the API endpoint for the user settings.
        res = self.app.post_json(
            '/api/v1/settings/twofactor/',
            {'code': _valid_code(self.user_settings.totp_secret)},
            auth=self.user.auth)

        # reload the user settings object from the DB
        self.user_settings.reload()

        assert_true(self.user_settings.is_confirmed)
        assert_equal(res.status_code, 200)

    def test_confirm_code_failure(self):
        res = self.app.post_json('/api/v1/settings/twofactor/',
                                 {'code': '000000'},
                                 auth=self.user.auth,
                                 expect_errors=True)
        assert_equal(res.status_code, 403)
        json = res.json
        assert_in('verification code', json['message_long'])

        # reload the user settings object from the DB
        self.user_settings.reload()

        assert_false(self.user_settings.is_confirmed)
Beispiel #2
0
    def test_revoke_didnt_award(self):
        badgeid = self.user_settings.badges[0]._id
        initnum = len(self.project.badgeassertion__awarded)
        assert_true(self.user_settings.can_award)
        url = api_url_for('award_badge', pid=self.project._id)
        ret = self.app.post_json(url, {'badgeid': badgeid},
                                 auth=self.user.auth)
        self.project.reload()
        assert_equals(ret.status_int, 200)
        assert_equals(initnum + 1, len(self.project.badgeassertion__awarded))

        assertion = self.project.badgeassertion__awarded[0]

        revoke = api_url_for('revoke_badge', pid=self.project._id)

        user2 = AuthUserFactory()
        user2.add_addon('badges', override=True)
        user2.save()
        user2.reload()

        ret = self.app.post_json(revoke, {
            'id': assertion._id,
            'reason': ''
        },
                                 auth=user2.auth,
                                 expect_errors=True)
        self.project.reload()
        self.user_settings.reload()
        assertion.reload()

        assert_equals(ret.status_int, 400)
        assert_false(assertion.revoked)
        assert_true(self.project.badgeassertion__awarded[0]._id, assertion._id)
        assert_false(assertion._id in self.user_settings.revocation_list)
Beispiel #3
0
class TestAssertion(OsfTestCase):
    def setUp(self):
        super(TestAssertion, self).setUp()
        self.user = AuthUserFactory()
        self.user.add_addon('badges', override=True)
        self.usersettings = self.user.get_addon('badges', self.user.auth)
        self.usersettings.save()
        self.project = ProjectFactory()
        self.node_settings = self.project.get_addon('badges')
        create_mock_badge(self.usersettings)
        self.badge = self.usersettings.badges[0]

    def test_parent(self):
        assertion = BadgeAssertion.create(self.badge, self.project)
        assert_equals(assertion.badge, self.badge)

    def test_recipient(self):
        assertion = BadgeAssertion.create(self.badge, self.project)
        test_data = {
            'idenity': self.project._id,
            'type': 'osfnode',
            'hashed': False
        }
        assert_equals(assertion.recipient, test_data)

    def test_awarder(self):
        assertion = BadgeAssertion.create(self.badge, self.project)
        assert_equals(assertion.awarder, self.usersettings)
Beispiel #4
0
 def test_set_config_not_owner(self, mock_metadata):
     mock_metadata.return_value = {
         'data': {
             'name': 'Fake Folder'
         }
     }
     user = AuthUserFactory()
     user.add_addon('zotero')
     self.project.add_contributor(user)
     self.project.save()
     res = self.app.put_json(
         self.project.api_url_for('zotero_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 = ZoteroSerializer(node_settings=self.node_addon, user_settings=None)
     result = {
         'result': serializer.serialized_node_settings
     }
     assert_equal(res.json, result)
Beispiel #5
0
class TestUserSettingsModel(OsfTestCase):
    def setUp(self):
        super(TestUserSettingsModel, self).setUp()
        self.user = AuthUserFactory()
        self.user.add_addon('badges', override=True)
        self.usersettings = self.user.get_addon('badges')
        self.usersettings.save()

    def test_can_award(self):
        assert_false(self.usersettings.can_award)
        create_mock_badge(self.usersettings)
        assert_true(self.usersettings.can_award)

    def test_to_openbadge(self):
        self.user.fullname = 'HoneyBadger'
        self.user.username = '******'
        self.user.save()

        test = {'name': 'HoneyBadger', 'email': '*****@*****.**'}

        assert_equal(self.usersettings.to_openbadge(), test)

    def test_badges(self):
        create_mock_badge(self.usersettings)
        create_mock_badge(self.usersettings)
        assert_equal(len(self.usersettings.badges), 2)
        create_mock_badge(self.usersettings)
        assert_equal(len(self.usersettings.badges), 3)
Beispiel #6
0
class TestBadge(OsfTestCase):
    def setUp(self):
        super(TestBadge, self).setUp()
        self.user = AuthUserFactory()
        self.user.add_addon('badges', override=True)
        self.usersettings = self.user.get_addon('badges', self.user.auth)
        self.usersettings.save()

    def test_fields(self):
        badgedata = create_badge_dict()
        create_mock_badge(self.usersettings, badge_data=badgedata)
        badge = self.usersettings.badges[0]
        assert_equals(badge.name, badgedata['badgeName'])
        assert_equals(badge.description, badgedata['description'])
        assert_equals(badge.image, 'temp.png')
        assert_equals(badge.criteria, badgedata['criteria'])

    def test_system_badge(self):
        create_mock_badge(self.usersettings)
        badge = self.usersettings.badges[0]
        badge.make_system_badge()
        assert_true(badge.is_system_badge)
        assert_equals(badge, Badge.get_system_badges()[0])

    def test_assertions(self):
        create_mock_badge(self.usersettings)
        badge = self.usersettings.badges[0]
        assert_equals(len(badge.assertions), 0)
        for n in xrange(4):
            BadgeAssertion.create(badge, None)
            assert_equals(len(badge.assertions), n + 1)
Beispiel #7
0
    def test_revoke_didnt_award(self):
        badgeid = self.user_settings.badges[0]._id
        initnum = len(self.project.badgeassertion__awarded)
        assert_true(self.user_settings.can_award)
        url = api_url_for('award_badge', pid=self.project._id)
        ret = self.app.post_json(url, {'badgeid': badgeid}, auth=self.user.auth)
        self.project.reload()
        assert_equals(ret.status_int, 200)
        assert_equals(initnum + 1, len(self.project.badgeassertion__awarded))

        assertion = self.project.badgeassertion__awarded[0]

        revoke = api_url_for('revoke_badge', pid=self.project._id)

        user2 = AuthUserFactory()
        user2.add_addon('badges', override=True)
        user2.save()
        user2.reload()

        ret = self.app.post_json(revoke,
            {
                'id': assertion._id,
                'reason': ''
            }, auth=user2.auth, expect_errors=True)
        self.project.reload()
        self.user_settings.reload()
        assertion.reload()

        assert_equals(ret.status_int, 400)
        assert_false(assertion.revoked)
        assert_true(self.project.badgeassertion__awarded[0]._id, assertion._id)
        assert_false(assertion._id in self.user_settings.revocation_list)
Beispiel #8
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 #9
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 #10
0
class TestBadge(OsfTestCase):

    def setUp(self):
        super(TestBadge, self).setUp()
        self.user = AuthUserFactory()
        self.user.add_addon('badges', override=True)
        self.usersettings = self.user.get_addon('badges', self.user.auth)
        self.usersettings.save()

    def test_fields(self):
        badgedata = create_badge_dict()
        create_mock_badge(self.usersettings, badge_data=badgedata)
        badge = self.usersettings.badges[0]
        assert_equals(badge.name, badgedata['badgeName'])
        assert_equals(badge.description, badgedata['description'])
        assert_equals(badge.image, 'temp.png')
        assert_equals(badge.criteria, badgedata['criteria'])

    def test_system_badge(self):
        create_mock_badge(self.usersettings)
        badge = self.usersettings.badges[0]
        badge.make_system_badge()
        assert_true(badge.is_system_badge)
        assert_equals(badge, Badge.get_system_badges()[0])

    def test_assertions(self):
        create_mock_badge(self.usersettings)
        badge = self.usersettings.badges[0]
        assert_equals(len(badge.assertions), 0)
        for n in xrange(4):
            BadgeAssertion.create(badge, None)
            assert_equals(len(badge.assertions), n + 1)
Beispiel #11
0
    def test_set_user_config_fail(self, mock_connection):

        mock_connection.return_value = create_mock_connection('wrong', 'info')

        # Create a user with no settings
        user = AuthUserFactory()
        user.add_addon('dataverse')
        user_settings = user.get_addon('dataverse')

        url = api_url_for('dataverse_set_user_config')
        params = {'dataverse_username': '******',
                  'dataverse_password': '******'}

        # Post incorrect credentials to existing user
        res = self.app.post_json(url, params, auth=self.user.auth,
                                 expect_errors=True)
        self.user_settings.reload()

        # Original user's info has not changed
        assert_equal(res.status_code, http.UNAUTHORIZED)
        assert_equal(self.user_settings.dataverse_username, 'snowman')
        assert_equal(self.user_settings.dataverse_password, 'frosty')

        # Post incorrect credentials to new user
        res = self.app.post_json(url, params, auth=user.auth,
                                 expect_errors=True)
        user_settings.reload()

        # New user's incorrect credentials were not saved
        assert_equal(res.status_code, http.UNAUTHORIZED)
        assert_equal(user_settings.dataverse_username, None)
        assert_equal(user_settings.dataverse_password, None)
Beispiel #12
0
    def test_set_user_config_fail(self, mock_connection):

        mock_connection.side_effect = UnauthorizedError('Bad credentials!')

        # Create a user with no settings
        user = AuthUserFactory()
        user.add_addon('dataverse')
        user_settings = user.get_addon('dataverse')

        url = api_url_for('dataverse_set_user_config')
        params = {'api_token': 'wrong-info'}

        # Post incorrect credentials to existing user
        res = self.app.post_json(url,
                                 params,
                                 auth=self.user.auth,
                                 expect_errors=True)
        self.user_settings.reload()

        # Original user's info has not changed
        assert_equal(res.status_code, http.UNAUTHORIZED)
        assert_equal(self.user_settings.api_token, 'snowman-frosty')

        # Post incorrect credentials to new user
        res = self.app.post_json(url,
                                 params,
                                 auth=user.auth,
                                 expect_errors=True)
        user_settings.reload()

        # New user's incorrect credentials were not saved
        assert_equal(res.status_code, http.UNAUTHORIZED)
        assert_equal(user_settings.api_token, None)
Beispiel #13
0
class TestUserSettingsModel(OsfTestCase):

    def setUp(self):
        super(TestUserSettingsModel, self).setUp()
        self.user = AuthUserFactory()
        self.user.add_addon('badges', override=True)
        self.usersettings = self.user.get_addon('badges')
        self.usersettings.save()

    def test_can_award(self):
        assert_false(self.usersettings.can_award)
        create_mock_badge(self.usersettings)
        assert_true(self.usersettings.can_award)

    def test_to_openbadge(self):
        self.user.fullname = 'HoneyBadger'
        self.user.username = '******'
        self.user.save()

        test = {
            'name': 'HoneyBadger',
            'email': '*****@*****.**'
        }

        assert_equal(self.usersettings.to_openbadge(), test)

    def test_badges(self):
        create_mock_badge(self.usersettings)
        create_mock_badge(self.usersettings)
        assert_equal(len(self.usersettings.badges), 2)
        create_mock_badge(self.usersettings)
        assert_equal(len(self.usersettings.badges), 3)
Beispiel #14
0
class TestAssertion(OsfTestCase):

    def setUp(self):
        super(TestAssertion, self).setUp()
        self.user = AuthUserFactory()
        self.user.add_addon('badges', override=True)
        self.usersettings = self.user.get_addon('badges', self.user.auth)
        self.usersettings.save()
        self.project = ProjectFactory()
        self.node_settings = self.project.get_addon('badges')
        create_mock_badge(self.usersettings)
        self.badge = self.usersettings.badges[0]

    def test_parent(self):
        assertion = BadgeAssertion.create(self.badge, self.project)
        assert_equals(assertion.badge, self.badge)

    def test_recipient(self):
        assertion = BadgeAssertion.create(self.badge, self.project)
        test_data = {
            'idenity': self.project._id,
            'type': 'osfnode',
            'hashed': False
        }
        assert_equals(assertion.recipient, test_data)

    def test_awarder(self):
        assertion = BadgeAssertion.create(self.badge, self.project)
        assert_equals(assertion.awarder, self.usersettings)
Beispiel #15
0
    def test_oauth_delete_user_two_osf_user(self, mock_revoke_token,
                                            mock_github_user):
        mock_revoke_token.return_value = True
        user = mock.Mock()
        user.id = "testing user id"
        user.login = "******"
        mock_github_user.return_value = user
        views.auth.create_and_attach_oauth(self.user_settings,
                                           "testing acess token",
                                           "testing token type")

        user2 = AuthUserFactory()
        user2.add_addon('github')
        user2.save()
        user_settings2 = user2.get_addon('github')
        views.auth.create_and_attach_oauth(user_settings2,
                                           "testing access token",
                                           "testing token type")

        url = api_url_for("github_oauth_delete_user")
        self.app.delete(url, auth=self.user.auth)
        self.user_settings.reload()
        user_settings2.reload()
        assert_false(self.user_settings.oauth_token_type)
        assert_false(self.user_settings.oauth_access_token)
        assert_false(self.user_settings.github_user_name)
        assert_false(self.user_settings.oauth_settings)
        assert_true(user_settings2.oauth_settings)
        assert_equal(user_settings2.oauth_token_type, "testing token type")
        assert_equal(user_settings2.oauth_access_token, "testing access token")
        assert_equal(user_settings2.github_user_name, "testing user")
Beispiel #16
0
class TestMenbibAuthViews(OsfTestCase):

    def setUp(self):
        self.app = TestApp(app)
        self.user = AuthUserFactory()
        self.app.authenticate(*self.user.auth)

    def test_menbib_oauth_start(self):
        url = api_url_for('menbib_oauth_start_user')
        res = self.app.get(url)
        assert_is_redirect(res)

    @mock.patch('website.addons.menbib.views.auth.finish_auth')
    def test_menbib_oauth_finish(self, mock_finish):
        mock_finish.return_value = AuthResult('mytokenabc', 'myrefreshabc', 'cool', '3600')
        url = api_url_for('menbib_oauth_finish')
        res = self.app.get(url)
        assert_is_redirect(res)

    def test_menbib_oauth_delete_user(self):
        self.user.add_addon('menbib')
        user_settings = self.user.get_addon('menbib')
        user_settings.access_token = '12345abc'
        assert_true(user_settings.has_auth)
        self.user.save()
        url = api_url_for('menbib_oauth_delete_user')
        res = self.app.delete(url)
        user_settings.reload()
        assert_false(user_settings.has_auth)
Beispiel #17
0
class TestAuthViews(OsfTestCase):

    def setUp(self):
        self.app = TestApp(app)
        self.user = AuthUserFactory()
        self.app.authenticate(*self.user.auth)


    def test_mendeley_oauth_start(self):
        self.user.add_addon('mendeley')
        settings = self.user.get_addon('mendeley')
        settings.access_token = '12345abc'
        print settings.has_auth
        settings.save()
       # assert_true(settings.has_auth)
        url = views.mendeley_oauth_start(self)
        print url



    def test_mendeley_oauth_delete_user(self):
        pass

    def test_mendeley_oauth_delete_node(self):
        pass

    def test_mendeley_oauth_callback(self):
        pass
Beispiel #18
0
    def test_set_user_config_fail(self, mock_connection):

        mock_connection.return_value = create_mock_connection('wrong', 'info')

        # Create a user with no settings
        user = AuthUserFactory()
        user.add_addon('dataverse')
        user_settings = user.get_addon('dataverse')

        url = api_url_for('dataverse_set_user_config')
        params = {'dataverse_username': '******', 'dataverse_password': '******'}

        # Post incorrect credentials to existing user
        res = self.app.post_json(url,
                                 params,
                                 auth=self.user.auth,
                                 expect_errors=True)
        self.user_settings.reload()

        # Original user's info has not changed
        assert_equal(res.status_code, http.UNAUTHORIZED)
        assert_equal(self.user_settings.dataverse_username, 'snowman')
        assert_equal(self.user_settings.dataverse_password, 'frosty')

        # Post incorrect credentials to new user
        res = self.app.post_json(url,
                                 params,
                                 auth=user.auth,
                                 expect_errors=True)
        user_settings.reload()

        # New user's incorrect credentials were not saved
        assert_equal(res.status_code, http.UNAUTHORIZED)
        assert_equal(user_settings.dataverse_username, None)
        assert_equal(user_settings.dataverse_password, None)
Beispiel #19
0
 def test_set_config_not_owner(self, mock_metadata):
     mock_metadata.return_value = {
         'data': {
             'name': 'Fake Folder'
         }
     }
     user = AuthUserFactory()
     user.add_addon('zotero')
     self.project.add_contributor(user)
     self.project.save()
     res = self.app.put_json(
         self.project.api_url_for('zotero_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 = ZoteroSerializer(node_settings=self.node_addon, user_settings=None)
     result = {
         'result': serializer.serialized_node_settings
     }
     assert_equal(res.json, result)
Beispiel #20
0
class TestDataverseRestrictions(DataverseAddonTestCase):
    def setUp(self):

        super(DataverseAddonTestCase, self).setUp()

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

    @mock.patch('website.addons.dataverse.views.config.connect_from_settings')
    def test_restricted_set_study_not_owner(self, mock_connection):
        mock_connection.return_value = create_mock_connection()

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

        url = api_url_for('set_dataverse_and_study',
                          pid=self.project._primary_key)
        params = {
            'dataverse': {
                'alias': 'ALIAS1'
            },
            'study': {
                'hdl': 'doi:12.3456/DVN/00002'
            },
        }
        res = self.app.post_json(url,
                                 params,
                                 auth=self.contrib.auth,
                                 expect_errors=True)
        assert_equal(res.status_code, http.FORBIDDEN)
Beispiel #21
0
    def test_set_user_config_fail(self, mock_connection):

        mock_connection.side_effect = UnauthorizedError('Bad credentials!')

        # Create a user with no settings
        user = AuthUserFactory()
        user.add_addon('dataverse')
        user_settings = user.get_addon('dataverse')

        url = api_url_for('dataverse_set_user_config')
        params = {'api_token': 'wrong-info'}

        # Post incorrect credentials to existing user
        res = self.app.post_json(url, params, auth=self.user.auth,
                                 expect_errors=True)
        self.user_settings.reload()

        # Original user's info has not changed
        assert_equal(res.status_code, http.UNAUTHORIZED)
        assert_equal(self.user_settings.api_token, 'snowman-frosty')

        # Post incorrect credentials to new user
        res = self.app.post_json(url, params, auth=user.auth,
                                 expect_errors=True)
        user_settings.reload()

        # New user's incorrect credentials were not saved
        assert_equal(res.status_code, http.UNAUTHORIZED)
        assert_equal(user_settings.api_token, None)
Beispiel #22
0
class TestBoxIntegration(OsfTestCase):

    def setUp(self):
        super(TestBoxIntegration, self).setUp()
        self.user = AuthUserFactory()
        # User is logged in
        self.app.authenticate(*self.user.auth)

    def test_cant_start_oauth_if_already_authorized(self):
        # User already has box authorized
        self.user.add_addon('box')
        self.user.save()
        settings = self.user.get_addon('box')
        oauth = BoxOAuthSettings(user_id='fa;l', access_token='a;lkjadl;kas')
        oauth.save()
        settings.oauth_settings = oauth
        settings.save()

        assert_true(self.user.get_addon('box').has_auth)
        # Tries to start oauth again
        url = api_url_for('box_oauth_start_user')
        res = self.app.get(url).follow()

        # Is redirected back to settings page
        assert_equal(
            res.request.path,
            web_url_for('user_addons')
        )
Beispiel #23
0
    def test_oauth_delete_user_two_osf_user(self, mock_revoke_token, mock_github_user):
        mock_revoke_token.return_value = True
        user = mock.Mock()
        user.id = "testing user id"
        user.login = "******"
        mock_github_user.return_value = user
        views.auth.create_and_attach_oauth(self.user_settings, "testing acess token", "testing token type")

        user2 = AuthUserFactory()
        user2.add_addon('github')
        user2.save()
        user_settings2 = user2.get_addon('github')
        views.auth.create_and_attach_oauth(user_settings2, "testing access token", "testing token type")

        url = api_url_for("github_oauth_delete_user")
        self.app.delete(url, auth=self.user.auth)
        self.user_settings.reload()
        user_settings2.reload()
        assert_false(self.user_settings.oauth_token_type)
        assert_false(self.user_settings.oauth_access_token)
        assert_false(self.user_settings.github_user_name)
        assert_false(self.user_settings.oauth_settings)
        assert_true(user_settings2.oauth_settings)
        assert_equal(user_settings2.oauth_token_type, "testing token type")
        assert_equal(user_settings2.oauth_access_token, "testing access token")
        assert_equal(user_settings2.github_user_name, "testing user")
Beispiel #24
0
class TestDataverseRestrictions(DataverseAddonTestCase, OsfTestCase):

    def setUp(self):

        super(DataverseAddonTestCase, self).setUp()

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

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

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

        url = api_url_for('dataverse_set_config', pid=self.project._primary_key)
        params = {
            'dataverse': {'alias': 'ALIAS1'},
            'dataset': {'doi': 'doi:12.3456/DVN/00002'},
        }
        res = self.app.post_json(url, params, auth=self.contrib.auth,
                                 expect_errors=True)
        assert_equal(res.status_code, http.FORBIDDEN)
Beispiel #25
0
 def test_many_users_each_with_the_same_github(self):
     user = AuthUserFactory()
     user.add_addon('github')
     user.external_accounts.append(self.oauth_settings)
     user.save()
     results = AddonSnapshot().get_events()
     github_res = [res for res in results if res['provider']['name'] == 'github'][0]
     assert_equal(github_res['users']['total'], 2)
Beispiel #26
0
    def test_s3_set_bucket_no_auth(self):

        user = AuthUserFactory()
        user.add_addon("s3")
        self.project.add_contributor(user, save=True)
        url = self.project.api_url_for("s3_post_node_settings")
        res = self.app.post_json(url, {"s3_bucket": "hammertofall"}, auth=user.auth, expect_errors=True)
        assert_equal(res.status_code, http.BAD_REQUEST)
Beispiel #27
0
 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)
Beispiel #28
0
class TestGoogleDriveUtils(OsfTestCase):

    def setUp(self):
        super(TestGoogleDriveUtils, 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')
        oauth_settings = GoogleDriveOAuthSettingsFactory()
        self.user_settings.oauth_settings = oauth_settings
        self.node_settings.user_settings = self.user_settings
        self.node_settings.folder_id = '09120912'
        self.node_settings.folder_path = 'foo/bar'

        self.user_settings.save()
        self.node_settings.save()
        # Log user in
        self.app.authenticate(*self.user.auth)

    def test_serialize_settings_helper_returns_correct_urls(self):
        result = serialize_settings(self.node_settings, self.user)
        urls = result['urls']

        assert_equal(urls['files'], self.project.web_url_for('collect_file_trees'))
        assert_equal(urls['config'], self.project.api_url_for('googledrive_config_put'))
        assert_equal(urls['deauthorize'], self.project.api_url_for('googledrive_deauthorize'))
        assert_equal(urls['importAuth'], self.project.api_url_for('googledrive_import_user_auth'))
        # Includes endpoint for fetching folders only
        # NOTE: Querystring params are in camelCase
        assert_equal(urls['get_folders'], self.project.api_url_for('googledrive_folders'))

    def test_serialize_settings_helper_returns_correct_auth_info(self):
        self.user_settings.access_token = 'abc123'
        result = serialize_settings(self.node_settings, self.user)
        assert_equal(result['nodeHasAuth'], self.node_settings.has_auth)
        assert_true(result['userHasAuth'])
        assert_true(result['userIsOwner'])

    def test_serialize_settings_for_user_no_auth(self):
        no_addon_user = AuthUserFactory()
        result = serialize_settings(self.node_settings, no_addon_user)
        assert_false(result['userIsOwner'])
        assert_false(result['userHasAuth'])

    def test_googledrive_import_user_auth_returns_serialized_settings(self):
        self.node_settings.user_settings = None
        self.node_settings.save()
        url = api_url_for('googledrive_import_user_auth', pid=self.project._primary_key)
        res = self.app.put(url, auth=self.user.auth)
        self.project.reload()
        self.node_settings.reload()

        expected_result = serialize_settings(self.node_settings, self.user)
        result = res.json['result']
        assert_equal(result, expected_result)
Beispiel #29
0
class TestGoogleDriveUtils(OsfTestCase):

    def setUp(self):
        super(TestGoogleDriveUtils, 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')
        oauth_settings = GoogleDriveOAuthSettingsFactory()
        self.user_settings.oauth_settings = oauth_settings
        self.node_settings.user_settings = self.user_settings
        self.node_settings.folder_id = '09120912'
        self.node_settings.folder_path = 'foo/bar'

        self.user_settings.save()
        self.node_settings.save()
        # Log user in
        self.app.authenticate(*self.user.auth)

    def test_serialize_settings_helper_returns_correct_urls(self):
        result = serialize_settings(self.node_settings, self.user)
        urls = result['urls']

        assert_equal(urls['files'], self.project.web_url_for('collect_file_trees'))
        assert_equal(urls['config'], self.project.api_url_for('googledrive_config_put'))
        assert_equal(urls['deauthorize'], self.project.api_url_for('googledrive_deauthorize'))
        assert_equal(urls['importAuth'], self.project.api_url_for('googledrive_import_user_auth'))
        # Includes endpoint for fetching folders only
        # NOTE: Querystring params are in camelCase
        assert_equal(urls['get_folders'], self.project.api_url_for('googledrive_folders'))

    def test_serialize_settings_helper_returns_correct_auth_info(self):
        self.user_settings.access_token = 'abc123'
        result = serialize_settings(self.node_settings, self.user)
        assert_equal(result['nodeHasAuth'], self.node_settings.has_auth)
        assert_true(result['userHasAuth'])
        assert_true(result['userIsOwner'])

    def test_serialize_settings_for_user_no_auth(self):
        no_addon_user = AuthUserFactory()
        result = serialize_settings(self.node_settings, no_addon_user)
        assert_false(result['userIsOwner'])
        assert_false(result['userHasAuth'])

    def test_googledrive_import_user_auth_returns_serialized_settings(self):
        self.node_settings.user_settings = None
        self.node_settings.save()
        url = api_url_for('googledrive_import_user_auth', pid=self.project._primary_key)
        res = self.app.put(url, auth=self.user.auth)
        self.project.reload()
        self.node_settings.reload()

        expected_result = serialize_settings(self.node_settings, self.user)
        result = res.json['result']
        assert_equal(result, expected_result)
Beispiel #30
0
 def test_many_users_each_with_the_same_github(self):
     user = AuthUserFactory()
     user.add_addon('github')
     user.external_accounts.append(self.oauth_settings)
     user.save()
     results = AddonSnapshot().get_events()
     github_res = [
         res for res in results if res['provider']['name'] == 'github'
     ][0]
     assert_equal(github_res['users']['total'], 2)
Beispiel #31
0
    def test_s3_set_bucket_no_auth(self):

        user = AuthUserFactory()
        user.add_addon('s3')
        self.project.add_contributor(user, save=True)
        url = self.project.api_url_for('s3_set_config')
        res = self.app.put_json(url, {'s3_bucket': 'hammertofall'},
                                auth=user.auth,
                                expect_errors=True)
        assert_equal(res.status_code, http.FORBIDDEN)
Beispiel #32
0
 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']['total'], 2)
Beispiel #33
0
 def test_dropbox_get_share_emails_returns_error_if_not_authorizer(self):
     contrib = AuthUserFactory()
     contrib.add_addon('dropbox')
     contrib.save()
     self.project.add_contributor(contrib, auth=Auth(self.user))
     self.project.save()
     url = api_url_for('dropbox_get_share_emails', pid=self.project._primary_key)
     # Non-authorizing contributor sends request
     res = self.app.get(url, auth=contrib.auth, expect_errors=True)
     assert_equal(res.status_code, httplib.FORBIDDEN)
Beispiel #34
0
 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)
Beispiel #35
0
 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)
Beispiel #36
0
    def test_s3_set_bucket_no_auth(self):

        user = AuthUserFactory()
        user.add_addon('s3')
        self.project.add_contributor(user, save=True)
        url = self.project.api_url + 's3/settings/'
        res = self.app.post_json(url, {'s3_bucket': 'hammertofall'},
                                 auth=user.auth,
                                 expect_errors=True)
        assert_equal(res.status_code, http.BAD_REQUEST)
Beispiel #37
0
class TestAuthViews(OsfTestCase):

    def setUp(self):
        super(TestAuthViews, self).setUp()
        self.user = AuthUserFactory()
        # Log user in
        self.app.authenticate(*self.user.auth)

    def test_dropbox_oauth_start(self):
        url = api_url_for('dropbox_oauth_start_user')
        res = self.app.get(url)
        assert_is_redirect(res)
        assert_in('&force_reapprove=true', res.location)

    @mock.patch('website.addons.dropbox.views.auth.DropboxOAuth2Flow.finish')
    @mock.patch('website.addons.dropbox.views.auth.get_client_from_user_settings')
    def test_dropbox_oauth_finish(self, mock_get, mock_finish):
        mock_client = mock.MagicMock()
        mock_client.account_info.return_value = {'display_name': 'Mr. Drop Box'}
        mock_get.return_value = mock_client
        mock_finish.return_value = ('mytoken123', 'mydropboxid', 'done')
        url = api_url_for('dropbox_oauth_finish')
        res = self.app.get(url)
        assert_is_redirect(res)

    @mock.patch('website.addons.dropbox.client.DropboxClient.disable_access_token')
    def test_dropbox_oauth_delete_user(self, mock_disable_access_token):
        self.user.add_addon('dropbox')
        settings = self.user.get_addon('dropbox')
        settings.access_token = '12345abc'
        settings.save()
        assert_true(settings.has_auth)
        self.user.save()
        url = api_url_for('dropbox_oauth_delete_user')
        self.app.delete(url)
        settings.reload()
        assert_false(settings.has_auth)

    @mock.patch('website.addons.dropbox.client.DropboxClient.disable_access_token')
    def test_dropbox_oauth_delete_user_with_invalid_credentials(self, mock_disable_access_token):
        self.user.add_addon('dropbox')
        settings = self.user.get_addon('dropbox')
        settings.access_token = '12345abc'
        settings.save()
        assert_true(settings.has_auth)

        mock_response = mock.Mock()
        mock_response.status = 401
        mock_disable_access_token.side_effect = ErrorResponse(mock_response, "The given OAuth 2 access token doesn't exist or has expired.")

        self.user.save()
        url = api_url_for('dropbox_oauth_delete_user')
        self.app.delete(url)
        settings.reload()
        assert_false(settings.has_auth)
Beispiel #38
0
 def test_s3_set_bucket_already_authed(self):
     user = AuthUserFactory()
     user.add_addon("s3")
     user_settings = user.get_addon("s3")
     user_settings.access_key = "foo"
     user_settings.secret_key = "bar"
     user_settings.save()
     self.project.add_contributor(user, save=True)
     url = self.project.api_url_for("s3_post_node_settings")
     res = self.app.post_json(url, {"s3_bucket": "hammertofall"}, auth=user.auth, expect_errors=True)
     assert_equal(res.status_code, http.BAD_REQUEST)
Beispiel #39
0
    def test_s3_set_bucket_no_auth(self):

        user = AuthUserFactory()
        user.add_addon('s3')
        self.project.add_contributor(user, save=True)
        url = self.project.api_url + 's3/settings/'
        res = self.app.post_json(
            url, {'s3_bucket': 'hammertofall'}, auth=user.auth,
            expect_errors=True
        )
        assert_equal(res.status_code, http.BAD_REQUEST)
Beispiel #40
0
class TestAuthViews(OsfTestCase):
    def setUp(self):
        super(TestAuthViews, self).setUp()
        self.user = AuthUserFactory()
        # Log user in
        self.app.authenticate(*self.user.auth)

    def test_box_oauth_start(self):
        url = api_url_for('box_oauth_start_user')
        res = self.app.get(url)
        assert_is_redirect(res)

    @mock.patch('website.addons.box.views.auth.box_oauth_finish')
    @mock.patch('website.addons.box.views.auth.finish_auth')
    @mock.patch('website.addons.box.views.auth.BoxClient')
    def test_box_oauth_finish(self, mock_get, mock_finish, mock_oauth):
        mock_client = mock.MagicMock()
        mock_client.get_user_info.return_value = {
            'name': 'Mr. Box',
            'id': '1234567890'
        }
        mock_get.return_value = mock_client
        mock_finish.return_value = {
            'token_type': 'something',
            'access_token': 'something',
            'refresh_token': 'something'
        }
        mock_oauth.return_value = ('mytoken123', 'myboxid', 'done')
        url = api_url_for('box_oauth_finish')
        res = self.app.get(url)
        assert_is_redirect(res)

    @mock.patch('website.addons.box.views.auth.flash')
    def test_box_oauth_finish_cancelled(self, mock_flash):
        url = api_url_for('box_oauth_finish', error='User declined!')
        res = self.app.get(url)
        assert_is_redirect(res)
        mock_flash.assert_called_once()

    @mock.patch('website.addons.box.model.BoxOAuthSettings.revoke_access_token'
                )
    def test_box_oauth_delete_user(self, mock_disable_access_token):
        self.user.add_addon('box')
        settings = self.user.get_addon('box')
        oauth = BoxOAuthSettings(user_id='fa;l', access_token='a;lkjadl;kas')
        oauth.save()
        settings.oauth_settings = oauth
        settings.save()
        assert_true(settings.has_auth)
        self.user.save()
        url = api_url_for('box_oauth_delete_user')
        self.app.delete(url)
        settings.reload()
        assert_false(settings.has_auth)
Beispiel #41
0
    def test_s3_set_bucket_no_auth(self):

        user = AuthUserFactory()
        user.add_addon('s3')
        self.project.add_contributor(user, save=True)
        url = self.project.api_url_for('s3_set_config')
        res = self.app.put_json(
            url, {'s3_bucket': 'hammertofall'}, auth=user.auth,
            expect_errors=True
        )
        assert_equal(res.status_code, http.FORBIDDEN)
Beispiel #42
0
 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)
Beispiel #43
0
 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)
Beispiel #44
0
 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']['total'], 2)
Beispiel #45
0
 def test_s3_set_bucket_already_authed(self):
     user = AuthUserFactory()
     user.add_addon('s3')
     user_settings = user.get_addon('s3')
     user_settings.access_key = 'foo'
     user_settings.secret_key = 'bar'
     user_settings.save()
     self.project.add_contributor(user, save=True)
     url = self.project.api_url_for('s3_post_node_settings')
     res = self.app.post_json(url, {'s3_bucket': 'hammertofall'},
                              auth=user.auth,
                              expect_errors=True)
     assert_equal(res.status_code, http.BAD_REQUEST)
Beispiel #46
0
class TestRestrictions(BoxAddonTestCase):
    def setUp(self):
        super(BoxAddonTestCase, self).setUp()

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

        self.user.add_addon('box')
        settings = self.user.get_addon('box')
        settings.access_token = '12345abc'
        settings.last_refreshed = datetime.utcnow()
        settings.save()

        self.patcher = mock.patch(
            'website.addons.box.model.BoxNodeSettings.fetch_folder_name')
        self.patcher.return_value = 'foo bar/baz'
        self.patcher.start()

    @mock.patch('website.addons.box.model.BoxNodeSettings.has_auth')
    def test_restricted_hgrid_data_contents(self, mock_auth):
        mock_auth.__get__ = mock.Mock(return_value=False)

        # tries to access a parent folder
        url = self.project.api_url_for('box_list_folders', path='foo bar')
        res = self.app.get(url, auth=self.contrib.auth, expect_errors=True)
        assert_equal(res.status_code, httplib.FORBIDDEN)

    def test_restricted_config_contrib_no_addon(self):
        url = api_url_for('box_config_put', pid=self.project._primary_key)
        res = self.app.put_json(url, {'selected': {
            'path': 'foo'
        }},
                                auth=self.contrib.auth,
                                expect_errors=True)
        assert_equal(res.status_code, httplib.BAD_REQUEST)

    def test_restricted_config_contrib_not_owner(self):
        # Contributor has box auth, but is not the node authorizer
        self.contrib.add_addon('box')
        self.contrib.save()

        url = api_url_for('box_config_put', pid=self.project._primary_key)
        res = self.app.put_json(url, {'selected': {
            'path': 'foo'
        }},
                                auth=self.contrib.auth,
                                expect_errors=True)
        assert_equal(res.status_code, httplib.FORBIDDEN)
Beispiel #47
0
class TestAuthViews(OsfTestCase):

    def setUp(self):
        super(TestAuthViews, self).setUp()
        self.user = AuthUserFactory()
        # Log user in
        self.app.authenticate(*self.user.auth)

    def test_box_oauth_start(self):
        url = api_url_for('box_oauth_start_user')
        res = self.app.get(url)
        assert_is_redirect(res)

    @mock.patch('website.addons.box.views.auth.box_oauth_finish')
    @mock.patch('website.addons.box.views.auth.finish_auth')
    @mock.patch('website.addons.box.views.auth.BoxClient')
    def test_box_oauth_finish(self, mock_get, mock_finish, mock_oauth):
        mock_client = mock.MagicMock()
        mock_client.get_user_info.return_value = {'name': 'Mr. Box', 'id': '1234567890'}
        mock_get.return_value = mock_client
        mock_finish.return_value = {
            'token_type': 'something',
            'access_token': 'something',
            'refresh_token': 'something'
        }
        mock_oauth.return_value = ('mytoken123', 'myboxid', 'done')
        url = api_url_for('box_oauth_finish')
        res = self.app.get(url)
        assert_is_redirect(res)

    @mock.patch('website.addons.box.views.auth.flash')
    def test_box_oauth_finish_cancelled(self, mock_flash):
        url = api_url_for('box_oauth_finish', error='User declined!')
        res = self.app.get(url)
        assert_is_redirect(res)
        mock_flash.assert_called_once()

    @mock.patch('website.addons.box.model.BoxOAuthSettings.revoke_access_token')
    def test_box_oauth_delete_user(self, mock_disable_access_token):
        self.user.add_addon('box')
        settings = self.user.get_addon('box')
        oauth = BoxOAuthSettings(user_id='fa;l', access_token='a;lkjadl;kas')
        oauth.save()
        settings.oauth_settings = oauth
        settings.save()
        assert_true(settings.has_auth)
        self.user.save()
        url = api_url_for('box_oauth_delete_user')
        self.app.delete(url)
        settings.reload()
        assert_false(settings.has_auth)
Beispiel #48
0
    def test_import_auth_cant_write_node(self):
        ea = self.ExternalAccountFactory()
        user = AuthUserFactory()
        user.add_addon(self.ADDON_SHORT_NAME, auth=Auth(user))
        user.external_accounts.append(ea)
        user.save()

        node = ProjectFactory(creator=self.user)
        node.add_contributor(user, permissions=[permissions.READ], auth=self.auth, save=True)
        node.add_addon(self.ADDON_SHORT_NAME, auth=self.auth)
        node.save()
        url = node.api_url_for("{0}_import_auth".format(self.ADDON_SHORT_NAME))
        res = self.app.put_json(url, {"external_account_id": ea._id}, auth=user.auth, expect_errors=True)
        assert_equal(res.status_code, http.FORBIDDEN)
Beispiel #49
0
    def test_s3_set_bucket_already_authed(self):

        user = AuthUserFactory()
        user.add_addon('s3')
        user_settings = user.get_addon('s3')
        user_settings.access_key = 'foo'
        user_settings.secret_key = 'bar'
        user_settings.save()
        self.project.add_contributor(user, save=True)
        url = self.project.api_url + 's3/settings/'
        res = self.app.post_json(
            url, {'s3_bucket': 'hammertofall'}, auth=user.auth,
            expect_errors=True
        )
        assert_equal(res.status_code, http.BAD_REQUEST)
Beispiel #50
0
    def test_import_auth_cant_write_node(self):
        ea = self.ExternalAccountFactory()
        user = AuthUserFactory()
        user.add_addon(self.ADDON_SHORT_NAME, auth=Auth(user))
        user.external_accounts.append(ea)
        user.save()

        node = ProjectFactory(creator=self.user)
        node.add_contributor(user, permissions=[permissions.READ], auth=self.auth, save=True)
        node.add_addon(self.ADDON_SHORT_NAME, auth=self.auth)
        node.save()
        url = node.api_url_for('{0}_import_auth'.format(self.ADDON_SHORT_NAME))
        res = self.app.put_json(url, {
            'external_account_id': ea._id
        }, auth=user.auth, expect_errors=True)
        assert_equal(res.status_code, http.FORBIDDEN)
Beispiel #51
0
 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)
Beispiel #52
0
 def test_set_config_not_owner(self):
     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)
     assert_equal(res.json, {})
Beispiel #53
0
class TestRestrictions(DropboxAddonTestCase):
    def setUp(self):
        super(DropboxAddonTestCase, self).setUp()

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

        # Set shared folder
        self.node_settings.folder = 'foo bar/bar'
        self.node_settings.save()

    @mock.patch('website.addons.dropbox.client.DropboxClient.metadata')
    def test_restricted_hgrid_data_contents(self, mock_metadata):
        mock_metadata.return_value = mock_responses['metadata_list']

        # tries to access a parent folder
        url = self.project.api_url_for('dropbox_hgrid_data_contents',
                                       path='foo bar')
        res = self.app.get(url, auth=self.contrib.auth, expect_errors=True)
        assert_equal(res.status_code, httplib.FORBIDDEN)

    def test_restricted_config_contrib_no_addon(self):
        url = self.project.api_url_for('dropbox_config_put')
        res = self.app.put_json(url, {'selected': {
            'path': 'foo'
        }},
                                auth=self.contrib.auth,
                                expect_errors=True)
        assert_equal(res.status_code, httplib.BAD_REQUEST)

    def test_restricted_config_contrib_not_owner(self):
        # Contributor has dropbox auth, but is not the node authorizer
        self.contrib.add_addon('dropbox')
        self.contrib.save()

        url = self.project.api_url_for('dropbox_config_put')
        res = self.app.put_json(url, {'selected': {
            'path': 'foo'
        }},
                                auth=self.contrib.auth,
                                expect_errors=True)
        assert_equal(res.status_code, httplib.FORBIDDEN)
Beispiel #54
0
    def test_set_user_config(self, mock_connection):

        mock_connection.return_value = create_mock_connection()

        # Create a user with no settings
        user = AuthUserFactory()
        user.add_addon('dataverse')
        user_settings = user.get_addon('dataverse')

        url = api_url_for('dataverse_set_user_config')
        params = {'api_token': 'snowman-frosty'}

        # Post dataverse credentials
        self.app.post_json(url, params, auth=user.auth)
        user_settings.reload()

        # User settings have updated correctly
        assert_equal(user_settings.api_token, 'snowman-frosty')
Beispiel #55
0
    def test_serialize_settings_helper_non_owner(self, mock_connection):
        mock_connection.return_value = create_mock_connection()

        # Non-owner user without add-on
        serializer = DataverseSerializer(node_settings=self.node_settings)
        result = serializer.serialized_node_settings
        assert_equal(result['nodeHasAuth'], self.node_settings.has_auth)
        assert_false(result['userHasAuth'])
        assert_false(result['userIsOwner'])

        # Non-owner user with add-on
        stranger = AuthUserFactory()
        stranger.add_addon('dataverse')
        stranger.external_accounts.append(create_external_account())
        serializer.user_settings = stranger.get_addon('dataverse')
        result = serializer.serialized_node_settings
        assert_equal(result['nodeHasAuth'], self.node_settings.has_auth)
        assert_true(result['userHasAuth'])
        assert_false(result['userIsOwner'])
Beispiel #56
0
    def test_serialize_settings_helper_non_owner(self, mock_connection):
        mock_connection.return_value = create_mock_connection()

        # Non-owner user without add-on
        stranger = AuthUserFactory()
        result = serialize_settings(self.node_settings, stranger)
        assert_equal(result['nodeHasAuth'], self.node_settings.has_auth)
        assert_false(result['userHasAuth'])
        assert_false(result['userIsOwner'])

        # Non-owner user with add-on
        stranger.add_addon('dataverse')
        stranger_settings = stranger.get_addon('dataverse')
        stranger_settings.api_token = 'foo-bar'
        stranger_settings.save()
        result = serialize_settings(self.node_settings, stranger)
        assert_equal(result['nodeHasAuth'], self.node_settings.has_auth)
        assert_true(result['userHasAuth'])
        assert_false(result['userIsOwner'])
Beispiel #57
0
class TestDropboxIntegration(OsfTestCase):
    def setUp(self):
        super(TestDropboxIntegration, self).setUp()
        self.user = AuthUserFactory()
        # User is logged in
        self.app.authenticate(*self.user.auth)

    def test_cant_start_oauth_if_already_authorized(self):
        # User already has dropbox authorized
        self.user.add_addon('dropbox')
        self.user.save()
        settings = self.user.get_addon('dropbox')
        settings.access_token = 'abc123foobarbaz'
        settings.save()
        assert_true(self.user.get_addon('dropbox').has_auth)
        # Tries to start oauth again
        url = api_url_for('dropbox_oauth_start_user')
        res = self.app.get(url).follow()

        # Is redirected back to settings page
        assert_equal(res.request.path, web_url_for('user_addons'))
Beispiel #58
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, 400)

    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)