def test_revoke_badge_reason(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) ret = self.app.post_json(revoke, { 'id': assertion._id, 'reason': 'Is a loser' }, auth=self.user.auth) self.project.reload() self.user_settings.reload() assertion.reload() assert_equals(ret.status_int, 200) assert_true(self.project.badgeassertion__awarded[0]._id, assertion._id) assert_true(assertion._id in self.user_settings.revocation_list) assert_equals(len(self.user_settings.revocation_list), 1) assert_true(assertion.revoked) assert_equals(self.user_settings.revocation_list[assertion._id], 'Is a loser')
def dataverse_user_config_get(user_addon, auth, **kwargs): """View for getting a JSON representation of the logged-in user's Dataverse user settings. """ try: connection = connect_from_settings_or_401(user_addon) except HTTPError as error: if error.code == 401: connection = None else: raise urls = { 'create': api_url_for('dataverse_set_user_config'), 'delete': api_url_for('dataverse_delete_user'), 'apiToken': 'https://{0}/account/apitoken'.format(HOST), } return { 'result': { 'connected': connection is not None, 'userHasAuth': user_addon.has_auth, 'apiToken': user_addon.api_token, 'urls': urls }, }, http.OK
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)
def box_user_config_get(user_addon, auth, **kwargs): """View for getting a JSON representation of the logged-in user's Box user settings. """ urls = { 'create': api_url_for('box_oauth_start_user'), 'delete': api_url_for('box_oauth_delete_user') } valid_credentials = True if user_addon.has_auth: try: client = get_client_from_user_settings(user_addon) client.get_user_info() except BoxClientException: valid_credentials = False return { 'result': { 'urls': urls, 'boxName': user_addon.username, 'userHasAuth': user_addon.has_auth, 'validCredentials': valid_credentials, 'nNodesAuthorized': len(user_addon.nodes_authorized), }, }
def test_revoke_badge_no_addon(self): badgeid = self.user_settings.badges[0]._id initnum = get_node_badges(self.project).count() 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, get_node_badges(self.project).count()) assertion = get_node_badges(self.project)[0] revoke = api_url_for('revoke_badge', pid=self.project._id) self.user.delete_addon('badges') self.user.save() self.user.reload() ret = self.app.post_json(revoke, { 'id': assertion._id, 'reason': '' }, auth=self.user.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(get_node_badges(self.project)[0]._id, assertion._id) assert_false(assertion._id in self.user_settings.revocation_list)
def dropbox_user_config_get(user_addon, auth, **kwargs): """View for getting a JSON representation of the logged-in user's Dropbox user settings. """ urls = { 'create': api_url_for('dropbox_oauth_start_user'), 'delete': api_url_for('dropbox_oauth_delete_user') } info = user_addon.dropbox_info valid_credentials = True if user_addon.has_auth: try: client = get_client_from_user_settings(user_addon) client.account_info() except ErrorResponse as error: if error.status == 401: valid_credentials = False else: HTTPError(http.BAD_REQUEST) return { 'result': { 'userHasAuth': user_addon.has_auth, 'validCredentials': valid_credentials, 'dropboxName': info['display_name'] if info else None, 'nNodesAuthorized': len(user_addon.nodes_authorized), 'urls': urls }, }, http.OK
def test_revoke_bad_aid(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) ret = self.app.post_json(revoke, { 'id': 'Im a bad id :D', 'reason': '' }, auth=self.user.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)
def serialize_urls(user_addon): return { 'enable': api_url_for('twofactor_enable'), 'disable': api_url_for('twofactor_disable'), 'settings': api_url_for('twofactor_settings_put'), 'otpauth': user_addon.otpauth_url if user_addon else '', }
def test_change_subscription_to_adopt_parent_subscription_removes_user(self): payload = { 'id': self.node._id, 'event': 'comments', 'notification_type': 'email_transactional' } url = api_url_for('configure_subscription') self.app.post_json(url, payload, auth=self.node.creator.auth) # check that subscription was created event_id = self.node._id + '_' + 'comments' s = NotificationSubscription.find_one(Q('_id', 'eq', event_id)) # change subscription to adopt_parent new_payload = { 'id': self.node._id, 'event': 'comments', 'notification_type': 'adopt_parent' } url = api_url_for('configure_subscription') self.app.post_json(url, new_payload, auth=self.node.creator.auth) s.reload() # assert that user is removed from the subscription entirely for n in constants.NOTIFICATION_TYPES: assert_false(self.node.creator in getattr(s, n))
def test_create_new_subscription(self): payload = { 'id': self.node._id, 'event': 'comments', 'notification_type': 'email_transactional' } url = api_url_for('configure_subscription') self.app.post_json(url, payload, auth=self.node.creator.auth) # check that subscription was created event_id = self.node._id + '_' + 'comments' s = NotificationSubscription.find_one(Q('_id', 'eq', event_id)) # check that user was added to notification_type field assert_equal(payload['id'], s.owner._id) assert_equal(payload['event'], s.event_name) assert_in(self.node.creator, getattr(s, payload['notification_type'])) # change subscription new_payload = { 'id': self.node._id, 'event': 'comments', 'notification_type': 'email_digest' } url = api_url_for('configure_subscription') self.app.post_json(url, new_payload, auth=self.node.creator.auth) s.reload() assert_false(self.node.creator in getattr(s, payload['notification_type'])) assert_in(self.node.creator, getattr(s, new_payload['notification_type']))
def test_dropbox_user_config_get_returns_correct_urls(self): url = api_url_for('dropbox_user_config_get') res = self.app.get(url, auth=self.user.auth) assert_equal(res.status_code, 200) # The JSONified URLs result urls = res.json['result']['urls'] assert_equal(urls['delete'], api_url_for('dropbox_oauth_delete_user')) assert_equal(urls['create'], api_url_for('dropbox_oauth_start_user'))
def test_drive_user_config_get_returns_correct_urls(self): self.user.add_addon('googledrive') url = api_url_for('googledrive_user_config_get', Auth(self.user)) res = self.app.get(url) assert_equal(res.status_code, 200) result = res.json['result']['urls'] assert_true(result['create'], api_url_for('googledrive_oauth_start_user')) assert_true(result['delete'], api_url_for('googledrive_oauth_delete_user'))
def test_drive_user_config_get_returns_correct_urls(self): self.user.add_addon("googledrive") url = api_url_for("googledrive_user_config_get", Auth(self.user)) res = self.app.get(url) assert_equal(res.status_code, 200) result = res.json["result"]["urls"] assert_true(result["create"], api_url_for("googledrive_oauth_start_user")) assert_true(result["delete"], api_url_for("googledrive_oauth_delete_user"))
def test_dropbox_user_config_get_returns_correct_urls(self, mock_account_info): mock_account_info.return_value = {'display_name': 'Mr. Drop Box'} url = api_url_for('dropbox_user_config_get') res = self.app.get(url, auth=self.user.auth) assert_equal(res.status_code, 200) # The JSONified URLs result urls = res.json['result']['urls'] assert_equal(urls['delete'], api_url_for('dropbox_oauth_delete_user')) assert_equal(urls['create'], api_url_for('dropbox_oauth_start_user'))
def test_dropbox_config_get(self): self.user_settings.save() url = api_url_for('dropbox_config_get', pid=self.project._primary_key) res = self.app.get(url, auth=self.user.auth) assert_equal(res.status_code, 200) result = res.json['result'] assert_equal(result['ownerName'], self.user_settings.owner.fullname) assert_equal(result['urls']['config'], api_url_for('dropbox_config_put', pid=self.project._primary_key))
def test_serialize_settings_helper_returns_correct_urls(self, mock_connection): mock_connection.return_value = create_mock_connection() # result = urls = self.serializer.serialized_urls assert_equal(urls['create'], api_url_for('dataverse_add_user_account')) assert_equal(urls['set'], self.project.api_url_for('dataverse_set_config')) assert_equal(urls['importAuth'], self.project.api_url_for('dataverse_add_user_auth')) assert_equal(urls['deauthorize'], self.project.api_url_for('dataverse_remove_user_auth')) assert_equal(urls['getDatasets'], self.project.api_url_for('dataverse_get_datasets')) assert_equal(urls['datasetPrefix'], 'http://dx.doi.org/') assert_equal(urls['dataversePrefix'], 'http://{0}/dataverse/'.format(self.host)) assert_equal(urls['accounts'], api_url_for('dataverse_get_user_accounts'))
def dataverse_user_config_get(user_addon, **kwargs): """View for getting a JSON representation of the logged-in user's Dataverse user settings. """ return { 'result': { 'userHasAuth': user_addon.has_auth, 'urls': { 'create': api_url_for('dataverse_add_user_account'), 'accounts': api_url_for('dataverse_get_user_accounts'), }, 'hosts': DEFAULT_HOSTS, }, }, http.OK
def addon_serialized_urls(self): node = self.node_settings.owner external_account = self.node_settings.external_account host = external_account.oauth_key if external_account else '' return { 'create': api_url_for('dataverse_add_user_account'), 'set': node.api_url_for('dataverse_set_config'), 'importAuth': node.api_url_for('dataverse_import_auth'), 'deauthorize': node.api_url_for('dataverse_deauthorize_node'), 'getDatasets': node.api_url_for('dataverse_get_datasets'), 'datasetPrefix': 'https://doi.org/', 'dataversePrefix': 'http://{0}/dataverse/'.format(host), 'accounts': api_url_for('dataverse_account_list'), }
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']))
def test_dataverse_root_not_published(self, mock_files, mock_connection, mock_text): mock_connection.return_value = create_mock_connection() mock_files.return_value = [] mock_text.return_value = 'Do you want to publish?' self.project.set_privacy('public') self.project.save() alias = self.node_settings.dataverse_alias doi = self.node_settings.dataset_doi external_account = create_external_account() self.user.external_accounts.add(external_account) self.user.save() self.node_settings.set_auth(external_account, self.user) self.node_settings.dataverse_alias = alias self.node_settings.dataset_doi = doi self.node_settings.save() url = api_url_for('dataverse_root_folder', pid=self.project._primary_key) # Contributor gets draft, no options res = self.app.get(url, auth=self.user.auth) assert_true(res.json[0]['permissions']['edit']) assert_false(res.json[0]['hasPublishedFiles']) assert_equal(res.json[0]['version'], 'latest') # Non-contributor gets nothing user2 = AuthUserFactory() res = self.app.get(url, auth=user2.auth) assert_equal(res.json, [])
def test_set_config_no_dataset(self, mock_connection): mock_connection.return_value = self.connection num_old_logs = self.project.logs.count() url = api_url_for('dataverse_set_config', pid=self.project._primary_key) params = { 'dataverse': {'alias': 'ALIAS3'}, 'dataset': {}, # The dataverse has no datasets } # Select a different dataset res = self.app.post_json(url, params, auth=self.user.auth, expect_errors=True) self.node_settings.reload() # Old settings did not change assert_equal(res.status_code, http.BAD_REQUEST) assert_equal(self.node_settings.dataverse_alias, 'ALIAS2') assert_equal(self.node_settings.dataset, 'Example (DVN/00001)') assert_equal(self.node_settings.dataset_doi, 'doi:12.3456/DVN/00001') # Nothing was logged self.project.reload() assert_equal(self.project.logs.count(), num_old_logs)
def test_googledrive_oauth_start(self, mock_auth_client_start): url = api_url_for('googledrive_oauth_start_user', Auth(self.user)) authorization_url = 'https://fake.domain/' state = 'secure state' mock_auth_client_start.return_value = (authorization_url, state) res = self.app.post(url) assert_true(res.json['url'], authorization_url)
def test_cannot_remove_another_user_email(self): user1 = AuthUserFactory() user2 = AuthUserFactory() url = api_url_for('update_user') header = {'id': user1.username, 'emails': [{'address': user1.username}]} res = self.app.put_json(url, header, auth=user2.auth, expect_errors=True) assert_equal(res.status_code, 403)
def test_s3_remove_user_settings_none(self): self.user_settings.access_key = None self.user_settings.secret_key = None self.user_settings.save() url = api_url_for('s3_delete_user_settings') self.app.delete(url, auth=self.user.auth) self.user_settings.reload()
def test_create_badge_empty_data(self, img_proc): img_proc.return_value = 'temp.png' url = api_url_for('create_badge') badge = create_badge_dict() badge['imageurl'] = '' ret = self.app.post_json(url, badge, auth=self.user.auth, expect_errors=True) assert_equals(ret.status_int, 400)
def test_get_metaschemas(self): url = api_url_for('get_metaschemas') res = self.app.get(url).json assert_equal( len(res['meta_schemas']), MetaSchema.objects.filter(active=True, schema_version=LATEST_SCHEMA_VERSION).count() )
def test_googledrive_oauth_start(self, mock_auth_client_start): url = api_url_for('googledrive_oauth_start_user') authorization_url = 'https://fake.domain/' state = 'secure state' mock_auth_client_start.return_value = (authorization_url, state) res = self.app.get(url, auth=self.user.auth) assert_true(res.headers['location'], authorization_url)
def test_create_badge_cant_issue(self, img_proc): img_proc.return_value = 'temp.png' self.user.delete_addon('badges') url = api_url_for('create_badge') badge = create_badge_dict() ret = self.app.post_json(url, badge, auth=self.user.auth, expect_errors=True) assert_equals(ret.status_int, 400)
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")
def test_update_user_timezone_offset(self): assert_equal(self.user.timezone, 'Etc/UTC') payload = {'timezone': 'America/New_York'} url = api_url_for('update_user', uid=self.user._id) self.app.put_json(url, payload, auth=self.user.auth) self.user.reload() assert_equal(self.user.timezone, 'America/New_York')
def test_disconnect(self): # Disconnect an external account from a user external_account = ExternalAccountFactory( provider='mock2', provider_id='mock_provider_id', provider_name='Mock Provider', ) self.user.external_accounts.add(external_account) self.user.save() # If the external account isn't attached, this test has no meaning assert_equal(ExternalAccount.objects.all().count(), 1) assert_in( external_account, self.user.external_accounts.all(), ) response = self.app.delete(api_url_for( 'oauth_disconnect', external_account_id=external_account._id), auth=self.user.auth) # Request succeeded assert_equal( response.status_code, http.OK, ) self.user.reload() # external_account.reload() # External account has been disassociated with the user assert_not_in( external_account, self.user.external_accounts.all(), ) # External account is still in the database assert_equal(ExternalAccount.objects.all().count(), 1)
def test_integration_inactive(self, mock_send_mail): conference = ConferenceFactory(active=False) fullname = 'John Deacon' username = '******' title = 'good songs' body = 'dragon on my back' recipient = '{0}{1}[email protected]'.format( 'test-' if settings.DEV_MODE else '', conference.endpoint, ) res = self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token': 'secret', 'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(fullname, username), 'recipient': recipient, 'subject': title, 'stripped-text': body, }, expect_errors=True, ) assert_equal(res.status_code, 406) call_args, call_kwargs = mock_send_mail.call_args assert_equal(call_args, (username, views.CONFERENCE_INACTIVE)) assert_equal(call_kwargs['fullname'], fullname) assert_equal_urls( call_kwargs['presentations_url'], web_url_for('conference_view', _absolute=True), )
def test_create_conference_node_with_same_name_as_existing_node(self, mock_upload, mock_send_mail): conference = ConferenceFactory() user = UserFactory() title = 'Long Live Greg' ProjectFactory(creator=user, title=title) body = 'Greg is a good plant' content = 'Long may they reign.' recipient = '{0}{1}[email protected]'.format( 'test-' if settings.DEV_MODE else '', conference.endpoint, ) self.app.post( api_url_for('meeting_hook'), { 'X-Mailgun-Sscore': 0, 'timestamp': '123', 'token': 'secret', 'signature': hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format('123', 'secret'), digestmod=hashlib.sha256, ).hexdigest(), 'attachment-count': '1', 'X-Mailgun-Sscore': 0, 'from': '{0} <{1}>'.format(user.fullname, user.username), 'recipient': recipient, 'subject': title, 'stripped-text': body, }, upload_files=[ ('attachment-1', 'attachment-1', content), ], ) assert AbstractNode.objects.filter(title=title, creator=user).count() == 2 assert mock_upload.called assert mock_send_mail.called
def search_share_atom(**kwargs): q = request.args.get('q', '*') sort = request.args.get('sort', 'dateUpdated') # we want the results per page to be constant between pages # TODO - move this functionality into build_query in util try: page = (int(request.args.get('page', 1)) - 1) * RESULTS_PER_PAGE except ValueError: page = 1 if page < 1: page = 1 query = build_query(q, size=RESULTS_PER_PAGE, start=page, sort=sort) try: search_results = search.search_share(query) except MalformedQueryError: raise HTTPError(http.BAD_REQUEST) except IndexNotFoundError: search_results = { 'count': 0, 'results': [] } atom_url = api_url_for('search_share_atom', _xml=True, _absolute=True) return util.create_atom_feed( name='SHARE', data=search_results['results'], query=q, size=RESULTS_PER_PAGE, start=page, url=atom_url, to_atom=share_search.to_atom )
def test_dataverse_root_not_released(self, mock_files, mock_request, mock_connection): mock_connection.return_value = create_mock_connection() mock_request.referrer = 'some_url/files/' mock_request.args = {'state': 'released'} mock_files.return_value = [] self.project.set_privacy('public') self.project.save() url = api_url_for('dataverse_root_folder_public', pid=self.project._primary_key) # Contributor gets draft, no options res = self.app.get(url, auth=self.user.auth) assert_in('draft', res.json[0]['urls']['fetch']) assert_true(res.json[0]['permissions']['edit']) assert_not_in('select', res.json[0]['extra']) # Non-contributor gets nothing user2 = AuthUserFactory() res = self.app.get(url, auth=user2.auth) assert_equal(res.json, [])
def test_cannnot_add_email_for_another_user(self): user1 = AuthUserFactory() user2 = AuthUserFactory() email = '*****@*****.**' url = api_url_for('update_user') header = { 'id': user1.username, 'emails': [{ 'address': user1.username, 'primary': True, 'confirmed': True }, { 'address': email, 'primary': False, 'confirmed': False }] } res = self.app.put_json(url, header, auth=user2.auth, expect_errors=True) assert_equal(res.status_code, 403)
def test_googledrive_oauth_finish_user_only(self, mock_session, mock_auth_client_finish, mock_auth_client_userinfo): user_no_addon = AuthUserFactory() state = '1234' mock_session.data = { 'googledrive_auth_state': state, } mock_auth_client_finish.return_value = { 'access_token': '1111', 'refresh_token': '2222', 'expires_at': time.time() + 3600, } mock_auth_client_userinfo.return_value = { 'sub': 'unique id', 'name': 'test-user', } url = api_url_for('googledrive_oauth_finish', user_no_addon.auth, code='1234', state=state) res = self.app.get(url) assert_is_redirect(res)
def test_dataverse_root_draft(self, mock_files, mock_request, mock_connection): mock_connection.return_value = create_mock_connection() mock_request.referrer = 'some_url/files/' mock_request.args = {'state': 'draft'} mock_files.return_value = ['mock_file'] self.project.set_privacy('public') self.project.save() url = api_url_for('dataverse_root_folder_public', pid=self.project._primary_key) # Contributor can select between states, current state is correct res = self.app.get(url, auth=self.user.auth) assert_in('draft', res.json[0]['urls']['fetch']) assert_true(res.json[0]['permissions']['edit']) assert_true(res.json[0]['hasReleasedFiles']) # Non-contributor gets released version, no options user2 = AuthUserFactory() res = self.app.get(url, auth=user2.auth) assert_in('released', res.json[0]['urls']['fetch'])
def test_sign_up_twice_sends_two_confirmation_emails_only(self, mock_mail): # Regression test for https://openscience.atlassian.net/browse/OSF-7060 url = api_url_for('register_user') sign_up_data = { 'fullName': 'Julius Caesar', 'email1': '*****@*****.**', 'email2': '*****@*****.**', 'password': '******' } self.app.post_json(url, sign_up_data) assert_equal(len(mock_mail.call_args_list), 1) args, kwargs = mock_mail.call_args assert_equal( args, ('*****@*****.**', mails.INITIAL_CONFIRM_EMAIL, 'html')) self.app.post_json(url, sign_up_data) assert_equal(len(mock_mail.call_args_list), 2) args, kwargs = mock_mail.call_args assert_equal( args, ('*****@*****.**', mails.INITIAL_CONFIRM_EMAIL, 'html'))
def finish_auth(node): """View helper for finishing the Dropbox Oauth2 flow. Returns the access_token, dropbox_id, and url_state. Handles various errors that may be raised by the Dropbox client. """ try: access_token, dropbox_id, url_state = get_auth_flow().finish( request.args) except DropboxOAuth2Flow.BadRequestException: raise HTTPError(http.BAD_REQUEST) except DropboxOAuth2Flow.BadStateException: # Start auth flow again return redirect(api_url_for('dropbox_oauth_start')) except DropboxOAuth2Flow.CsrfException: raise HTTPError(http.FORBIDDEN) except DropboxOAuth2Flow.NotApprovedException: # User canceled flow if node: return redirect(node.web_url_for('node_setting')) return redirect(web_url_for('user_addons')) except DropboxOAuth2Flow.ProviderException: raise HTTPError(http.FORBIDDEN) return AuthResult(access_token, dropbox_id, url_state)
def addon_serialized_urls(self): node = self.node_settings.owner return { 'auth': api_url_for('oauth_connect', service_name='box'), 'importAuth': node.api_url_for('box_add_user_auth'), 'files': node.web_url_for('collect_file_trees'), 'folders': node.api_url_for('box_folder_list'), 'config': node.api_url_for('box_set_config'), 'emails': node.api_url_for('box_get_share_emails'), 'share': 'https://app.box.com/files/0/f/{0}'.format( self.node_settings.folder_id), 'deauthorize': node.api_url_for('box_remove_user_auth'), 'accounts': node.api_url_for('box_get_user_settings'), }
def test_oauth_callback_without_node(self, mock_get_token, mock_github_user): mock_get_token.return_value = { "access_token": "testing access token", "token_type": "testing token type", "scope": ["repo"] } user = mock.Mock() user.id = "testing user id" user.login = "******" mock_github_user.return_value = user url = api_url_for('github_oauth_callback', uid=self.user._id) res = self.app.get(url, {"code": "12345"}, auth=self.user.auth) self.user_settings.reload() assert_true(res.status_code, 302) assert_in("/settings/addons/", res.location) assert_true(self.user_settings.oauth_settings) assert_equal(self.user_settings.oauth_access_token, "testing access token") assert_equal(self.user_settings.oauth_token_type, "testing token type") assert_equal(self.user_settings.github_user_name, "testing user") assert_equal(self.user_settings.oauth_settings.github_user_id, "testing user id")
def test_delete_user(self): url = api_url_for('dataverse_delete_user') # User without add-on can't delete user2 = AuthUserFactory() res = self.app.delete_json(url, auth=user2.auth, expect_errors=True) assert_equal(res.status_code, http.BAD_REQUEST) self.user_settings.reload() assert_true(self.user_settings.api_token) # Aurthoized user can delete self.app.delete_json(url, auth=self.user.auth) # User is no longer authorized self.user_settings.reload() assert_false(self.user_settings.api_token) # User's authorized nodes are now deauthorized self.node_settings.reload() assert_false(self.node_settings.dataverse_alias) assert_false(self.node_settings.dataverse) assert_false(self.node_settings.dataset_doi) assert_false(self.node_settings.dataset) assert_false(self.node_settings.user_settings)
def test_delete_external_account_not_owner(self): other_user = AuthUserFactory() url = api_url_for('oauth_disconnect', external_account_id=self.external_account._id) res = self.app.delete(url, auth=other_user.auth, expect_errors=True) assert_equal(res.status_code, http.FORBIDDEN)
def test_account_list_not_authorized(self): url = api_url_for('{0}_account_list'.format(self.ADDON_SHORT_NAME)) res = self.app.get(url, auth=None, expect_errors=True) assert_equal(res.status_code, http.FOUND)
def test_account_list_single(self): url = api_url_for('{0}_account_list'.format(self.ADDON_SHORT_NAME)) res = self.app.get(url, auth=self.user.auth) assert_equal(res.status_code, http.OK) assert_in('accounts', res.json) assert_equal(len(res.json['accounts']), 1)
def verify(self, vtype='hosted'): return { 'type': 'hosted', 'url': api_url_for('get_assertion_json', _absolute=True, aid=self._id) }
def test_get_metaschemas(self): url = api_url_for('get_metaschemas') res = self.app.get(url).json assert_equal(len(res['meta_schemas']), RegistrationSchema.objects.get_latest_versions().count())
def test_api_url_for(self): with self.app.test_request_context(): assert api_url_for('dummy_view', pid='123') == '/api/v1/123/'
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()
def test_get_metaschemas(self): url = api_url_for('get_metaschemas') res = self.app.get(url).json assert_equal(len(res['meta_schemas']), len(ACTIVE_META_SCHEMAS))
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)
def test_restricted_get_revisions(self): path = 'foo bar/baz.rst' url = api_url_for('dropbox_get_revisions', path=path, pid=self.project._primary_key) 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('dropbox_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_search_views(self): #Test search contributor url = api_url_for('search_contributor') res = self.app.get(url, {'query': self.contrib.fullname}) assert_equal(res.status_code, 200) result = res.json['users'] assert_equal(len(result), 1) brian = result[0] assert_equal(brian['fullname'], self.contrib.fullname) assert_in('profile_image_url', brian) assert_equal(brian['registered'], self.contrib.is_registered) assert_equal(brian['active'], self.contrib.is_active) #Test search pagination res = self.app.get(url, {'query': 'fr'}) assert_equal(res.status_code, 200) result = res.json['users'] pages = res.json['pages'] page = res.json['page'] assert_equal(len(result), 5) assert_equal(pages, 3) assert_equal(page, 0) #Test default page 1 res = self.app.get(url, {'query': 'fr', 'page': 1}) assert_equal(res.status_code, 200) result = res.json['users'] page = res.json['page'] assert_equal(len(result), 5) assert_equal(page, 1) #Test default page 2 res = self.app.get(url, {'query': 'fr', 'page': 2}) assert_equal(res.status_code, 200) result = res.json['users'] page = res.json['page'] assert_equal(len(result), 4) assert_equal(page, 2) #Test smaller pages res = self.app.get(url, {'query': 'fr', 'size': 5}) assert_equal(res.status_code, 200) result = res.json['users'] pages = res.json['pages'] page = res.json['page'] assert_equal(len(result), 5) assert_equal(page, 0) assert_equal(pages, 3) #Test smaller pages page 2 res = self.app.get(url, { 'query': 'fr', 'page': 2, 'size': 5, }) assert_equal(res.status_code, 200) result = res.json['users'] pages = res.json['pages'] page = res.json['page'] assert_equal(len(result), 4) assert_equal(page, 2) assert_equal(pages, 3) #Test search projects url = '/search/' res = self.app.get(url, {'q': self.project.title}) assert_equal(res.status_code, 200) #Test search node res = self.app.post_json(api_url_for('search_node'), {'query': self.project.title}, auth=factories.AuthUserFactory().auth) assert_equal(res.status_code, 200) #Test search node includePublic true res = self.app.post_json(api_url_for('search_node'), { 'query': 'a', 'includePublic': True }, auth=self.user_one.auth) node_ids = [node['id'] for node in res.json['nodes']] assert_in(self.project_private_user_one._id, node_ids) assert_in(self.project_public_user_one._id, node_ids) assert_in(self.project_public_user_two._id, node_ids) assert_not_in(self.project_private_user_two._id, node_ids) #Test search node includePublic false res = self.app.post_json(api_url_for('search_node'), { 'query': 'a', 'includePublic': False }, auth=self.user_one.auth) node_ids = [node['id'] for node in res.json['nodes']] assert_in(self.project_private_user_one._id, node_ids) assert_in(self.project_public_user_one._id, node_ids) assert_not_in(self.project_public_user_two._id, node_ids) assert_not_in(self.project_private_user_two._id, node_ids) #Test search user url = '/api/v1/search/user/' res = self.app.get(url, {'q': 'Umwali'}) assert_equal(res.status_code, 200) assert_false(res.json['results']) user_one = factories.AuthUserFactory(fullname='Joe Umwali') user_two = factories.AuthUserFactory(fullname='Joan Uwase') res = self.app.get(url, {'q': 'Umwali'}) assert_equal(res.status_code, 200) assert_equal(len(res.json['results']), 1) assert_false(res.json['results'][0]['social']) user_one.social = { 'github': user_one.given_name, 'twitter': user_one.given_name, 'ssrn': user_one.given_name } user_one.save() res = self.app.get(url, {'q': 'Umwali'}) assert_equal(res.status_code, 200) assert_equal(len(res.json['results']), 1) assert_not_in('Joan', res.body) assert_true(res.json['results'][0]['social']) assert_equal(res.json['results'][0]['names']['fullname'], user_one.fullname) assert_equal(res.json['results'][0]['social']['github'], 'http://github.com/{}'.format(user_one.given_name)) assert_equal(res.json['results'][0]['social']['twitter'], 'http://twitter.com/{}'.format(user_one.given_name)) assert_equal( res.json['results'][0]['social']['ssrn'], 'http://papers.ssrn.com/sol3/cf_dev/AbsByAuth.cfm?per_id={}'. format(user_one.given_name)) user_two.social = { 'profileWebsites': ['http://me.com/{}'.format(user_two.given_name)], 'orcid': user_two.given_name, 'linkedIn': user_two.given_name, 'scholar': user_two.given_name, 'impactStory': user_two.given_name, 'baiduScholar': user_two.given_name } user_two.save() user_three = factories.AuthUserFactory(fullname='Janet Umwali') user_three.social = { 'github': user_three.given_name, 'ssrn': user_three.given_name } user_three.save() res = self.app.get(url, {'q': 'Umwali'}) assert_equal(res.status_code, 200) assert_equal(len(res.json['results']), 2) assert_true(res.json['results'][0]['social']) assert_true(res.json['results'][1]['social']) assert_not_equal(res.json['results'][0]['social']['ssrn'], res.json['results'][1]['social']['ssrn']) assert_not_equal(res.json['results'][0]['social']['github'], res.json['results'][1]['social']['github']) res = self.app.get(url, {'q': 'Uwase'}) assert_equal(res.status_code, 200) assert_equal(len(res.json['results']), 1) assert_true(res.json['results'][0]['social']) assert_not_in('ssrn', res.json['results'][0]['social']) assert_equal(res.json['results'][0]['social']['profileWebsites'][0], 'http://me.com/{}'.format(user_two.given_name)) assert_equal( res.json['results'][0]['social']['impactStory'], 'https://impactstory.org/u/{}'.format(user_two.given_name)) assert_equal(res.json['results'][0]['social']['orcid'], 'http://orcid.org/{}'.format(user_two.given_name)) assert_equal( res.json['results'][0]['social']['baiduScholar'], 'http://xueshu.baidu.com/scholarID/{}'.format(user_two.given_name)) assert_equal(res.json['results'][0]['social']['linkedIn'], 'https://www.linkedin.com/{}'.format(user_two.given_name)) assert_equal( res.json['results'][0]['social']['scholar'], 'http://scholar.google.com/citations?user={}'.format( user_two.given_name))
def test_cancelled_oauth_request_from_node_settings_page_redirects_correctly(self): res = self.app.get(api_url_for('figshare_oauth_callback', uid=self.user._id, nid=self.project._id), auth=self.user.auth) assert_equal(res.status_code, 302) assert_urls_equal(res.headers['location'], self.project.web_url_for('node_setting'))
def test_api_url_for_with_multiple_urls(self): with self.app.test_request_context(): url = api_url_for('dummy_view', pid='123', nid='abc') assert url == '/api/v1/123/component/abc/'
def test_box_oauth_start(self): url = api_url_for('box_oauth_start_user') res = self.app.get(url) assert_is_redirect(res)
def api_url_for(self, view_name, _absolute=False, *args, **kwargs): return api_url_for(view_name, pid=self._id, _absolute=_absolute, *args, **kwargs)
def test_get_metaschemas_all(self): url = api_url_for('get_metaschemas', include='all') res = self.app.get(url) assert_equal(res.status_code, http_status.HTTP_200_OK) assert_equal(len(res.json['meta_schemas']), RegistrationSchema.objects.filter(active=True).count())