From f117d8a2064042043eeada02695d42bf05fad27d Mon Sep 17 00:00:00 2001 From: James John James Date: Sun, 16 Jun 2019 21:04:04 +0100 Subject: [PATCH 01/40] remove csrf global --- core/controllers/base.py | 14 ++++++ core/controllers/base_test.py | 18 +++++++- core/controllers/profile.py | 2 + core/controllers/profile_test.py | 4 +- core/templates/dev/head/App.ts | 11 +++-- .../exploration-creation.service.ts | 9 ++-- core/templates/dev/head/pages/Base.ts | 12 +++-- .../pages/about-page/about-page.mainpage.html | 5 -- .../pages/admin-page/admin-page.directive.ts | 8 +++- .../pages/admin-page/admin-page.mainpage.html | 1 - .../privacy-page/privacy-page.mainpage.html | 5 -- .../signup-page/signup-page.controller.ts | 10 ++-- .../pages/terms-page/terms-page.mainpage.html | 5 -- .../head/services/AssetsBackendApiService.ts | 9 ++-- .../dev/head/services/CsrfService.ts | 39 ++++++++++++++++ .../dev/head/services/CsrfServiceSpec.ts | 46 +++++++++++++++++++ .../templates/FilepathEditorDirective.ts | 7 +-- main.py | 3 ++ 18 files changed, 166 insertions(+), 42 deletions(-) create mode 100644 core/templates/dev/head/services/CsrfService.ts create mode 100644 core/templates/dev/head/services/CsrfServiceSpec.ts diff --git a/core/controllers/base.py b/core/controllers/base.py index 0076de51d233..9a90b9f9356d 100755 --- a/core/controllers/base.py +++ b/core/controllers/base.py @@ -577,3 +577,17 @@ def is_csrf_token_valid(cls, user_id, token): return False except Exception: return False + + +class CsrfTokenHandler(BaseHandler): + """Handles sending CSRF tokens to the frontend.""" + + GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON + REQUIRE_PAYLOAD_CSRF_CHECK = False + + def get(self): + csrf_token = CsrfTokenManager.create_csrf_token( + self.user_id) + self.render_json({ + 'token': csrf_token, + }) diff --git a/core/controllers/base_test.py b/core/controllers/base_test.py index b80d4086d330..798adb2d6664 100644 --- a/core/controllers/base_test.py +++ b/core/controllers/base_test.py @@ -671,7 +671,8 @@ def test_every_method_has_decorator(self): # Following handler are present in base.py where acl_decorators # cannot be imported. if (handler.__name__ == 'LogoutPage' or - handler.__name__ == 'Error404Handler'): + handler.__name__ == 'Error404Handler' or + handler-__name__ == 'CsrfTokenHandler'): continue if handler.get != base.BaseHandler.get: @@ -888,3 +889,18 @@ def test_no_error_is_raised_on_opening_new_tab_after_signup(self): ) self.get_html_response('/about') + + +class CsrfTokenHandlerTests(test_utils.GenericTestBase): + + def test_valid_token_is_returned(self): + """Test that a valid csrf token is returned by + the handler. + """ + + response = self.get_json('/csrf') + csrf_token = response['token'] + + self.assertTrue(base.CsrfTokenManager.is_csrf_token_valid( + None, csrf_token)) + diff --git a/core/controllers/profile.py b/core/controllers/profile.py index 187a100449d3..5c7cfc760a1c 100644 --- a/core/controllers/profile.py +++ b/core/controllers/profile.py @@ -284,6 +284,8 @@ def get(self): 'has_ever_registered': bool( user_settings.username and user_settings.last_agreed_to_terms), 'username': user_settings.username, + 'csrf_token': base.CsrfTokenManager.create_csrf_token( + self.user_id), }) @acl_decorators.require_user_id_else_redirect_to_homepage diff --git a/core/controllers/profile_test.py b/core/controllers/profile_test.py index 407fcfdf63de..4506ebaab888 100644 --- a/core/controllers/profile_test.py +++ b/core/controllers/profile_test.py @@ -200,7 +200,7 @@ def test_user_settings_of_non_existing_user(self): u'username': None, } response = self.get_json(feconf.SIGNUP_DATA_URL) - self.assertEqual(response, values_dict) + self.assertDictContainsSubset(response, values_dict) self.logout() def test_user_settings_of_existing_user(self): @@ -214,7 +214,7 @@ def test_user_settings_of_existing_user(self): } with self.swap(feconf, 'CAN_SEND_EMAILS', True): response = self.get_json(feconf.SIGNUP_DATA_URL) - self.assertEqual(response, values_dict) + self.assertDictContainsSubset(response, values_dict) self.logout() diff --git a/core/templates/dev/head/App.ts b/core/templates/dev/head/App.ts index 65a0b1ecc900..9c35ca5245e0 100644 --- a/core/templates/dev/head/App.ts +++ b/core/templates/dev/head/App.ts @@ -23,6 +23,7 @@ require('pages/Base.ts'); require('services/AlertsService.ts'); require('services/ContextService.ts'); +require('services/CsrfService.ts'); require('services/NavigationService.ts'); require('services/UtilsService.ts'); require('services/DebouncerService.ts'); @@ -190,12 +191,13 @@ oppia.config([ // Add an interceptor to convert requests to strings and to log and show // warnings for error responses. $httpProvider.interceptors.push([ - '$q', '$log', 'AlertsService', function($q, $log, AlertsService) { + '$q', '$log', 'AlertsService', 'CsrfService', + function ($q, $log, AlertsService, CsrfService) { return { request: function(config) { if (config.data) { config.data = $.param({ - csrf_token: GLOBALS.csrf_token, + csrf_token: CsrfService.getToken(), payload: JSON.stringify(config.data), source: document.URL }, true); @@ -268,7 +270,8 @@ oppia.config(['toastrConfig', function(toastrConfig) { // Overwrite the built-in exceptionHandler service to log errors to the backend // (so that they can be fixed). -oppia.factory('$exceptionHandler', ['$log', function($log) { +oppia.factory('$exceptionHandler', ['$log', 'CsrfService', + function($log, CsrfService) { var MIN_TIME_BETWEEN_ERRORS_MSEC = 5000; var timeOfLastPostedError = Date.now() - MIN_TIME_BETWEEN_ERRORS_MSEC; @@ -292,7 +295,7 @@ oppia.factory('$exceptionHandler', ['$log', function($log) { type: 'POST', url: '/frontend_errors', data: $.param({ - csrf_token: GLOBALS.csrf_token, + csrf_token: CsrfService.getToken(), payload: JSON.stringify({ error: messageAndSourceAndStackTrace }), diff --git a/core/templates/dev/head/components/entity-creation-services/exploration-creation.service.ts b/core/templates/dev/head/components/entity-creation-services/exploration-creation.service.ts index e8e40999eb66..6968dc384186 100644 --- a/core/templates/dev/head/components/entity-creation-services/exploration-creation.service.ts +++ b/core/templates/dev/head/components/entity-creation-services/exploration-creation.service.ts @@ -19,14 +19,17 @@ require('domain/utilities/UrlInterpolationService.ts'); require('services/AlertsService.ts'); +require('services/CsrfService.ts'); require('services/SiteAnalyticsService.ts'); oppia.factory('ExplorationCreationService', [ '$http', '$rootScope', '$timeout', '$uibModal', '$window', - 'AlertsService', 'SiteAnalyticsService', 'UrlInterpolationService', + 'AlertsService', 'CsrfService', 'SiteAnalyticsService', + 'UrlInterpolationService', function( $http, $rootScope, $timeout, $uibModal, $window, - AlertsService, SiteAnalyticsService, UrlInterpolationService) { + AlertsService, CsrfService, SiteAnalyticsService, + UrlInterpolationService) { var CREATE_NEW_EXPLORATION_URL_TEMPLATE = '/create/'; var explorationCreationInProgress = false; @@ -98,7 +101,7 @@ oppia.factory('ExplorationCreationService', [ var form = new FormData(); form.append('yaml_file', yamlFile); form.append('payload', JSON.stringify({})); - form.append('csrf_token', GLOBALS.csrf_token); + form.append('csrf_token', CsrfService.getToken()); $.ajax({ contentType: false, diff --git a/core/templates/dev/head/pages/Base.ts b/core/templates/dev/head/pages/Base.ts index d2ee04cede42..b5b3809e6542 100644 --- a/core/templates/dev/head/pages/Base.ts +++ b/core/templates/dev/head/pages/Base.ts @@ -15,6 +15,7 @@ require('domain/sidebar/SidebarStatusService.ts'); require('domain/utilities/UrlInterpolationService.ts'); require('services/AlertsService.ts'); +require('services/CsrfService.ts'); require('services/contextual/UrlService.ts'); require('services/stateful/BackgroundMaskService.ts'); @@ -24,11 +25,11 @@ require('services/stateful/BackgroundMaskService.ts'); oppia.controller('Base', [ '$document', '$rootScope', '$scope', 'AlertsService', 'BackgroundMaskService', - 'SidebarStatusService', 'UrlInterpolationService', 'UrlService', 'DEV_MODE', - 'SITE_FEEDBACK_FORM_URL', 'SITE_NAME', + 'CsrfService', 'SidebarStatusService', 'UrlInterpolationService', + 'UrlService', 'DEV_MODE', 'SITE_FEEDBACK_FORM_URL', 'SITE_NAME', function($document, $rootScope, $scope, AlertsService, BackgroundMaskService, - SidebarStatusService, UrlInterpolationService, UrlService, DEV_MODE, - SITE_FEEDBACK_FORM_URL, SITE_NAME) { + CsrfService, SidebarStatusService, UrlInterpolationService, + UrlService, DEV_MODE, SITE_FEEDBACK_FORM_URL, SITE_NAME) { $scope.siteName = SITE_NAME; $scope.AlertsService = AlertsService; $scope.currentLang = 'en'; @@ -53,6 +54,9 @@ oppia.controller('Base', [ $scope.currentLang = response.language; }); + if (UrlService.getPathname() !== '/signup') { + CsrfService.fetchToken(); + } // TODO(sll): use 'touchstart' for mobile. $document.on('click', function() { SidebarStatusService.onDocumentClick(); diff --git a/core/templates/dev/head/pages/about-page/about-page.mainpage.html b/core/templates/dev/head/pages/about-page/about-page.mainpage.html index 67b88bde01d3..ed7f4f60f7e0 100644 --- a/core/templates/dev/head/pages/about-page/about-page.mainpage.html +++ b/core/templates/dev/head/pages/about-page/about-page.mainpage.html @@ -2,11 +2,6 @@ @require('../../base_components/header.html', {"title": "About us - Oppia"}) - diff --git a/core/templates/dev/head/pages/admin-page/admin-page.directive.ts b/core/templates/dev/head/pages/admin-page/admin-page.directive.ts index e8b72d33959d..1c1eda18cd4b 100644 --- a/core/templates/dev/head/pages/admin-page/admin-page.directive.ts +++ b/core/templates/dev/head/pages/admin-page/admin-page.directive.ts @@ -77,6 +77,7 @@ require('value_generators/valueGeneratorsRequires.ts'); require('domain/objects/NumberWithUnitsObjectFactory.ts'); require('domain/utilities/UrlInterpolationService.ts'); require('pages/admin-page/services/admin-router.service.ts'); +require('services/CsrfService.ts'); require('services/UtilsService.ts'); oppia.directive('adminPage', ['UrlInterpolationService', @@ -89,8 +90,10 @@ oppia.directive('adminPage', ['UrlInterpolationService', '/pages/admin-page/admin-page.directive.html'), controllerAs: '$ctrl', controller: [ - '$http', '$location', '$scope', 'AdminRouterService', 'DEV_MODE', - function($http, $location, $scope, AdminRouterService, DEV_MODE) { + '$http', '$location', '$scope', 'AdminRouterService', 'CsrfService', + 'DEV_MODE', + function($http, $location, $scope, AdminRouterService, CsrfService, + DEV_MODE) { var ctrl = this; ctrl.userEmail = GLOBALS.USER_EMAIL; ctrl.inDevMode = DEV_MODE; @@ -102,6 +105,7 @@ oppia.directive('adminPage', ['UrlInterpolationService', ctrl.isRolesTabOpen = AdminRouterService.isRolesTabOpen; ctrl.isMiscTabOpen = AdminRouterService.isMiscTabOpen; + CsrfService.fetchToken(); ctrl.setStatusMessage = function(statusMessage) { ctrl.statusMessage = statusMessage; }; diff --git a/core/templates/dev/head/pages/admin-page/admin-page.mainpage.html b/core/templates/dev/head/pages/admin-page/admin-page.mainpage.html index 24c61b2eefd6..3216555ebbb9 100644 --- a/core/templates/dev/head/pages/admin-page/admin-page.mainpage.html +++ b/core/templates/dev/head/pages/admin-page/admin-page.mainpage.html @@ -8,7 +8,6 @@ diff --git a/core/templates/dev/head/pages/signup-page/signup-page.controller.ts b/core/templates/dev/head/pages/signup-page/signup-page.controller.ts index 2433042c983b..34641d473913 100644 --- a/core/templates/dev/head/pages/signup-page/signup-page.controller.ts +++ b/core/templates/dev/head/pages/signup-page/signup-page.controller.ts @@ -18,6 +18,7 @@ require('domain/utilities/UrlInterpolationService.ts'); require('services/AlertsService.ts'); +require('services/CsrfService.ts'); require('services/IdGenerationService.ts'); require('services/SiteAnalyticsService.ts'); require('services/UserService.ts'); @@ -26,13 +27,13 @@ require('services/stateful/FocusManagerService.ts'); oppia.controller('Signup', [ '$http', '$rootScope', '$scope', '$uibModal', 'AlertsService', - 'FocusManagerService', - 'SiteAnalyticsService', 'UrlInterpolationService', 'UrlService', + 'CsrfService', 'FocusManagerService', 'SiteAnalyticsService', + 'UrlInterpolationService', 'UrlService', 'SITE_NAME', function( $http, $rootScope, $scope, $uibModal, AlertsService, - FocusManagerService, - SiteAnalyticsService, UrlInterpolationService, UrlService, + CsrfService, FocusManagerService, SiteAnalyticsService, + UrlInterpolationService, UrlService, SITE_NAME) { var _SIGNUP_DATA_URL = '/signuphandler/data'; $rootScope.loadingMessage = 'I18N_SIGNUP_LOADING'; @@ -49,6 +50,7 @@ oppia.controller('Signup', [ $scope.showEmailPreferencesForm = data.can_send_emails; $scope.hasUsername = Boolean($scope.username); FocusManagerService.setFocus('usernameInputField'); + CsrfService.setToken(data.csrf_token); }); $scope.blurredAtLeastOnce = false; diff --git a/core/templates/dev/head/pages/terms-page/terms-page.mainpage.html b/core/templates/dev/head/pages/terms-page/terms-page.mainpage.html index d2b95b3350aa..d43e17cf71ae 100644 --- a/core/templates/dev/head/pages/terms-page/terms-page.mainpage.html +++ b/core/templates/dev/head/pages/terms-page/terms-page.mainpage.html @@ -2,11 +2,6 @@ @require('../../base_components/header.html', {"title": "Terms of Use - Oppia"}) - diff --git a/core/templates/dev/head/services/AssetsBackendApiService.ts b/core/templates/dev/head/services/AssetsBackendApiService.ts index 279b1db85692..f9d6c0064c79 100644 --- a/core/templates/dev/head/services/AssetsBackendApiService.ts +++ b/core/templates/dev/head/services/AssetsBackendApiService.ts @@ -21,13 +21,16 @@ require('domain/utilities/AudioFileObjectFactory.ts'); require('domain/utilities/FileDownloadRequestObjectFactory.ts'); require('domain/utilities/ImageFileObjectFactory.ts'); require('domain/utilities/UrlInterpolationService.ts'); +require('services/CsrfService.ts'); oppia.factory('AssetsBackendApiService', [ '$http', '$q', 'AudioFileObjectFactory', 'FileDownloadRequestObjectFactory', - 'ImageFileObjectFactory', 'UrlInterpolationService', 'DEV_MODE', + 'ImageFileObjectFactory', 'CsrfService', 'UrlInterpolationService', + 'DEV_MODE', function( $http, $q, AudioFileObjectFactory, FileDownloadRequestObjectFactory, - ImageFileObjectFactory, UrlInterpolationService, DEV_MODE) { + ImageFileObjectFactory, CsrfService, UrlInterpolationService, + DEV_MODE) { if (!DEV_MODE && !GLOBALS.GCS_RESOURCE_BUCKET_NAME) { throw Error('GCS_RESOURCE_BUCKET_NAME is not set in prod.'); } @@ -152,7 +155,7 @@ oppia.factory('AssetsBackendApiService', [ form.append('payload', JSON.stringify({ filename: filename })); - form.append('csrf_token', GLOBALS.csrf_token); + form.append('csrf_token', CsrfService.getToken()); $.ajax({ url: _getAudioUploadUrl(explorationId), diff --git a/core/templates/dev/head/services/CsrfService.ts b/core/templates/dev/head/services/CsrfService.ts new file mode 100644 index 000000000000..c3ad29be8a85 --- /dev/null +++ b/core/templates/dev/head/services/CsrfService.ts @@ -0,0 +1,39 @@ +// Copyright 2019 The Oppia Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview Service for managing csrf tokens + */ + +oppia.factory('CsrfService', [function() { + var token = null; + return { + fetchToken: function() { + fetch('/csrf').then(function(response) { + return response.text(); + }).then(function(response) { + token = JSON.parse(response.substring(5)).token; + }); + }, + + // For Signup page + setToken: function(csrf_token) { + token = csrf_token; + }, + + getToken: function() { + return token; + } + }; +}]); diff --git a/core/templates/dev/head/services/CsrfServiceSpec.ts b/core/templates/dev/head/services/CsrfServiceSpec.ts new file mode 100644 index 000000000000..524d87be3477 --- /dev/null +++ b/core/templates/dev/head/services/CsrfServiceSpec.ts @@ -0,0 +1,46 @@ +// Copyright 2014 The Oppia Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview Unit tests for the csrf service + */ + +require('services/CsrfService.ts'); + +describe('Csrf Service', function () { + var CsrfService, $httpBackend; + + beforeEach(angular.mock.module('oppia')); + beforeEach(angular.mock.inject(function($injector) { + CsrfService = $injector.get('CsrfService'); + $httpBackend = $injector.get('$httpBackend'); + })); + + it('should return the correct csrf token', function() { + var response = ')]}\'{token: \'sample csrf token\'}'; + + $httpBackend.expect('GET', '/csrf').respond( + 200, response); + + CsrfService.fetchToken(); + + expect(CsrfService.getToken()).toBe('sample csrf token'); + }) + + it('should correctly set the csrf token', function() { + CsrfService.setToken('sample csrf token'); + + expect(CsrfService.getToken()).toBe('sample csrf token'); + }) +}) diff --git a/extensions/objects/templates/FilepathEditorDirective.ts b/extensions/objects/templates/FilepathEditorDirective.ts index d5abdf16ab2c..b1c4410168ac 100644 --- a/extensions/objects/templates/FilepathEditorDirective.ts +++ b/extensions/objects/templates/FilepathEditorDirective.ts @@ -17,14 +17,15 @@ */ // This directive can only be used in the context of an exploration. +require('services/CsrfService.ts'); oppia.directive('filepathEditor', [ '$http', '$sce', 'AlertsService', 'AssetsBackendApiService', - 'ContextService', 'UrlInterpolationService', + 'ContextService', 'CsrfService', 'UrlInterpolationService', 'OBJECT_EDITOR_URL_PREFIX', function( $http, $sce, AlertsService, AssetsBackendApiService, - ContextService, UrlInterpolationService, + ContextService, CsrfService, UrlInterpolationService, OBJECT_EDITOR_URL_PREFIX) { return { restrict: 'E', @@ -636,7 +637,7 @@ oppia.directive('filepathEditor', [ filename: ctrl.generateImageFilename( dimensions.height, dimensions.width) })); - form.append('csrf_token', GLOBALS.csrf_token); + form.append('csrf_token', CsrfService.getToken()); $.ajax({ url: '/createhandler/imageupload/' + ctrl.explorationId, diff --git a/main.py b/main.py index d3067b5c4ee1..f833b3126144 100644 --- a/main.py +++ b/main.py @@ -662,6 +662,9 @@ def ui_access_wrapper(self, *args, **kwargs): get_redirect_route( r'/resolveissuehandler/', editor.ResolveIssueHandler), + get_redirect_route( + r'/csrf', base.CsrfTokenHandler), + # 404 error handler. get_redirect_route(r'/<:.*>', base.Error404Handler), ] From 6bbc8626217cf796767ea2ef743ce950a9aa67b2 Mon Sep 17 00:00:00 2001 From: James John James Date: Mon, 17 Jun 2019 07:03:34 +0100 Subject: [PATCH 02/40] refactor tests --- .github/CODEOWNERS | 1 + core/controllers/admin_test.py | 28 ++-- core/controllers/base_test.py | 13 +- core/controllers/collection_editor_test.py | 49 ++---- core/controllers/creator_dashboard_test.py | 24 +-- core/controllers/editor_test.py | 107 +++++++------ core/controllers/email_dashboard_test.py | 87 +++++------ core/controllers/feedback_test.py | 48 +++--- core/controllers/learner_dashboard_test.py | 4 +- core/controllers/learner_playlist_test.py | 8 +- core/controllers/library_test.py | 8 +- core/controllers/moderator_test.py | 4 +- core/controllers/profile_test.py | 80 +++++----- core/controllers/question_editor_test.py | 64 ++++---- core/controllers/reader_test.py | 40 ++--- core/controllers/resources_test.py | 94 ++++++------ core/controllers/skill_editor_test.py | 7 +- core/controllers/story_editor_test.py | 7 +- core/controllers/subscriptions_test.py | 20 +-- core/controllers/suggestion_test.py | 144 +++++++++--------- core/controllers/topic_editor_test.py | 30 ++-- .../topics_and_skills_dashboard_test.py | 6 +- core/controllers/voice_artist_test.py | 12 +- core/domain/email_manager_test.py | 37 +++-- core/domain/feedback_services_test.py | 4 +- core/domain/summary_services_test.py | 4 +- core/tests/test_utils.py | 11 +- 27 files changed, 448 insertions(+), 493 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 7c3f8801f2bc..99c2a435ee1a 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -403,6 +403,7 @@ /core/templates/dev/head/pages/footer_js_libs.html @vojtechjelinek /core/templates/dev/head/pages/header_css_libs.html @vojtechjelinek /core/templates/dev/head/pages/header_js_libs.html @vojtechjelinek +/core/templates/dev/head/services/CsrfService*.ts @jamesjay4199 @vojtechjelinek /gulpfile.js @vojtechjelinek /jinja_utils*.py @vojtechjelinek /webpack.config.ts @vojtechjelinek diff --git a/core/controllers/admin_test.py b/core/controllers/admin_test.py index 208e94eba222..99869d2b08f7 100644 --- a/core/controllers/admin_test.py +++ b/core/controllers/admin_test.py @@ -56,8 +56,8 @@ def test_change_configuration_property(self): """Test that configuration properties can be changed.""" self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_html_response('/admin') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] new_config_value = True response_dict = self.get_json('/adminhandler') @@ -92,8 +92,8 @@ class GenerateDummyExplorationsTest(test_utils.GenericTestBase): def test_generate_count_greater_than_publish_count(self): self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_html_response('/admin') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/adminhandler', { 'action': 'generate_dummy_explorations', @@ -108,8 +108,8 @@ def test_generate_count_greater_than_publish_count(self): def test_generate_count_equal_to_publish_count(self): self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_html_response('/admin') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/adminhandler', { 'action': 'generate_dummy_explorations', @@ -124,8 +124,8 @@ def test_generate_count_equal_to_publish_count(self): def test_generate_count_less_than_publish_count(self): self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_html_response('/admin') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] generated_exps_response = self.post_json( '/adminhandler', { 'action': 'generate_dummy_explorations', @@ -164,8 +164,8 @@ def test_view_and_update_role(self): response_dict, {'user1': feconf.ROLE_ID_EXPLORATION_EDITOR}) # Check role correctly gets updated. - response = self.get_html_response(feconf.ADMIN_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response_dict = self.post_json( feconf.ADMIN_ROLE_HANDLER_URL, {'role': feconf.ROLE_ID_MODERATOR, 'username': username}, @@ -192,8 +192,8 @@ def test_invalid_username_in_view_and_update_role(self): expected_status_int=400) # Trying to update role of non-existent user. - response = self.get_html_response(feconf.ADMIN_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.post_json( feconf.ADMIN_ROLE_HANDLER_URL, {'role': feconf.ROLE_ID_MODERATOR, 'username': username}, @@ -294,8 +294,8 @@ def test_clear_search_index(self): self.assertEqual(result_collections, ['0']) self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_html_response('/admin') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] generated_exps_response = self.post_json( '/adminhandler', { 'action': 'clear_search_index' diff --git a/core/controllers/base_test.py b/core/controllers/base_test.py index 798adb2d6664..c93469e3c684 100644 --- a/core/controllers/base_test.py +++ b/core/controllers/base_test.py @@ -672,7 +672,7 @@ def test_every_method_has_decorator(self): # cannot be imported. if (handler.__name__ == 'LogoutPage' or handler.__name__ == 'Error404Handler' or - handler-__name__ == 'CsrfTokenHandler'): + handler.__name__ == 'CsrfTokenHandler'): continue if handler.get != base.BaseHandler.get: @@ -857,8 +857,8 @@ def test_error_is_raised_on_opening_new_tab_during_signup(self): during signup. """ self.login('abc@example.com') - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.get_html_response('/about', expected_status_int=302) self.assertIn('Logout', response.location) @@ -878,8 +878,8 @@ def test_no_error_is_raised_on_opening_new_tab_after_signup(self): after signup. """ self.login('abc@example.com') - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SIGNUP_DATA_URL, { @@ -892,7 +892,7 @@ def test_no_error_is_raised_on_opening_new_tab_after_signup(self): class CsrfTokenHandlerTests(test_utils.GenericTestBase): - + def test_valid_token_is_returned(self): """Test that a valid csrf token is returned by the handler. @@ -903,4 +903,3 @@ def test_valid_token_is_returned(self): self.assertTrue(base.CsrfTokenManager.is_csrf_token_valid( None, csrf_token)) - diff --git a/core/controllers/collection_editor_test.py b/core/controllers/collection_editor_test.py index ed0f7269bcae..f21444f33a92 100644 --- a/core/controllers/collection_editor_test.py +++ b/core/controllers/collection_editor_test.py @@ -132,11 +132,8 @@ def test_editable_collection_handler_put_with_invalid_payload_version(self): self.login(self.EDITOR_EMAIL) # Call get handler to return the csrf token. - response = self.get_html_response( - '%s/%s' % ( - feconf.COLLECTION_URL_PREFIX, - self.COLLECTION_ID)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Raises error as version is None. json_response = self.put_json( @@ -180,11 +177,8 @@ def test_editable_collection_handler_put_cannot_access(self): self.login(self.VIEWER_EMAIL) # Call get handler to return the csrf token. - response = self.get_html_response( - '%s/%s' % ( - feconf.COLLECTION_URL_PREFIX, - self.COLLECTION_ID)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Ensure viewers do not have access to the PUT Handler. self.put_json( @@ -211,11 +205,8 @@ def test_editable_collection_handler_put_can_access(self): self.login(self.EDITOR_EMAIL) # Call get handler to return the csrf token. - response = self.get_html_response( - '%s/%s' % ( - feconf.COLLECTION_URL_PREFIX, - self.COLLECTION_ID)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] json_response = self.put_json( '%s/%s' % ( @@ -293,10 +284,8 @@ def test_can_not_publish_collection_with_invalid_payload_version(self): self.save_new_valid_collection( collection_id, self.owner_id, exploration_id=exploration_id) rights_manager.publish_exploration(self.owner, exploration_id) - response = self.get_html_response( - '%s/%s' % ( - feconf.COLLECTION_URL_PREFIX, self.COLLECTION_ID)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Raises error as version is None. response_dict = self.put_json( @@ -332,10 +321,8 @@ def test_can_not_unpublish_collection_with_invalid_payload_version(self): collection_id, self.owner_id, exploration_id=exploration_id) rights_manager.publish_exploration(self.owner, exploration_id) collection = collection_services.get_collection_by_id(collection_id) - response = self.get_html_response( - '%s/%s' % ( - feconf.COLLECTION_URL_PREFIX, self.COLLECTION_ID)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response_dict = self.put_json( '/collection_editor_handler/publish/%s' % collection_id, {'version': collection.version}, @@ -345,9 +332,8 @@ def test_can_not_unpublish_collection_with_invalid_payload_version(self): # Login as admin and try to unpublish the collection. self.login(self.ADMIN_EMAIL) - response = self.get_html_response( - '%s/%s' % (feconf.COLLECTION_URL_PREFIX, self.COLLECTION_ID)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Raises error as version is None. response_dict = self.put_json( @@ -384,10 +370,8 @@ def test_publish_unpublish_collection(self): collection_id, self.owner_id, exploration_id=exploration_id) rights_manager.publish_exploration(self.owner, exploration_id) collection = collection_services.get_collection_by_id(collection_id) - response = self.get_html_response( - '%s/%s' % ( - feconf.COLLECTION_URL_PREFIX, self.COLLECTION_ID)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response_dict = self.put_json( '/collection_editor_handler/publish/%s' % collection_id, {'version': collection.version}, @@ -397,9 +381,8 @@ def test_publish_unpublish_collection(self): # Login as admin and unpublish the collection. self.login(self.ADMIN_EMAIL) - response = self.get_html_response( - '%s/%s' % (feconf.COLLECTION_URL_PREFIX, self.COLLECTION_ID)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response_dict = self.put_json( '/collection_editor_handler/unpublish/%s' % collection_id, {'version': collection.version}, diff --git a/core/controllers/creator_dashboard_test.py b/core/controllers/creator_dashboard_test.py index 4d321acf6f84..25164c39ded9 100644 --- a/core/controllers/creator_dashboard_test.py +++ b/core/controllers/creator_dashboard_test.py @@ -726,8 +726,8 @@ def test_can_update_display_preference(self): display_preference = self.get_json( feconf.CREATOR_DASHBOARD_DATA_URL)['display_preference'] self.assertEqual(display_preference, 'card') - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.CREATOR_DASHBOARD_DATA_URL, {'display_preference': 'list'}, @@ -740,8 +740,8 @@ def test_can_update_display_preference(self): def test_can_create_collections(self): self.set_admins([self.OWNER_USERNAME]) self.login(self.OWNER_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] collection_id = self.post_json( feconf.NEW_COLLECTION_URL, {}, csrf_token=csrf_token)[ creator_dashboard.COLLECTION_ID_KEY] @@ -886,8 +886,8 @@ def test_new_exploration_ids(self): """Test generation of exploration ids.""" self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] exp_a_id = self.post_json( feconf.NEW_EXPLORATION_URL, {}, csrf_token=csrf_token )[creator_dashboard.EXPLORATION_ID_KEY] @@ -897,8 +897,8 @@ def test_new_exploration_ids(self): def test_can_non_admins_can_not_upload_exploration(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.post_json( feconf.UPLOAD_EXPLORATION_URL, {}, csrf_token=csrf_token, @@ -914,8 +914,8 @@ def test_can_upload_exploration(self): self.set_admins([self.ADMIN_USERNAME]) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] explorations_list = self.get_json( feconf.CREATOR_DASHBOARD_DATA_URL)['explorations_list'] self.assertEqual(explorations_list, []) @@ -935,8 +935,8 @@ def test_can_not_upload_exploration_when_server_does_not_allow_file_upload( self): self.set_admins([self.ADMIN_USERNAME]) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s?yaml_file=%s' % ( feconf.UPLOAD_EXPLORATION_URL, diff --git a/core/controllers/editor_test.py b/core/controllers/editor_test.py index 1473c157b966..c0857f347354 100644 --- a/core/controllers/editor_test.py +++ b/core/controllers/editor_test.py @@ -143,14 +143,14 @@ def test_that_default_exploration_cannot_be_published(self): """ self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] exp_id = self.post_json( feconf.NEW_EXPLORATION_URL, {}, csrf_token=csrf_token )[creator_dashboard.EXPLORATION_ID_KEY] - response = self.get_html_response('/create/%s' % exp_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] publish_url = '%s/%s' % (feconf.EXPLORATION_STATUS_PREFIX, exp_id) self.put_json( publish_url, { @@ -164,8 +164,8 @@ def test_add_new_state_error_cases(self): current_version = 1 self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] def _get_payload(new_state_name, version=None): """Gets the payload in the dict format.""" @@ -240,8 +240,8 @@ def test_publish_exploration(self): exp_id = exp_services.get_new_exploration_id() self.save_new_valid_exploration( exp_id, self.admin_id, end_state_name='end state') - response = self.get_html_response('/create/%s' % exp_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] publish_url = '%s/%s' % (feconf.EXPLORATION_STATUS_PREFIX, exp_id) exploration_rights = self.put_json( @@ -597,9 +597,8 @@ def test_state_yaml_handler(self): exploration.add_states(['State A', 'State 2', 'State 3']) exploration.states['State A'].update_interaction_id('TextInput') - response = self.get_html_response( - '%s/%s' % (feconf.EDITOR_URL_PREFIX, exp_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.post_json('/createhandler/state_yaml/%s' % exp_id, { 'state_dict': exploration.states['State A'].to_dict(), 'width': 50, @@ -616,9 +615,8 @@ def test_state_yaml_handler_with_no_state_dict_raises_error(self): owner_id = self.get_user_id_from_email(self.OWNER_EMAIL) self.save_new_valid_exploration(exp_id, owner_id) - response = self.get_html_response( - '%s/%s' % (feconf.EDITOR_URL_PREFIX, exp_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/createhandler/state_yaml/%s' % exp_id, {}, @@ -768,9 +766,8 @@ def test_record_user_saw_tutorial(self): self.save_new_valid_exploration(exp_id, owner_id) - response = self.get_html_response( - '%s/%s' % (feconf.EDITOR_URL_PREFIX, exp_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] user_settings = user_services.get_user_settings(owner_id) @@ -1116,9 +1113,8 @@ def test_get_with_disabled_exploration_id_raises_error(self): def test_reverting_to_old_exploration(self): """Test reverting to old exploration versions.""" # Open editor page. - response = self.get_html_response( - '%s/%s' % (feconf.EDITOR_URL_PREFIX, self.EXP_ID)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # May not revert to any version that's not 1. for rev_version in (-1, 0, 2, 3, 4, '1', ()): @@ -1202,9 +1198,8 @@ def test_versioning_for_default_exploration(self): expected_status_int=404) def test_revert_with_invalid_current_version_raises_error(self): - response = self.get_html_response( - '%s/%s' % (feconf.EDITOR_URL_PREFIX, self.EXP_ID)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.post_json( '/createhandler/revert/%s' % self.EXP_ID, { @@ -1292,9 +1287,8 @@ def test_for_assign_role_for_exploration(self): exploration.states['State 2'].update_interaction_id('TextInput') exploration.states['State 3'].update_interaction_id('TextInput') - response = self.get_html_response( - '%s/%s' % (feconf.EDITOR_URL_PREFIX, exp_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Owner adds rights for other users. rights_url = '%s/%s' % (feconf.EXPLORATION_RIGHTS_PREFIX, exp_id) @@ -1337,7 +1331,8 @@ def test_for_assign_role_for_exploration(self): response = self.get_html_response('/create/%s' % exp_id) self.assert_can_edit(response.body) self.assert_can_voiceover(response.body) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Check that collaborator can add a new state called 'State 4'. add_url = '%s/%s' % (feconf.EXPLORATION_DATA_PREFIX, exp_id) @@ -1378,7 +1373,8 @@ def test_for_assign_role_for_exploration(self): self.login(self.COLLABORATOR2_EMAIL) response = self.get_html_response('/create/%s' % exp_id) self.assert_can_edit(response.body) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Check that collaborator2 can add a new state called 'State 5'. add_url = '%s/%s' % (feconf.EXPLORATION_DATA_PREFIX, exp_id) @@ -1419,7 +1415,8 @@ def test_for_assign_role_for_exploration(self): response = self.get_html_response('/create/%s' % exp_id) self.assert_cannot_edit(response.body) self.assert_can_voiceover(response.body) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Check that voice artist cannot add new members. exploration = exp_services.get_exploration_by_id(exp_id) @@ -1443,8 +1440,8 @@ def test_transfering_ownership_to_the_community(self): self.save_new_valid_exploration( exp_id, self.owner_id, title='My Exploration', end_state_name='END') - response = self.get_html_response('/create/%s' % exp_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] rights_manager.publish_exploration(self.owner, exp_id) # Owner transfers ownership to the community. @@ -1497,8 +1494,8 @@ def test_cannot_transfer_ownership_of_invalid_exp_to_the_community(self): # The exploration is now invalid due to invalid language code. # Therefore, the following PUT request will raise an exception after # creating a domain object from the exploration model and validating it. - response = self.get_html_response('/create/%s' % exp_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] rights_url = '%s/%s' % (feconf.EXPLORATION_RIGHTS_PREFIX, exp_id) response = self.put_json( @@ -1523,8 +1520,8 @@ def test_put_with_invalid_new_member_raises_error(self): self.login(self.OWNER_EMAIL) exp_id = 'exp_id' self.save_new_valid_exploration(exp_id, self.owner_id) - response = self.get_html_response('/create/%s' % exp_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] exploration = exp_services.get_exploration_by_id(exp_id) response = self.put_json( @@ -1542,8 +1539,8 @@ def test_make_private_exploration_viewable(self): self.login(self.OWNER_EMAIL) exp_id = 'exp_id' self.save_new_valid_exploration(exp_id, self.owner_id) - response = self.get_html_response('/create/%s' % exp_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] exploration = exp_services.get_exploration_by_id(exp_id) exploration_rights = rights_manager.get_exploration_rights(exp_id) self.assertFalse(exploration_rights.viewable_if_private) @@ -1560,8 +1557,8 @@ def test_put_with_no_specified_changes_raise_error(self): self.login(self.OWNER_EMAIL) exp_id = 'exp_id' self.save_new_valid_exploration(exp_id, self.owner_id) - response = self.get_html_response('/create/%s' % exp_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] exploration = exp_services.get_exploration_by_id(exp_id) response = self.put_json( @@ -1588,9 +1585,8 @@ def test_user_exploration_emails_handler(self): exploration = exp_services.get_exploration_by_id(exp_id) - response = self.get_html_response( - '%s/%s' % (feconf.EDITOR_URL_PREFIX, exp_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] exp_email_preferences = ( user_services.get_email_preferences_for_exploration( @@ -1638,9 +1634,8 @@ def test_put_with_invalid_message_type_raises_error(self): self.login(self.OWNER_EMAIL) exp_id = 'eid' self.save_new_valid_exploration(exp_id, self.owner_id) - response = self.get_html_response( - '%s/%s' % (feconf.EDITOR_URL_PREFIX, exp_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.put_json( '%s/%s' % (feconf.USER_EXPLORATION_EMAILS_PREFIX, exp_id), @@ -1687,9 +1682,9 @@ def test_error_cases_for_email_sending(self): # Log in as a moderator. self.login(self.MODERATOR_EMAIL) - # Go to the exploration editor page. - response = self.get_html_response('/create/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + # Get csrf token. + response = self.get_json('/csrf') + csrf_token = response['token'] # Try to unpublish the exploration without an email body. This # should cause an error. @@ -1741,8 +1736,8 @@ def test_email_is_sent_correctly_when_unpublishing(self): self.login(self.MODERATOR_EMAIL) # Go to the exploration editor page. - response = self.get_html_response('/create/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] new_email_body = 'Your exploration is unpublished :(' @@ -1802,8 +1797,8 @@ def test_email_functionality_cannot_be_used_by_non_moderators(self): self.login(self.EDITOR_EMAIL) # Go to the exploration editor page. - response = self.get_html_response('/create/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] new_email_body = 'Your exploration is unpublished :(' @@ -2068,8 +2063,8 @@ def setUp(self): 'is_valid': True } - response = self.get_html_response('/create/%s' % self.EXP_ID) - self.csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + self.csrf_token = response['token'] def test_resolve_issue_handler(self): """Test that resolving an issue deletes associated playthroughs.""" @@ -2190,8 +2185,8 @@ def setUp(self): self._create_exp_user_data_model_objects_for_tests() # Generate CSRF token. - response = self.get_html_response('/create/%s' % self.EXP_ID1) - self.csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + self.csrf_token = response['token'] def test_exploration_loaded_with_draft_applied(self): response = self.get_json( diff --git a/core/controllers/email_dashboard_test.py b/core/controllers/email_dashboard_test.py index 309e5787bf44..e3ac0cd7a206 100644 --- a/core/controllers/email_dashboard_test.py +++ b/core/controllers/email_dashboard_test.py @@ -45,8 +45,8 @@ def setUp(self): def test_that_handler_works_correctly(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/emaildashboard')) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -127,8 +127,8 @@ def test_that_page_is_accessible_to_authorised_users_only(self): def test_that_exception_is_raised_for_invalid_input(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/emaildashboard')) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -260,8 +260,8 @@ def test_email_dashboard_result_page_with_invalid_query_id_raises_400(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_html_response('/emaildashboardresult/%s' % query_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.post_json( '/emaildashboardresult/%s' % 'invalid_query_id', {}, @@ -304,8 +304,8 @@ def test_email_dashboard_result_page_with_mismatch_of_query_id_raises_401( taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_html_response('/emaildashboardresult/%s' % query_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Raises authorization error when passing a query id whose associated # query model is not created by the logged in user. @@ -343,8 +343,8 @@ def test_cancel_email_handler_with_invalid_query_id_raises_400(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_html_response('/emaildashboardresult/%s' % query_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.post_json( '/emaildashboardcancelresult/%s' % 'invalid_query_id', {}, @@ -386,9 +386,8 @@ def test_cancel_email_handler_with_mismatch_of_query_id_raises_401(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_html_response('/emaildashboardresult/%s' % query_id) - csrf_token = self.get_csrf_token_from_response(response) - + response = self.get_json('/csrf') + csrf_token = response['token'] # Raises authorization error when passing a query id whose associated # query model is not created by the logged in user. response = self.post_json( @@ -425,8 +424,8 @@ def test_bulk_email_handler_with_invalid_query_id_raises_400(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_html_response('/emaildashboardresult/%s' % query_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.post_json( '/emaildashboardtestbulkemailhandler/%s' % 'invalid_query_id', {}, @@ -468,8 +467,8 @@ def test_bulk_email_handler_with_mismatch_of_query_id_raises_401(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_html_response('/emaildashboardresult/%s' % query_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Raises authorization error when passing a query id whose associated # query model is not created by the logged in user. @@ -484,8 +483,8 @@ def test_bulk_email_handler_with_mismatch_of_query_id_raises_401(self): def test_that_correct_emails_are_sent_to_all_users(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/emaildashboard')) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -522,9 +521,8 @@ def test_that_correct_emails_are_sent_to_all_users(self): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response( - '/emaildashboardresult/%s' % query_model.id)) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboardresult/%s' % query_model.id, { 'data': { @@ -587,8 +585,8 @@ def test_that_valid_exceptions_are_raised(self): with self.assertRaisesRegexp(Exception, '400 Bad Request'): self.get_html_response('/emaildashboardresult/%s' % 'q123') - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/emaildashboard')) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -640,9 +638,8 @@ def test_that_valid_exceptions_are_raised(self): with self.swap(feconf, 'CAN_SEND_EMAILS', True): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response( - '/emaildashboardresult/%s' % query_models[0].id)) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboardresult/%s' % query_models[0].id, { 'data': { @@ -664,8 +661,8 @@ def test_that_valid_exceptions_are_raised(self): def test_that_correct_emails_are_sent_to_max_n_recipients(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/emaildashboard')) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -688,9 +685,8 @@ def test_that_correct_emails_are_sent_to_max_n_recipients(self): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response( - '/emaildashboardresult/%s' % query_models[0].id)) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboardresult/%s' % query_models[0].id, { 'data': { @@ -712,8 +708,8 @@ def test_that_correct_emails_are_sent_to_max_n_recipients(self): def test_that_no_emails_are_sent_if_query_is_canceled(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/emaildashboard')) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -736,9 +732,8 @@ def test_that_no_emails_are_sent_if_query_is_canceled(self): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response( - '/emaildashboardresult/%s' % query_models[0].id)) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboardcancelresult/%s' % query_models[0].id, {}, csrf_token=csrf_token) @@ -752,8 +747,8 @@ def test_that_no_emails_are_sent_if_query_is_canceled(self): def test_that_test_email_for_bulk_emails_is_sent(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/emaildashboard')) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -776,9 +771,8 @@ def test_that_test_email_for_bulk_emails_is_sent(self): # Check that correct test email is sent. self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response( - '/emaildashboardresult/%s' % query_models[0].id)) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboardtestbulkemailhandler/%s' % query_models[0].id, { 'email_body': email_body, @@ -816,8 +810,8 @@ def test_that_test_email_for_bulk_emails_is_sent(self): def test_that_test_email_is_not_sent_to_query_recipients(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/emaildashboard')) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -836,9 +830,8 @@ def test_that_test_email_is_not_sent_to_query_recipients(self): self.process_and_flush_pending_tasks() self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response( - '/emaildashboardresult/%s' % query_models[0].id)) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/emaildashboardtestbulkemailhandler/%s' % query_models[0].id, { 'email_body': 'email_body', diff --git a/core/controllers/feedback_test.py b/core/controllers/feedback_test.py index 60b6034256e0..3dd9aec51e22 100644 --- a/core/controllers/feedback_test.py +++ b/core/controllers/feedback_test.py @@ -54,8 +54,8 @@ def setUp(self): # The corresponding user has already registered as an editor, and has a # username. self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/%s' % self.EXP_ID) - self.csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + self.csrf_token = response['token'] self.post_json('%s/%s' % ( feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID ), { @@ -131,8 +131,8 @@ def setUp(self): def test_create_thread(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { 'subject': u'New Thread ¡unicode!', @@ -164,8 +164,8 @@ def test_create_thread(self): def test_missing_thread_subject_raises_400_error(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response_dict = self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { 'state_name': None, @@ -177,8 +177,8 @@ def test_missing_thread_subject_raises_400_error(self): def test_missing_thread_text_raises_400_error(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response_dict = self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { @@ -192,8 +192,8 @@ def test_missing_thread_text_raises_400_error(self): def test_post_message_to_existing_thread(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # First, create a thread. self.post_json( @@ -252,8 +252,8 @@ def test_no_username_shown_for_logged_out_learners(self): exp_services.save_new_exploration(self.editor_id, exploration) rights_manager.publish_exploration(self.editor, new_exp_id) - response = self.get_html_response('/create/%s' % new_exp_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/explorehandler/give_feedback/%s' % new_exp_id, { @@ -275,8 +275,8 @@ def test_no_username_shown_for_logged_out_learners(self): def test_message_id_assignment_for_multiple_posts_to_same_thread(self): # Create a thread for others to post to. self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { 'state_name': None, @@ -323,8 +323,8 @@ def _get_email(index): # Each of these users posts a new message to the same thread. for num in range(num_users): self.login(_get_email(num)) - response = self.get_html_response('/create/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( thread_url, { 'text': 'New Message %s' % num @@ -411,8 +411,8 @@ def _get_message_ids_in_a_thread(self, thread_id): def test_feedback_threads(self): self.login(self.USER_EMAIL) - response = self.get_html_response(feconf.LIBRARY_INDEX_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json('%s/%s' % ( feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID @@ -438,8 +438,8 @@ def test_feedback_threads(self): self.logout() self.login(self.OWNER_EMAIL_1) - response = self.get_html_response(feconf.LIBRARY_INDEX_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # The owner opens the feedback thread. thread_url = '%s/%s' % (feconf.FEEDBACK_THREAD_URL_PREFIX, thread_id) @@ -468,8 +468,8 @@ def test_feedback_threads(self): self.logout() self.login(self.USER_EMAIL) - response = self.get_html_response(feconf.LIBRARY_INDEX_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # The user opens the feedback thread. thread_url = '%s/%s' % (feconf.FEEDBACK_THREAD_URL_PREFIX, thread_id) @@ -498,8 +498,8 @@ def test_feedback_threads(self): # Another owner logs in. self.login(self.OWNER_EMAIL_2) - response = self.get_html_response(feconf.LIBRARY_INDEX_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # The second owner opens the feedback thread. thread_url = '%s/%s' % (feconf.FEEDBACK_THREAD_URL_PREFIX, thread_id) diff --git a/core/controllers/learner_dashboard_test.py b/core/controllers/learner_dashboard_test.py index 105375f76a24..ba4f643bc839 100644 --- a/core/controllers/learner_dashboard_test.py +++ b/core/controllers/learner_dashboard_test.py @@ -290,8 +290,8 @@ def setUp(self): self.editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL) # Get the CSRF token and create a single thread with a single message. self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/%s' % self.EXP_ID_1) - self.csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + self.csrf_token = response['token'] self.post_json('%s/%s' % ( feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID_1 ), { diff --git a/core/controllers/learner_playlist_test.py b/core/controllers/learner_playlist_test.py index 1fdc6ffc8be4..92179dea2f80 100644 --- a/core/controllers/learner_playlist_test.py +++ b/core/controllers/learner_playlist_test.py @@ -71,8 +71,8 @@ def setUp(self): def test_add_exploration_to_learner_playlist(self): self.login(self.VIEWER_EMAIL) - response = self.get_html_response(feconf.LEARNER_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Add one exploration to the playlist. self.post_json( @@ -169,8 +169,8 @@ def test_add_exploration_to_learner_playlist(self): def test_add_collection_to_learner_playlist(self): self.login(self.VIEWER_EMAIL) - response = self.get_html_response(feconf.LEARNER_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Add one collection to the playlist. self.post_json( diff --git a/core/controllers/library_test.py b/core/controllers/library_test.py index 3bb35e57f101..376e8e11b6f3 100644 --- a/core/controllers/library_test.py +++ b/core/controllers/library_test.py @@ -273,8 +273,8 @@ def test_library_index_handler_for_user_preferred_language(self): 'preferred_language_codes': ['en'], }, response_dict) - response = self.get_html_response(feconf.PREFERENCES_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Change the user's preferred language to de. self.put_json( @@ -402,8 +402,8 @@ def test_library_group_page_for_user_preferred_language(self): 'preferred_language_codes': ['en'], }, response_dict) - response = self.get_html_response(feconf.PREFERENCES_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json( feconf.PREFERENCES_DATA_URL, diff --git a/core/controllers/moderator_test.py b/core/controllers/moderator_test.py index 903235eef6c2..b2d79c5d44e4 100644 --- a/core/controllers/moderator_test.py +++ b/core/controllers/moderator_test.py @@ -69,8 +69,8 @@ def setUp(self): def test_unpublished_activities_cannot_be_added_to_featured_list(self): self.login(self.MODERATOR_EMAIL) - response = self.get_html_response('/moderator') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Posting a list that includes private activities results in an error. self.post_json( diff --git a/core/controllers/profile_test.py b/core/controllers/profile_test.py index 4506ebaab888..c21874b19c22 100644 --- a/core/controllers/profile_test.py +++ b/core/controllers/profile_test.py @@ -49,8 +49,8 @@ def test_going_somewhere_else_while_signing_in_logs_user_out(self): def test_to_check_url_redirection_in_signup(self): """To validate the redirections from return_url.""" self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Registering this user fully. self.post_json( @@ -93,8 +93,8 @@ def strip_domain_from_location_header(url): def test_accepting_terms_is_handled_correctly(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response_dict = self.post_json( feconf.SIGNUP_DATA_URL, {'agreed_to_terms': False}, @@ -117,8 +117,8 @@ def test_accepting_terms_is_handled_correctly(self): def test_username_is_handled_correctly(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response_dict = self.post_json( feconf.SIGNUP_DATA_URL, {'agreed_to_terms': True}, @@ -154,8 +154,8 @@ def test_username_is_handled_correctly(self): def test_default_dashboard_for_new_users(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # This user should have the creator dashboard as default. self.post_json( @@ -173,8 +173,8 @@ def test_default_dashboard_for_new_users(self): self.logout() self.login(self.VIEWER_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # This user should have the learner dashboard as default. self.post_json( @@ -225,8 +225,8 @@ def test_username_check(self): self.signup('abc@example.com', username='abc') self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response_dict = self.post_json( feconf.USERNAME_CHECK_DATA_URL, {'username': 'abc'}, @@ -264,8 +264,8 @@ class EmailPreferencesTests(test_utils.GenericTestBase): def test_user_not_setting_email_prefs_on_signup(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SIGNUP_DATA_URL, {'username': 'abc', 'agreed_to_terms': True}, @@ -301,8 +301,8 @@ def test_user_not_setting_email_prefs_on_signup(self): def test_user_allowing_emails_on_signup(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SIGNUP_DATA_URL, {'username': 'abc', 'agreed_to_terms': True, @@ -338,8 +338,8 @@ def test_user_allowing_emails_on_signup(self): def test_user_disallowing_emails_on_signup(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SIGNUP_DATA_URL, {'username': 'abc', 'agreed_to_terms': True, @@ -382,8 +382,8 @@ def test_email_preferences_updates(self): self.signup(self.EDITOR_EMAIL, username=self.EDITOR_USERNAME) editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL) self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/preferences') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] payload = { 'update_type': 'email_preferences', @@ -462,8 +462,8 @@ def test_can_see_subscriptions(self): def test_can_update_profile_picture_data_url(self): self.login(self.OWNER_EMAIL) - response = self.get_html_response('/preferences') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] user_settings = user_services.get_user_settings(self.owner_id) self.assertTrue( user_settings.profile_picture_data_url.startswith( @@ -481,8 +481,8 @@ def test_can_update_profile_picture_data_url(self): def test_can_update_default_dashboard(self): self.login(self.OWNER_EMAIL) - response = self.get_html_response('/preferences') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] user_settings = user_services.get_user_settings(self.owner_id) self.assertIsNone(user_settings.default_dashboard) self.put_json( @@ -497,8 +497,8 @@ def test_can_update_default_dashboard(self): def test_update_preferences_with_invalid_update_type_raises_exception(self): self.login(self.OWNER_EMAIL) - response = self.get_html_response('/preferences') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with self.assertRaisesRegexp(Exception, 'Invalid update type:'): self.put_json( feconf.PREFERENCES_DATA_URL, @@ -534,8 +534,8 @@ class ProfileDataHandlerTests(test_utils.GenericTestBase): def test_preference_page_updates(self): self.signup(self.EDITOR_EMAIL, username=self.EDITOR_USERNAME) self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/preferences') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] original_preferences = self.get_json('/preferenceshandler/data') self.assertEqual( ['en'], original_preferences['preferred_language_codes']) @@ -562,8 +562,8 @@ def test_preference_page_updates(self): def test_profile_data_is_independent_of_currently_logged_in_user(self): self.signup(self.EDITOR_EMAIL, username=self.EDITOR_USERNAME) self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/preferences') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json( '/preferenceshandler/data', {'update_type': 'user_bio', 'data': 'My new editor bio'}, @@ -576,8 +576,8 @@ def test_profile_data_is_independent_of_currently_logged_in_user(self): self.signup(self.VIEWER_EMAIL, username=self.VIEWER_USERNAME) self.login(self.VIEWER_EMAIL) - response = self.get_html_response('/preferences') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json( '/preferenceshandler/data', {'update_type': 'user_bio', 'data': 'My new viewer bio'}, @@ -775,8 +775,8 @@ def test_save_site_language_handler(self): """ language_code = 'es' self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/preferences') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json( '/preferenceshandler/data', { 'update_type': 'preferred_site_language_code', @@ -795,8 +795,8 @@ def test_can_update_site_language_code(self): user_settings = user_services.get_user_settings( self.editor_id, strict=True) self.assertIsNone(user_settings.preferred_site_language_code) - response = self.get_html_response('/preferences') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json( feconf.SITE_LANGUAGE_DATA_URL, payload={'site_language_code': 'en'}, csrf_token=csrf_token) @@ -815,8 +815,8 @@ class LongUserBioHandlerTests(test_utils.GenericTestBase): def test_userbio_within_limit(self): self.signup(self.EMAIL_A, self.USERNAME_A) self.login(self.EMAIL_A) - response = self.get_html_response('/preferences') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json( '/preferenceshandler/data', { 'update_type': 'user_bio', @@ -831,8 +831,8 @@ def test_userbio_within_limit(self): def test_user_bio_exceeds_limit(self): self.signup(self.EMAIL_B, self.USERNAME_B) self.login(self.EMAIL_B) - response = self.get_html_response('/preferences') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] user_bio_response = self.put_json( '/preferenceshandler/data', { 'update_type': 'user_bio', diff --git a/core/controllers/question_editor_test.py b/core/controllers/question_editor_test.py index 6fcd6419183c..c1b80fb7e338 100644 --- a/core/controllers/question_editor_test.py +++ b/core/controllers/question_editor_test.py @@ -68,8 +68,8 @@ def setUp(self): def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): self.login(self.NEW_USER_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/%s' % (feconf.NEW_QUESTION_URL, self.skill_id), {}, csrf_token=csrf_token, expected_status_int=401) @@ -77,8 +77,8 @@ def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): def test_post_with_editor_email_does_not_allow_question_creation(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] question_dict = self.question.to_dict() question_dict['id'] = None self.post_json( @@ -89,8 +89,8 @@ def test_post_with_editor_email_does_not_allow_question_creation(self): def test_post_with_incorrect_skill_id_returns_404(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] incorrect_skill_id = 'abc123456789' self.post_json( '%s/%s' % (feconf.NEW_QUESTION_URL, incorrect_skill_id), @@ -99,8 +99,8 @@ def test_post_with_incorrect_skill_id_returns_404(self): def test_post_with_incorrect_question_id_returns_400(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] question_dict = self.question.to_dict() question_dict['id'] = 'abc123456789' self.post_json( @@ -111,8 +111,8 @@ def test_post_with_incorrect_question_id_returns_400(self): def test_post_with_incorrect_question_schema_returns_400(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] question_dict = self.question.to_dict() del question_dict['question_state_data']['content'] self.post_json( @@ -123,8 +123,8 @@ def test_post_with_incorrect_question_schema_returns_400(self): def test_post_with_admin_email_allows_question_creation(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] question_dict = self.question.to_dict() question_dict['id'] = None self.post_json( @@ -141,8 +141,8 @@ def test_post_with_admin_email_allows_question_creation(self): def test_post_with_topic_manager_email_allows_question_creation(self): self.login(self.TOPIC_MANAGER_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] question_dict = self.question.to_dict() question_dict['id'] = None self.post_json( @@ -159,8 +159,8 @@ def test_post_with_topic_manager_email_allows_question_creation(self): def test_post_with_invalid_question_returns_400_status(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] question_dict = self.question.to_dict() question_dict['id'] = None question_dict['question_state_data'] = 'invalid_question_state_data' @@ -186,8 +186,8 @@ def setUp(self): def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): self.login(self.NEW_USER_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/%s/%s' % ( feconf.QUESTION_SKILL_LINK_URL_PREFIX, self.question_id, @@ -197,8 +197,8 @@ def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): def test_post_with_incorrect_skill_id_returns_404(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] incorrect_skill_id = 'abc123456789' self.post_json( '%s/%s/%s' % ( @@ -209,8 +209,8 @@ def test_post_with_incorrect_skill_id_returns_404(self): def test_post_with_admin_email_allows_question_linking(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/%s/%s' % ( feconf.QUESTION_SKILL_LINK_URL_PREFIX, self.question_id, @@ -228,8 +228,8 @@ def test_post_with_admin_email_allows_question_linking(self): def test_post_with_topic_manager_email_allows_question_linking(self): self.login(self.TOPIC_MANAGER_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/%s/%s' % ( feconf.QUESTION_SKILL_LINK_URL_PREFIX, self.question_id, @@ -443,8 +443,8 @@ def test_put_with_admin_email_allows_question_editing(self): payload['commit_message'] = 'update question data' self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response_json = self.put_json( '%s/%s' % ( feconf.QUESTION_EDITOR_DATA_URL_PREFIX, self.question_id), @@ -489,8 +489,8 @@ def test_put_with_topic_manager_email_allows_question_editing(self): payload['commit_message'] = 'update question data' self.login(self.TOPIC_MANAGER_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] payload = {} new_question_data = self._create_valid_question_data('GHI') change_list = [{ @@ -528,8 +528,8 @@ def test_put_with_editor_email_allows_question_editing(self): payload['commit_message'] = 'update question data' self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] payload = {} new_question_data = self._create_valid_question_data('GHI') change_list = [{ @@ -565,8 +565,8 @@ def test_put_with_creating_new_fully_specified_question_returns_400(self): payload['change_list'] = change_list payload['commit_message'] = 'update question data' self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json( '%s/%s' % ( feconf.QUESTION_EDITOR_DATA_URL_PREFIX, self.question_id), diff --git a/core/controllers/reader_test.py b/core/controllers/reader_test.py index 1da7e4c2451e..b3b7b3b61e9d 100644 --- a/core/controllers/reader_test.py +++ b/core/controllers/reader_test.py @@ -436,8 +436,8 @@ def test_assign_and_read_ratings(self): self.signup('user@example.com', 'user') self.login('user@example.com') - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/explore/%s' % self.EXP_ID)) + response = self.get_json('/csrf') + csrf_token = response['token'] # User checks rating. ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) @@ -478,8 +478,8 @@ def test_non_logged_in_users_cannot_rate(self): self.signup('user@example.com', 'user') self.login('user@example.com') - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/explore/%s' % self.EXP_ID)) + response = self.get_json('/csrf') + csrf_token = response['token'] self.logout() ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) @@ -501,8 +501,8 @@ def test_ratings_by_different_users(self): self.signup('b@example.com', 'b') self.login('a@example.com') - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/explore/%s' % self.EXP_ID)) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json( '/explorehandler/rating/%s' % self.EXP_ID, { 'user_rating': 4 @@ -511,8 +511,8 @@ def test_ratings_by_different_users(self): self.logout() self.login('b@example.com') - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/explore/%s' % self.EXP_ID)) + response = self.get_json('/csrf') + csrf_token = response['token'] ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) self.assertEqual(ratings['user_rating'], None) self.put_json( @@ -1016,8 +1016,8 @@ def test_that_emails_are_sent(self): # Login and flag exploration. self.login(self.NEW_USER_EMAIL) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/%s' % (feconf.FLAG_EXPLORATION_URL_PREFIX, self.EXP_ID), { @@ -1071,8 +1071,8 @@ def test_non_logged_in_users_cannot_report(self): """Check that non-logged in users cannot report.""" self.login(self.NEW_USER_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/explore/%s' % self.EXP_ID)) + response = self.get_json('/csrf') + csrf_token = response['token'] self.logout() # Create report for exploration. @@ -1157,8 +1157,8 @@ def test_independent_exp_complete_event_handler(self): """ self.login(self.USER_EMAIL) - response = self.get_html_response(feconf.LIBRARY_INDEX_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] payload = { 'client_time_spent_in_secs': 0, @@ -1195,8 +1195,8 @@ def test_exp_complete_event_in_collection(self): """ self.login(self.USER_EMAIL) - response = self.get_html_response(feconf.LIBRARY_INDEX_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] payload = { 'client_time_spent_in_secs': 0, @@ -1240,8 +1240,8 @@ def test_exp_incomplete_event_handler(self): """Test handler for leaving an exploration incomplete.""" self.login(self.USER_EMAIL) - response = self.get_html_response(feconf.LIBRARY_INDEX_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] payload = { 'client_time_spent_in_secs': 0, @@ -1434,8 +1434,8 @@ def setUp(self): }] } - response = self.get_html_response('/explore/%s' % self.exp_id) - self.csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + self.csrf_token = response['token'] def test_new_playthrough_gets_stored(self): """Test that a new playthrough gets created and is added to an existing diff --git a/core/controllers/resources_test.py b/core/controllers/resources_test.py index 7104c6340665..031e21f93e2d 100644 --- a/core/controllers/resources_test.py +++ b/core/controllers/resources_test.py @@ -51,8 +51,8 @@ def setUp(self): def test_image_upload_with_no_filename_raises_error(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -69,8 +69,8 @@ def test_image_upload_with_no_filename_raises_error(self): def test_image_upload_with_invalid_filename_raises_error(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -88,8 +88,8 @@ def test_image_upload_with_invalid_filename_raises_error(self): def test_cannot_upload_duplicate_image(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -122,8 +122,8 @@ def test_image_upload_and_download(self): """Test image uploading and downloading.""" self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -144,8 +144,8 @@ def test_image_upload_and_download(self): def test_non_matching_extensions_are_detected(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] filename_without_extension = 'test' supplied_filename = ('%s.jpg' % filename_without_extension) @@ -183,8 +183,8 @@ def test_upload_empty_image(self): """Test upload of an empty image.""" self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Upload an empty image. response_dict = self.post_json( @@ -203,8 +203,8 @@ def test_upload_bad_image(self): """Test upload of a malformed image.""" self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Upload an invalid image. response_dict = self.post_json( @@ -230,8 +230,8 @@ def test_bad_filenames_are_detected(self): # TODO(sll): Add more tests here. self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -250,9 +250,8 @@ def test_bad_filenames_are_detected(self): def test_missing_extensions_are_detected(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) - + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: raw_image = f.read() @@ -271,8 +270,8 @@ def test_missing_extensions_are_detected(self): def test_bad_extensions_are_detected(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -337,8 +336,8 @@ def setUp(self): mock_accepted_audio_extensions) def test_guest_can_not_upload(self): - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: @@ -356,8 +355,8 @@ def test_guest_can_not_upload(self): def test_cannot_upload_audio_with_invalid_exp_id(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: @@ -373,8 +372,8 @@ def test_cannot_upload_audio_with_invalid_exp_id(self): def test_audio_upload(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: @@ -389,8 +388,8 @@ def test_audio_upload(self): def test_audio_upload_with_non_mp3_file(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] file_system_class = fs_services.get_exploration_file_system_class() fs = fs_domain.AbstractFileSystem(file_system_class( @@ -417,8 +416,8 @@ def test_audio_upload_with_non_mp3_file(self): def test_detect_non_matching_extensions(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Use an accepted audio extension in mismatched_filename # that differs from the uploaded file's audio type. @@ -449,8 +448,8 @@ def test_detect_non_audio_file(self): """ self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), @@ -471,8 +470,8 @@ def test_detect_non_audio_file(self): def test_audio_upload_mpeg_container(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join( feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MPEG_CONTAINER), @@ -490,8 +489,8 @@ def test_invalid_extension_is_detected(self): """Test that invalid extensions are caught.""" self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] filename_without_extension = 'test' invalid_extension = 'wav' @@ -520,9 +519,8 @@ def test_upload_empty_audio(self): """Test upload of empty audio.""" self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) - + response = self.get_json('/csrf') + csrf_token = response['token'] # Upload empty audio. response_dict = self.post_json( '%s/0' % self.AUDIO_UPLOAD_URL_PREFIX, @@ -539,8 +537,8 @@ def test_upload_bad_audio(self): """Test upload of malformed audio.""" self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response_dict = self.post_json( '%s/0' % self.AUDIO_UPLOAD_URL_PREFIX, {'filename': 'test.mp3'}, @@ -558,8 +556,8 @@ def test_missing_extensions_are_detected(self): """Test upload of filenames with no extensions are caught.""" self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] missing_extension_filename = 'test' with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), @@ -584,8 +582,8 @@ def test_exceed_max_length_detected(self): """Test that audio file is less than max playback length.""" self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_OVER_MAX_LENGTH), @@ -610,8 +608,8 @@ def test_non_matching_extensions_are_detected(self): """ self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/create/0') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Use an accepted audio extension in mismatched_filename # that differs from the uploaded file's audio type. diff --git a/core/controllers/skill_editor_test.py b/core/controllers/skill_editor_test.py index e80927a12419..20cdecdb9431 100644 --- a/core/controllers/skill_editor_test.py +++ b/core/controllers/skill_editor_test.py @@ -50,11 +50,8 @@ def setUp(self): def _get_csrf_token_for_put(self): """Gets the csrf token.""" - csrf_token = None - url_prefix = feconf.SKILL_EDITOR_URL_PREFIX - response = self.get_html_response( - '%s/%s' % (url_prefix, self.skill_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] return csrf_token def _delete_skill_model_and_memcache(self, user_id, skill_id): diff --git a/core/controllers/story_editor_test.py b/core/controllers/story_editor_test.py index fb44214fb685..6957c2bfbefa 100644 --- a/core/controllers/story_editor_test.py +++ b/core/controllers/story_editor_test.py @@ -107,11 +107,8 @@ def test_editable_story_handler_put(self): }] } self.login(self.ADMIN_EMAIL) - response = self.get_html_response( - '%s/%s/%s' % ( - feconf.STORY_EDITOR_URL_PREFIX, self.topic_id, - self.story_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] json_response = self.put_json( '%s/%s/%s' % ( diff --git a/core/controllers/subscriptions_test.py b/core/controllers/subscriptions_test.py index 4443058d670c..01c452b73476 100644 --- a/core/controllers/subscriptions_test.py +++ b/core/controllers/subscriptions_test.py @@ -44,8 +44,8 @@ def test_subscribe_handler(self): """Test handler for new subscriptions to creators.""" self.login(self.USER_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] payload = { 'creator_username': self.EDITOR_USERNAME @@ -77,8 +77,8 @@ def test_subscribe_handler(self): # Test another user subscription. self.login(self.USER2_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SUBSCRIBE_URL_PREFIX, payload, @@ -99,8 +99,8 @@ def test_unsubscribe_handler(self): # Add one subscription to editor. self.login(self.USER_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SUBSCRIBE_URL_PREFIX, payload, csrf_token=csrf_token) @@ -108,8 +108,8 @@ def test_unsubscribe_handler(self): # Add another subscription. self.login(self.USER2_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SUBSCRIBE_URL_PREFIX, payload, csrf_token=csrf_token) @@ -140,8 +140,8 @@ def test_unsubscribe_handler(self): # Unsubscribing another user. self.login(self.USER_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.UNSUBSCRIBE_URL_PREFIX, payload, csrf_token=csrf_token) diff --git a/core/controllers/suggestion_test.py b/core/controllers/suggestion_test.py index 57e03397c8c4..6a72fa8e5c67 100644 --- a/core/controllers/suggestion_test.py +++ b/core/controllers/suggestion_test.py @@ -91,8 +91,8 @@ def setUp(self): self.logout() self.login(self.AUTHOR_EMAIL) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -116,8 +116,8 @@ def setUp(self): self.logout() self.login(self.AUTHOR_EMAIL_2) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -162,8 +162,8 @@ def setUp(self): def test_create_suggestion(self): self.login(self.AUTHOR_EMAIL_2) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] exploration = exp_services.get_exploration_by_id(self.EXP_ID) self.post_json( @@ -193,16 +193,16 @@ def test_create_suggestion(self): def test_suggestion_to_exploration_handler_with_invalid_suggestion_id(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Invalid format of suggestion id. response = self.put_json( @@ -218,8 +218,8 @@ def test_suggestion_to_exploration_handler_with_invalid_suggestion_id(self): 'Invalid format for suggestion_id. It must contain 3 parts ' 'separated by \'.\'') - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Suggestion does not exist. self.put_json( @@ -263,8 +263,8 @@ def test_suggestion_to_exploration_handler_with_invalid_target_type(self): [('author_id', self.author_id), ( 'target_id', exp_id)])[0].suggestion_id - response = self.get_html_response('/explore/%s' % exp_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.put_json( '%s/exploration/%s/%s' % ( @@ -283,8 +283,8 @@ def test_suggestion_to_exploration_handler_with_invalid_target_type(self): def test_suggestion_to_exploration_handler_with_invalid_target_id(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( @@ -293,8 +293,8 @@ def test_suggestion_to_exploration_handler_with_invalid_target_id(self): self.save_new_default_exploration('exp_id', self.editor_id) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.put_json( '%s/exploration/%s/%s' % ( @@ -334,8 +334,8 @@ def test_owner_of_exploration_cannot_repond_to_own_suggestion(self): [('author_id', self.editor_id), ( 'target_id', exp_id)])[0].suggestion_id - response = self.get_html_response('/explore/%s' % exp_id) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.put_json( '%s/exploration/%s/%s' % ( @@ -353,16 +353,16 @@ def test_owner_of_exploration_cannot_repond_to_own_suggestion(self): def test_suggestion_to_exploration_handler_with_invalid_action(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.put_json( '%s/exploration/%s/%s' % ( @@ -380,8 +380,8 @@ def test_suggestion_to_exploration_handler_with_invalid_action(self): def test_reject_suggestion_to_exploration(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] suggestion_to_reject = self.get_json( '%s?author_id=%s' % ( @@ -394,8 +394,8 @@ def test_reject_suggestion_to_exploration(self): self.assertEqual( suggestion.status, suggestion_models.STATUS_IN_REVIEW) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, @@ -418,16 +418,16 @@ def test_accept_suggestion(self): # Test editor can accept successfully. self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -457,8 +457,8 @@ def test_accept_suggestion(self): feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id_2))['suggestions'][0] - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -476,8 +476,8 @@ def test_accept_suggestion(self): feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id_2))['suggestions'][0] - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -492,8 +492,8 @@ def test_accept_suggestion(self): suggestion_services.increment_score_for_user( self.author_id, 'content.Algebra', 15) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -514,8 +514,8 @@ def test_accept_suggestion(self): # Testing admins can accept suggestions. self.login(self.ADMIN_EMAIL) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, @@ -555,8 +555,8 @@ def test_suggestion_list_handler(self): self.assertEqual(len(suggestions), 2) def test_cannot_resubmit_suggestion_with_invalid_suggestion_id(self): - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.put_json( '%s/resubmit/%s' % ( @@ -571,8 +571,8 @@ def test_cannot_resubmit_suggestion_with_invalid_suggestion_id(self): def test_resubmit_rejected_suggestion(self): self.login(self.EDITOR_EMAIL) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] suggestion = suggestion_services.query_suggestions( [('author_id', self.author_id), ('target_id', self.EXP_ID)])[0] @@ -581,8 +581,8 @@ def test_resubmit_rejected_suggestion(self): self.logout() self.login(self.AUTHOR_EMAIL) - response = self.get_html_response('/explore/%s' % self.EXP_ID) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json('%s/resubmit/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion.suggestion_id), { @@ -641,8 +641,8 @@ def setUp(self): feconf.CURRENT_STATE_SCHEMA_VERSION) } self.login(self.AUTHOR_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -688,8 +688,8 @@ def test_accept_question_suggestion(self): )['suggestions'][0] self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): self.put_json('%s/topic/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, @@ -754,8 +754,8 @@ def setUp(self): } self.login(self.AUTHOR_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -783,8 +783,8 @@ def test_cannot_access_suggestion_to_topic_handler(self): suggestion_models.TARGET_TYPE_QUESTION, self.topic_id, self.author_id, 'description', '', has_suggestion=True) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', False): self.put_json( @@ -820,8 +820,8 @@ def test_suggestion_to_topic_handler_with_invalid_target_type(self): [('author_id', self.author_id), ( 'target_id', exp_id)])[0].suggestion_id - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): response = self.put_json( @@ -841,8 +841,8 @@ def test_suggestion_to_topic_handler_with_invalid_target_type(self): def test_suggestion_to_topic_handler_with_invalid_target_id(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( @@ -853,8 +853,8 @@ def test_suggestion_to_topic_handler_with_invalid_target_id(self): 'topic_id', self.admin_id, 'Name1', 'Description', [], [], [], [], 1) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): response = self.put_json( @@ -877,16 +877,16 @@ def test_suggestion_to_topic_handler_with_invalid_target_id(self): def test_suggestion_to_topic_handler_with_invalid_action(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): response = self.put_json( @@ -905,8 +905,8 @@ def test_suggestion_to_topic_handler_with_invalid_action(self): def test_reject_suggestion_to_topic(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] suggestion_to_reject = self.get_json( '%s?author_id=%s' % ( @@ -919,8 +919,8 @@ def test_reject_suggestion_to_topic(self): self.assertEqual( suggestion.status, suggestion_models.STATUS_IN_REVIEW) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): self.put_json('%s/topic/%s/%s' % ( @@ -942,8 +942,8 @@ def test_reject_suggestion_to_topic(self): def test_accept_suggestion_to_topic(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( @@ -956,8 +956,8 @@ def test_accept_suggestion_to_topic(self): self.assertEqual( suggestion.status, suggestion_models.STATUS_IN_REVIEW) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): self.put_json('%s/topic/%s/%s' % ( diff --git a/core/controllers/topic_editor_test.py b/core/controllers/topic_editor_test.py index 8c4f0087f692..2c2504a98a18 100644 --- a/core/controllers/topic_editor_test.py +++ b/core/controllers/topic_editor_test.py @@ -66,9 +66,8 @@ class TopicEditorStoryHandlerTests(BaseTopicEditorControllerTests): def test_story_creation(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response( - '%s/%s' % (feconf.TOPIC_EDITOR_URL_PREFIX, self.topic_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] json_response = self.post_json( '%s/%s' % (feconf.TOPIC_EDITOR_STORY_URL, self.topic_id), {'title': 'Story title'}, @@ -338,9 +337,8 @@ def test_editable_topic_handler_put(self): }] } self.login(self.ADMIN_EMAIL) - response = self.get_html_response( - '%s/%s' % (feconf.TOPIC_EDITOR_URL_PREFIX, self.topic_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] json_response = self.put_json( '%s/%s' % ( @@ -478,9 +476,8 @@ def test_editable_topic_handler_put_for_assigned_topic_manager(self): self.topic_id) self.login(self.TOPIC_MANAGER_EMAIL) - response = self.get_html_response( - '%s/%s' % (feconf.TOPIC_EDITOR_URL_PREFIX, self.topic_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Check that the topic manager can edit the topic now. json_response = self.put_json( '%s/%s' % ( @@ -523,9 +520,8 @@ class TopicManagerRightsHandlerTests(BaseTopicEditorControllerTests): def test_assign_topic_manager_role(self): """Test the assign topic manager role for a topic functionality.""" self.login(self.ADMIN_EMAIL) - response = self.get_html_response( - '%s/%s' % (feconf.TOPIC_EDITOR_URL_PREFIX, self.topic_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Test for when assignee does not have sufficient rights to become a # manager for a topic. @@ -556,9 +552,8 @@ class TopicPublishSendMailHandlerTests(BaseTopicEditorControllerTests): def test_send_mail(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response( - '%s/%s' % (feconf.TOPIC_EDITOR_URL_PREFIX, self.topic_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with self.swap(feconf, 'CAN_SEND_EMAILS', True): self.put_json( '%s/%s' % ( @@ -603,9 +598,8 @@ class TopicPublishHandlerTests(BaseTopicEditorControllerTests): def test_publish_and_unpublish_topic(self): """Test the publish and unpublish functionality.""" self.login(self.ADMIN_EMAIL) - response = self.get_html_response( - '%s/%s' % (feconf.TOPIC_EDITOR_URL_PREFIX, self.topic_id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # Test whether admin can publish and unpublish a topic. self.put_json( '%s/%s' % ( diff --git a/core/controllers/topics_and_skills_dashboard_test.py b/core/controllers/topics_and_skills_dashboard_test.py index 2101320554d0..33cb07027225 100644 --- a/core/controllers/topics_and_skills_dashboard_test.py +++ b/core/controllers/topics_and_skills_dashboard_test.py @@ -48,10 +48,8 @@ def setUp(self): def _get_csrf_token_for_put(self): """Gets the csrf token.""" - csrf_token = None - url_prefix = feconf.TOPICS_AND_SKILLS_DASHBOARD_URL - response = self.get_html_response(url_prefix) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] return csrf_token diff --git a/core/controllers/voice_artist_test.py b/core/controllers/voice_artist_test.py index 9d74a2705230..d196decac1c6 100644 --- a/core/controllers/voice_artist_test.py +++ b/core/controllers/voice_artist_test.py @@ -70,8 +70,8 @@ def setUp(self): self.login(self.VOICE_ARTIST_EMAIL) # Generate CSRF token. - response = self.get_html_response('/create/%s' % self.EXP_ID) - self.csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + self.csrf_token = response['token'] def test_put_with_no_payload_version_raises_error(self): with self.assertRaisesRegexp( @@ -197,8 +197,8 @@ def setUp(self): draft_change_list_id=1).put() # Generate CSRF token. - response = self.get_html_response('/create/%s' % self.EXP_ID) - self.csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + self.csrf_token = response['token'] def test_draft_updated_version_valid(self): payload = { @@ -277,8 +277,8 @@ def setUp(self): self.login(self.VOICE_ARTIST_EMAIL) # Generate CSRF token. - response = self.get_html_response('/create/%s' % self.EXP_ID) - self.csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + self.csrf_token = response['token'] def test_firsttime_translation_tutorial(self): """Testing of the firsttime translation tutorial http requests.""" diff --git a/core/domain/email_manager_test.py b/core/domain/email_manager_test.py index 55717c7e5d8f..35fe24d5812c 100644 --- a/core/domain/email_manager_test.py +++ b/core/domain/email_manager_test.py @@ -202,9 +202,8 @@ def test_role_email_is_sent_when_editor_assigns_role(self): with self.can_send_emails_ctx, self.can_send_editor_role_email_ctx: self.login(self.EDITOR_EMAIL) - response = self.get_html_response('%s/%s' % ( - feconf.EDITOR_URL_PREFIX, self.exploration.id)) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.put_json('%s/%s' % ( feconf.EXPLORATION_RIGHTS_PREFIX, self.exploration.id), { 'version': self.exploration.version, @@ -571,8 +570,8 @@ def test_email_not_sent_if_config_does_not_permit_it(self): self.new_email_content) self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SIGNUP_DATA_URL, { @@ -602,8 +601,8 @@ def _log_error_for_tests(error_message): self.assertEqual(log_new_error_counter.times_called, 0) self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # No user-facing error should surface. self.post_json( @@ -650,8 +649,8 @@ def _log_error_for_tests(error_message): self.assertEqual(log_new_error_counter.times_called, 0) self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # No user-facing error should surface. self.post_json( @@ -696,8 +695,8 @@ def _log_error_for_tests(error_message): self.assertEqual(log_new_error_counter.times_called, 0) self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] # No user-facing error should surface. self.post_json( @@ -728,8 +727,8 @@ def test_contents_of_signup_email_are_correct(self): 'Email Sender') self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SIGNUP_DATA_URL, { @@ -761,8 +760,8 @@ def test_email_only_sent_once_for_repeated_signups_by_same_user(self): self.new_email_content) self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SIGNUP_DATA_URL, { @@ -795,8 +794,8 @@ def test_email_only_sent_if_signup_was_successful(self): self.new_email_content) self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SIGNUP_DATA_URL, @@ -837,8 +836,8 @@ def test_record_of_sent_email_is_written_to_datastore(self): self.assertEqual(len(all_models), 0) self.login(self.EDITOR_EMAIL) - response = self.get_html_response(feconf.SIGNUP_URL) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( feconf.SIGNUP_DATA_URL, { diff --git a/core/domain/feedback_services_test.py b/core/domain/feedback_services_test.py index 1894135389d5..69f0e3153570 100644 --- a/core/domain/feedback_services_test.py +++ b/core/domain/feedback_services_test.py @@ -946,8 +946,8 @@ def test_that_emails_are_not_sent_if_already_seen(self): thread_id = threadlist[0].id self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token_from_response( - self.get_html_response('/create/%s' % self.exploration.id)) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '%s/%s' % ( feconf.FEEDBACK_THREAD_VIEW_EVENT_URL, thread_id), diff --git a/core/domain/summary_services_test.py b/core/domain/summary_services_test.py index b50cd5688199..835b8231f007 100644 --- a/core/domain/summary_services_test.py +++ b/core/domain/summary_services_test.py @@ -258,8 +258,8 @@ def setUp(self): super(LibraryGroupsTest, self).setUp() self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_html_response('/admin') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] with self.swap( html_validation_service, 'get_filename_with_dimensions', diff --git a/core/tests/test_utils.py b/core/tests/test_utils.py index 16c413149b42..463506fe0680 100644 --- a/core/tests/test_utils.py +++ b/core/tests/test_utils.py @@ -844,7 +844,8 @@ def signup(self, email, username): with self.urlfetch_mock(): response = self.get_html_response(feconf.SIGNUP_URL) self.assertEqual(response.status_int, 200) - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] response = self.testapp.post( feconf.SIGNUP_DATA_URL, params={ 'csrf_token': csrf_token, @@ -862,8 +863,8 @@ def set_config_property(self, config_obj, new_config_value): """ with self.login_context('tmpsuperadmin@example.com', is_super_admin=True): - response = self.get_html_response('/admin') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/adminhandler', { 'action': 'save_config_properties', @@ -881,8 +882,8 @@ def set_user_role(self, username, user_role): """ with self.login_context('tmpsuperadmin@example.com', is_super_admin=True): - response = self.get_html_response('/admin') - csrf_token = self.get_csrf_token_from_response(response) + response = self.get_json('/csrf') + csrf_token = response['token'] self.post_json( '/adminrolehandler', { 'username': username, From 809e4b3c69f41127ce5abafb60d18c2e54fece18 Mon Sep 17 00:00:00 2001 From: James John James Date: Mon, 17 Jun 2019 07:22:39 +0100 Subject: [PATCH 03/40] lint issues --- core/templates/dev/head/App.ts | 85 ++++++++++--------- core/templates/dev/head/pages/Base.ts | 2 +- .../dev/head/services/CsrfService.ts | 4 +- .../dev/head/services/CsrfServiceSpec.ts | 10 +-- 4 files changed, 51 insertions(+), 50 deletions(-) diff --git a/core/templates/dev/head/App.ts b/core/templates/dev/head/App.ts index 9c35ca5245e0..ca378c8712d9 100644 --- a/core/templates/dev/head/App.ts +++ b/core/templates/dev/head/App.ts @@ -192,7 +192,7 @@ oppia.config([ // warnings for error responses. $httpProvider.interceptors.push([ '$q', '$log', 'AlertsService', 'CsrfService', - function ($q, $log, AlertsService, CsrfService) { + function($q, $log, AlertsService, CsrfService) { return { request: function(config) { if (config.data) { @@ -272,49 +272,50 @@ oppia.config(['toastrConfig', function(toastrConfig) { // (so that they can be fixed). oppia.factory('$exceptionHandler', ['$log', 'CsrfService', function($log, CsrfService) { - var MIN_TIME_BETWEEN_ERRORS_MSEC = 5000; - var timeOfLastPostedError = Date.now() - MIN_TIME_BETWEEN_ERRORS_MSEC; - - return function(exception, cause) { - var messageAndSourceAndStackTrace = [ - '', - 'Cause: ' + cause, - exception.message, - String(exception.stack), - ' at URL: ' + window.location.href - ].join('\n'); - - // To prevent an overdose of errors, throttle to at most 1 error every - // MIN_TIME_BETWEEN_ERRORS_MSEC. - if (Date.now() - timeOfLastPostedError > MIN_TIME_BETWEEN_ERRORS_MSEC) { - // Catch all errors, to guard against infinite recursive loops. - try { - // We use jQuery here instead of Angular's $http, since the latter - // creates a circular dependency. - $.ajax({ - type: 'POST', - url: '/frontend_errors', - data: $.param({ - csrf_token: CsrfService.getToken(), - payload: JSON.stringify({ - error: messageAndSourceAndStackTrace - }), - source: document.URL - }, true), - contentType: 'application/x-www-form-urlencoded', - dataType: 'text', - async: true - }); - - timeOfLastPostedError = Date.now(); - } catch (loggingError) { - $log.warn('Error logging failed.'); + var MIN_TIME_BETWEEN_ERRORS_MSEC = 5000; + var timeOfLastPostedError = Date.now() - MIN_TIME_BETWEEN_ERRORS_MSEC; + + return function(exception, cause) { + var messageAndSourceAndStackTrace = [ + '', + 'Cause: ' + cause, + exception.message, + String(exception.stack), + ' at URL: ' + window.location.href + ].join('\n'); + + // To prevent an overdose of errors, throttle to at most 1 error every + // MIN_TIME_BETWEEN_ERRORS_MSEC. + if (Date.now() - timeOfLastPostedError > MIN_TIME_BETWEEN_ERRORS_MSEC) { + // Catch all errors, to guard against infinite recursive loops. + try { + // We use jQuery here instead of Angular's $http, since the latter + // creates a circular dependency. + $.ajax({ + type: 'POST', + url: '/frontend_errors', + data: $.param({ + csrf_token: CsrfService.getToken(), + payload: JSON.stringify({ + error: messageAndSourceAndStackTrace + }), + source: document.URL + }, true), + contentType: 'application/x-www-form-urlencoded', + dataType: 'text', + async: true + }); + + timeOfLastPostedError = Date.now(); + } catch (loggingError) { + $log.warn('Error logging failed.'); + } } - } - $log.error.apply($log, arguments); - }; -}]); + $log.error.apply($log, arguments); + }; + } +]); oppia.constant('LABEL_FOR_CLEARING_FOCUS', 'labelForClearingFocus'); diff --git a/core/templates/dev/head/pages/Base.ts b/core/templates/dev/head/pages/Base.ts index b5b3809e6542..4e83be756dc5 100644 --- a/core/templates/dev/head/pages/Base.ts +++ b/core/templates/dev/head/pages/Base.ts @@ -55,7 +55,7 @@ oppia.controller('Base', [ }); if (UrlService.getPathname() !== '/signup') { - CsrfService.fetchToken(); + CsrfService.fetchToken(); } // TODO(sll): use 'touchstart' for mobile. $document.on('click', function() { diff --git a/core/templates/dev/head/services/CsrfService.ts b/core/templates/dev/head/services/CsrfService.ts index c3ad29be8a85..a007c313a4f3 100644 --- a/core/templates/dev/head/services/CsrfService.ts +++ b/core/templates/dev/head/services/CsrfService.ts @@ -28,8 +28,8 @@ oppia.factory('CsrfService', [function() { }, // For Signup page - setToken: function(csrf_token) { - token = csrf_token; + setToken: function(csrfToken) { + token = csrfToken; }, getToken: function() { diff --git a/core/templates/dev/head/services/CsrfServiceSpec.ts b/core/templates/dev/head/services/CsrfServiceSpec.ts index 524d87be3477..e7b9fcf8dd28 100644 --- a/core/templates/dev/head/services/CsrfServiceSpec.ts +++ b/core/templates/dev/head/services/CsrfServiceSpec.ts @@ -18,7 +18,7 @@ require('services/CsrfService.ts'); -describe('Csrf Service', function () { +describe('Csrf Service', function() { var CsrfService, $httpBackend; beforeEach(angular.mock.module('oppia')); @@ -29,18 +29,18 @@ describe('Csrf Service', function () { it('should return the correct csrf token', function() { var response = ')]}\'{token: \'sample csrf token\'}'; - + $httpBackend.expect('GET', '/csrf').respond( 200, response); CsrfService.fetchToken(); expect(CsrfService.getToken()).toBe('sample csrf token'); - }) + }); it('should correctly set the csrf token', function() { CsrfService.setToken('sample csrf token'); expect(CsrfService.getToken()).toBe('sample csrf token'); - }) -}) + }); +}); From 3a917c397beb3d4156d452431b0db5846f55bb54 Mon Sep 17 00:00:00 2001 From: James John James Date: Mon, 17 Jun 2019 07:33:27 +0100 Subject: [PATCH 04/40] lint issues --- .../dev/head/services/AssetsBackendApiService.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core/templates/dev/head/services/AssetsBackendApiService.ts b/core/templates/dev/head/services/AssetsBackendApiService.ts index f9d6c0064c79..e7eed275a517 100644 --- a/core/templates/dev/head/services/AssetsBackendApiService.ts +++ b/core/templates/dev/head/services/AssetsBackendApiService.ts @@ -24,13 +24,13 @@ require('domain/utilities/UrlInterpolationService.ts'); require('services/CsrfService.ts'); oppia.factory('AssetsBackendApiService', [ - '$http', '$q', 'AudioFileObjectFactory', 'FileDownloadRequestObjectFactory', - 'ImageFileObjectFactory', 'CsrfService', 'UrlInterpolationService', - 'DEV_MODE', + '$http', '$q', 'AudioFileObjectFactory', 'CsrfService', + 'FileDownloadRequestObjectFactory', 'ImageFileObjectFactory', + 'UrlInterpolationService', 'DEV_MODE', function( - $http, $q, AudioFileObjectFactory, FileDownloadRequestObjectFactory, - ImageFileObjectFactory, CsrfService, UrlInterpolationService, - DEV_MODE) { + $http, $q, AudioFileObjectFactory, CsrfService, + FileDownloadRequestObjectFactory, ImageFileObjectFactory, + UrlInterpolationService, DEV_MODE) { if (!DEV_MODE && !GLOBALS.GCS_RESOURCE_BUCKET_NAME) { throw Error('GCS_RESOURCE_BUCKET_NAME is not set in prod.'); } From b7ff267e653eceb7d55c5ecadc23af0224b3ab04 Mon Sep 17 00:00:00 2001 From: James John James Date: Mon, 17 Jun 2019 10:36:20 +0100 Subject: [PATCH 05/40] work on fe tests --- core/templates/dev/head/services/CsrfService.ts | 11 ++++++----- core/templates/dev/head/services/CsrfServiceSpec.ts | 11 ----------- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/core/templates/dev/head/services/CsrfService.ts b/core/templates/dev/head/services/CsrfService.ts index a007c313a4f3..2c5b169d52d7 100644 --- a/core/templates/dev/head/services/CsrfService.ts +++ b/core/templates/dev/head/services/CsrfService.ts @@ -18,19 +18,20 @@ oppia.factory('CsrfService', [function() { var token = null; + var setToken = function(csrfToken) { + token = csrfToken; + }; + return { fetchToken: function() { fetch('/csrf').then(function(response) { return response.text(); }).then(function(response) { - token = JSON.parse(response.substring(5)).token; + setToken(JSON.parse(response.substring(5)).token); }); }, - // For Signup page - setToken: function(csrfToken) { - token = csrfToken; - }, + setToken: setToken, getToken: function() { return token; diff --git a/core/templates/dev/head/services/CsrfServiceSpec.ts b/core/templates/dev/head/services/CsrfServiceSpec.ts index e7b9fcf8dd28..436576527f33 100644 --- a/core/templates/dev/head/services/CsrfServiceSpec.ts +++ b/core/templates/dev/head/services/CsrfServiceSpec.ts @@ -27,17 +27,6 @@ describe('Csrf Service', function() { $httpBackend = $injector.get('$httpBackend'); })); - it('should return the correct csrf token', function() { - var response = ')]}\'{token: \'sample csrf token\'}'; - - $httpBackend.expect('GET', '/csrf').respond( - 200, response); - - CsrfService.fetchToken(); - - expect(CsrfService.getToken()).toBe('sample csrf token'); - }); - it('should correctly set the csrf token', function() { CsrfService.setToken('sample csrf token'); From efe0d3c8338c496aeb2045d4e6c857dfedf4e648 Mon Sep 17 00:00:00 2001 From: James John James Date: Mon, 17 Jun 2019 12:28:10 +0100 Subject: [PATCH 06/40] working on failing tests --- core/controllers/admin_test.py | 25 ++-- core/controllers/base_test.py | 7 +- core/controllers/collection_editor_test.py | 25 ++-- core/controllers/creator_dashboard_test.py | 18 +-- core/controllers/editor_test.py | 76 ++++-------- core/controllers/email_dashboard_test.py | 60 ++++------ core/controllers/feedback_test.py | 36 ++---- core/controllers/learner_dashboard_test.py | 3 +- core/controllers/learner_playlist_test.py | 6 +- core/controllers/library_test.py | 6 +- core/controllers/moderator_test.py | 3 +- core/controllers/profile_test.py | 60 ++++------ core/controllers/question_editor_test.py | 48 +++----- core/controllers/reader_test.py | 30 ++--- core/controllers/resources_test.py | 69 ++++------- core/controllers/skill_editor_test.py | 3 +- core/controllers/story_editor_test.py | 3 +- core/controllers/subscriptions_test.py | 15 +-- core/controllers/suggestion_test.py | 110 ++++++------------ core/controllers/topic_editor_test.py | 18 +-- .../topics_and_skills_dashboard_test.py | 3 +- core/controllers/voice_artist_test.py | 9 +- core/domain/email_manager_test.py | 27 ++--- core/domain/feedback_services_test.py | 3 +- core/domain/summary_services_test.py | 3 +- core/tests/test_utils.py | 20 ++-- 26 files changed, 230 insertions(+), 456 deletions(-) diff --git a/core/controllers/admin_test.py b/core/controllers/admin_test.py index 99869d2b08f7..8cb707993e86 100644 --- a/core/controllers/admin_test.py +++ b/core/controllers/admin_test.py @@ -56,8 +56,7 @@ def test_change_configuration_property(self): """Test that configuration properties can be changed.""" self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() new_config_value = True response_dict = self.get_json('/adminhandler') @@ -92,8 +91,7 @@ class GenerateDummyExplorationsTest(test_utils.GenericTestBase): def test_generate_count_greater_than_publish_count(self): self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/adminhandler', { 'action': 'generate_dummy_explorations', @@ -108,8 +106,7 @@ def test_generate_count_greater_than_publish_count(self): def test_generate_count_equal_to_publish_count(self): self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/adminhandler', { 'action': 'generate_dummy_explorations', @@ -124,8 +121,7 @@ def test_generate_count_equal_to_publish_count(self): def test_generate_count_less_than_publish_count(self): self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() generated_exps_response = self.post_json( '/adminhandler', { 'action': 'generate_dummy_explorations', @@ -164,8 +160,7 @@ def test_view_and_update_role(self): response_dict, {'user1': feconf.ROLE_ID_EXPLORATION_EDITOR}) # Check role correctly gets updated. - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response_dict = self.post_json( feconf.ADMIN_ROLE_HANDLER_URL, {'role': feconf.ROLE_ID_MODERATOR, 'username': username}, @@ -186,15 +181,14 @@ def test_invalid_username_in_view_and_update_role(self): self.login(self.ADMIN_EMAIL, is_super_admin=True) # Trying to view role of non-existent user. - response = self.get_json( + self.get_json( feconf.ADMIN_ROLE_HANDLER_URL, params={'method': 'username', 'username': username}, expected_status_int=400) # Trying to update role of non-existent user. - response = self.get_json('/csrf') - csrf_token = response['token'] - response = self.post_json( + csrf_token = self.get_csrf_token() + self.post_json( feconf.ADMIN_ROLE_HANDLER_URL, {'role': feconf.ROLE_ID_MODERATOR, 'username': username}, csrf_token=csrf_token, @@ -294,8 +288,7 @@ def test_clear_search_index(self): self.assertEqual(result_collections, ['0']) self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() generated_exps_response = self.post_json( '/adminhandler', { 'action': 'clear_search_index' diff --git a/core/controllers/base_test.py b/core/controllers/base_test.py index c93469e3c684..1adfb41595fe 100644 --- a/core/controllers/base_test.py +++ b/core/controllers/base_test.py @@ -857,8 +857,7 @@ def test_error_is_raised_on_opening_new_tab_during_signup(self): during signup. """ self.login('abc@example.com') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.get_html_response('/about', expected_status_int=302) self.assertIn('Logout', response.location) @@ -878,9 +877,7 @@ def test_no_error_is_raised_on_opening_new_tab_after_signup(self): after signup. """ self.login('abc@example.com') - response = self.get_json('/csrf') - csrf_token = response['token'] - + csrf_token = self.get_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, { 'username': 'abc', diff --git a/core/controllers/collection_editor_test.py b/core/controllers/collection_editor_test.py index f21444f33a92..415f16b0e5a4 100644 --- a/core/controllers/collection_editor_test.py +++ b/core/controllers/collection_editor_test.py @@ -132,8 +132,7 @@ def test_editable_collection_handler_put_with_invalid_payload_version(self): self.login(self.EDITOR_EMAIL) # Call get handler to return the csrf token. - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Raises error as version is None. json_response = self.put_json( @@ -177,8 +176,7 @@ def test_editable_collection_handler_put_cannot_access(self): self.login(self.VIEWER_EMAIL) # Call get handler to return the csrf token. - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Ensure viewers do not have access to the PUT Handler. self.put_json( @@ -205,9 +203,7 @@ def test_editable_collection_handler_put_can_access(self): self.login(self.EDITOR_EMAIL) # Call get handler to return the csrf token. - response = self.get_json('/csrf') - csrf_token = response['token'] - + csrf_token = self.get_csrf_token() json_response = self.put_json( '%s/%s' % ( feconf.COLLECTION_EDITOR_DATA_URL_PREFIX, @@ -284,8 +280,7 @@ def test_can_not_publish_collection_with_invalid_payload_version(self): self.save_new_valid_collection( collection_id, self.owner_id, exploration_id=exploration_id) rights_manager.publish_exploration(self.owner, exploration_id) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Raises error as version is None. response_dict = self.put_json( @@ -321,8 +316,7 @@ def test_can_not_unpublish_collection_with_invalid_payload_version(self): collection_id, self.owner_id, exploration_id=exploration_id) rights_manager.publish_exploration(self.owner, exploration_id) collection = collection_services.get_collection_by_id(collection_id) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response_dict = self.put_json( '/collection_editor_handler/publish/%s' % collection_id, {'version': collection.version}, @@ -332,8 +326,7 @@ def test_can_not_unpublish_collection_with_invalid_payload_version(self): # Login as admin and try to unpublish the collection. self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Raises error as version is None. response_dict = self.put_json( @@ -370,8 +363,7 @@ def test_publish_unpublish_collection(self): collection_id, self.owner_id, exploration_id=exploration_id) rights_manager.publish_exploration(self.owner, exploration_id) collection = collection_services.get_collection_by_id(collection_id) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response_dict = self.put_json( '/collection_editor_handler/publish/%s' % collection_id, {'version': collection.version}, @@ -381,8 +373,7 @@ def test_publish_unpublish_collection(self): # Login as admin and unpublish the collection. self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response_dict = self.put_json( '/collection_editor_handler/unpublish/%s' % collection_id, {'version': collection.version}, diff --git a/core/controllers/creator_dashboard_test.py b/core/controllers/creator_dashboard_test.py index 25164c39ded9..96a07b7c18ce 100644 --- a/core/controllers/creator_dashboard_test.py +++ b/core/controllers/creator_dashboard_test.py @@ -726,8 +726,7 @@ def test_can_update_display_preference(self): display_preference = self.get_json( feconf.CREATOR_DASHBOARD_DATA_URL)['display_preference'] self.assertEqual(display_preference, 'card') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.CREATOR_DASHBOARD_DATA_URL, {'display_preference': 'list'}, @@ -740,8 +739,7 @@ def test_can_update_display_preference(self): def test_can_create_collections(self): self.set_admins([self.OWNER_USERNAME]) self.login(self.OWNER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() collection_id = self.post_json( feconf.NEW_COLLECTION_URL, {}, csrf_token=csrf_token)[ creator_dashboard.COLLECTION_ID_KEY] @@ -886,8 +884,7 @@ def test_new_exploration_ids(self): """Test generation of exploration ids.""" self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() exp_a_id = self.post_json( feconf.NEW_EXPLORATION_URL, {}, csrf_token=csrf_token )[creator_dashboard.EXPLORATION_ID_KEY] @@ -897,8 +894,7 @@ def test_new_exploration_ids(self): def test_can_non_admins_can_not_upload_exploration(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.post_json( feconf.UPLOAD_EXPLORATION_URL, {}, csrf_token=csrf_token, @@ -914,8 +910,7 @@ def test_can_upload_exploration(self): self.set_admins([self.ADMIN_USERNAME]) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() explorations_list = self.get_json( feconf.CREATOR_DASHBOARD_DATA_URL)['explorations_list'] self.assertEqual(explorations_list, []) @@ -935,8 +930,7 @@ def test_can_not_upload_exploration_when_server_does_not_allow_file_upload( self): self.set_admins([self.ADMIN_USERNAME]) self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s?yaml_file=%s' % ( feconf.UPLOAD_EXPLORATION_URL, diff --git a/core/controllers/editor_test.py b/core/controllers/editor_test.py index c0857f347354..762264ecda75 100644 --- a/core/controllers/editor_test.py +++ b/core/controllers/editor_test.py @@ -143,14 +143,12 @@ def test_that_default_exploration_cannot_be_published(self): """ self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() exp_id = self.post_json( feconf.NEW_EXPLORATION_URL, {}, csrf_token=csrf_token )[creator_dashboard.EXPLORATION_ID_KEY] - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() publish_url = '%s/%s' % (feconf.EXPLORATION_STATUS_PREFIX, exp_id) self.put_json( publish_url, { @@ -164,8 +162,7 @@ def test_add_new_state_error_cases(self): current_version = 1 self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() def _get_payload(new_state_name, version=None): """Gets the payload in the dict format.""" @@ -240,8 +237,7 @@ def test_publish_exploration(self): exp_id = exp_services.get_new_exploration_id() self.save_new_valid_exploration( exp_id, self.admin_id, end_state_name='end state') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() publish_url = '%s/%s' % (feconf.EXPLORATION_STATUS_PREFIX, exp_id) exploration_rights = self.put_json( @@ -597,8 +593,7 @@ def test_state_yaml_handler(self): exploration.add_states(['State A', 'State 2', 'State 3']) exploration.states['State A'].update_interaction_id('TextInput') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.post_json('/createhandler/state_yaml/%s' % exp_id, { 'state_dict': exploration.states['State A'].to_dict(), 'width': 50, @@ -615,8 +610,7 @@ def test_state_yaml_handler_with_no_state_dict_raises_error(self): owner_id = self.get_user_id_from_email(self.OWNER_EMAIL) self.save_new_valid_exploration(exp_id, owner_id) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/createhandler/state_yaml/%s' % exp_id, {}, @@ -766,8 +760,7 @@ def test_record_user_saw_tutorial(self): self.save_new_valid_exploration(exp_id, owner_id) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() user_settings = user_services.get_user_settings(owner_id) @@ -1113,8 +1106,7 @@ def test_get_with_disabled_exploration_id_raises_error(self): def test_reverting_to_old_exploration(self): """Test reverting to old exploration versions.""" # Open editor page. - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # May not revert to any version that's not 1. for rev_version in (-1, 0, 2, 3, 4, '1', ()): @@ -1198,8 +1190,7 @@ def test_versioning_for_default_exploration(self): expected_status_int=404) def test_revert_with_invalid_current_version_raises_error(self): - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.post_json( '/createhandler/revert/%s' % self.EXP_ID, { @@ -1287,8 +1278,7 @@ def test_for_assign_role_for_exploration(self): exploration.states['State 2'].update_interaction_id('TextInput') exploration.states['State 3'].update_interaction_id('TextInput') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Owner adds rights for other users. rights_url = '%s/%s' % (feconf.EXPLORATION_RIGHTS_PREFIX, exp_id) @@ -1331,8 +1321,7 @@ def test_for_assign_role_for_exploration(self): response = self.get_html_response('/create/%s' % exp_id) self.assert_can_edit(response.body) self.assert_can_voiceover(response.body) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Check that collaborator can add a new state called 'State 4'. add_url = '%s/%s' % (feconf.EXPLORATION_DATA_PREFIX, exp_id) @@ -1373,8 +1362,7 @@ def test_for_assign_role_for_exploration(self): self.login(self.COLLABORATOR2_EMAIL) response = self.get_html_response('/create/%s' % exp_id) self.assert_can_edit(response.body) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Check that collaborator2 can add a new state called 'State 5'. add_url = '%s/%s' % (feconf.EXPLORATION_DATA_PREFIX, exp_id) @@ -1415,8 +1403,7 @@ def test_for_assign_role_for_exploration(self): response = self.get_html_response('/create/%s' % exp_id) self.assert_cannot_edit(response.body) self.assert_can_voiceover(response.body) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Check that voice artist cannot add new members. exploration = exp_services.get_exploration_by_id(exp_id) @@ -1440,8 +1427,7 @@ def test_transfering_ownership_to_the_community(self): self.save_new_valid_exploration( exp_id, self.owner_id, title='My Exploration', end_state_name='END') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() rights_manager.publish_exploration(self.owner, exp_id) # Owner transfers ownership to the community. @@ -1494,8 +1480,7 @@ def test_cannot_transfer_ownership_of_invalid_exp_to_the_community(self): # The exploration is now invalid due to invalid language code. # Therefore, the following PUT request will raise an exception after # creating a domain object from the exploration model and validating it. - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() rights_url = '%s/%s' % (feconf.EXPLORATION_RIGHTS_PREFIX, exp_id) response = self.put_json( @@ -1520,8 +1505,7 @@ def test_put_with_invalid_new_member_raises_error(self): self.login(self.OWNER_EMAIL) exp_id = 'exp_id' self.save_new_valid_exploration(exp_id, self.owner_id) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() exploration = exp_services.get_exploration_by_id(exp_id) response = self.put_json( @@ -1539,8 +1523,7 @@ def test_make_private_exploration_viewable(self): self.login(self.OWNER_EMAIL) exp_id = 'exp_id' self.save_new_valid_exploration(exp_id, self.owner_id) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() exploration = exp_services.get_exploration_by_id(exp_id) exploration_rights = rights_manager.get_exploration_rights(exp_id) self.assertFalse(exploration_rights.viewable_if_private) @@ -1557,8 +1540,7 @@ def test_put_with_no_specified_changes_raise_error(self): self.login(self.OWNER_EMAIL) exp_id = 'exp_id' self.save_new_valid_exploration(exp_id, self.owner_id) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() exploration = exp_services.get_exploration_by_id(exp_id) response = self.put_json( @@ -1585,9 +1567,7 @@ def test_user_exploration_emails_handler(self): exploration = exp_services.get_exploration_by_id(exp_id) - response = self.get_json('/csrf') - csrf_token = response['token'] - + csrf_token = self.get_csrf_token() exp_email_preferences = ( user_services.get_email_preferences_for_exploration( self.owner_id, exp_id)) @@ -1634,8 +1614,7 @@ def test_put_with_invalid_message_type_raises_error(self): self.login(self.OWNER_EMAIL) exp_id = 'eid' self.save_new_valid_exploration(exp_id, self.owner_id) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.put_json( '%s/%s' % (feconf.USER_EXPLORATION_EMAILS_PREFIX, exp_id), @@ -1683,8 +1662,7 @@ def test_error_cases_for_email_sending(self): self.login(self.MODERATOR_EMAIL) # Get csrf token. - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Try to unpublish the exploration without an email body. This # should cause an error. @@ -1736,8 +1714,7 @@ def test_email_is_sent_correctly_when_unpublishing(self): self.login(self.MODERATOR_EMAIL) # Go to the exploration editor page. - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() new_email_body = 'Your exploration is unpublished :(' @@ -1797,8 +1774,7 @@ def test_email_functionality_cannot_be_used_by_non_moderators(self): self.login(self.EDITOR_EMAIL) # Go to the exploration editor page. - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() new_email_body = 'Your exploration is unpublished :(' @@ -2063,8 +2039,7 @@ def setUp(self): 'is_valid': True } - response = self.get_json('/csrf') - self.csrf_token = response['token'] + self.csrf_token = self.get_csrf_token() def test_resolve_issue_handler(self): """Test that resolving an issue deletes associated playthroughs.""" @@ -2185,8 +2160,7 @@ def setUp(self): self._create_exp_user_data_model_objects_for_tests() # Generate CSRF token. - response = self.get_json('/csrf') - self.csrf_token = response['token'] + self.csrf_token = self.get_csrf_token() def test_exploration_loaded_with_draft_applied(self): response = self.get_json( diff --git a/core/controllers/email_dashboard_test.py b/core/controllers/email_dashboard_test.py index e3ac0cd7a206..22651dbaaa9d 100644 --- a/core/controllers/email_dashboard_test.py +++ b/core/controllers/email_dashboard_test.py @@ -45,8 +45,7 @@ def setUp(self): def test_that_handler_works_correctly(self): self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -127,8 +126,7 @@ def test_that_page_is_accessible_to_authorised_users_only(self): def test_that_exception_is_raised_for_invalid_input(self): self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -260,8 +258,7 @@ def test_email_dashboard_result_page_with_invalid_query_id_raises_400(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.post_json( '/emaildashboardresult/%s' % 'invalid_query_id', {}, @@ -304,8 +301,7 @@ def test_email_dashboard_result_page_with_mismatch_of_query_id_raises_401( taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Raises authorization error when passing a query id whose associated # query model is not created by the logged in user. @@ -343,8 +339,7 @@ def test_cancel_email_handler_with_invalid_query_id_raises_400(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.post_json( '/emaildashboardcancelresult/%s' % 'invalid_query_id', {}, @@ -386,8 +381,7 @@ def test_cancel_email_handler_with_mismatch_of_query_id_raises_401(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Raises authorization error when passing a query id whose associated # query model is not created by the logged in user. response = self.post_json( @@ -424,8 +418,7 @@ def test_bulk_email_handler_with_invalid_query_id_raises_400(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.post_json( '/emaildashboardtestbulkemailhandler/%s' % 'invalid_query_id', {}, @@ -467,8 +460,7 @@ def test_bulk_email_handler_with_mismatch_of_query_id_raises_401(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Raises authorization error when passing a query id whose associated # query model is not created by the logged in user. @@ -483,8 +475,7 @@ def test_bulk_email_handler_with_mismatch_of_query_id_raises_401(self): def test_that_correct_emails_are_sent_to_all_users(self): self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -521,8 +512,7 @@ def test_that_correct_emails_are_sent_to_all_users(self): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboardresult/%s' % query_model.id, { 'data': { @@ -585,8 +575,7 @@ def test_that_valid_exceptions_are_raised(self): with self.assertRaisesRegexp(Exception, '400 Bad Request'): self.get_html_response('/emaildashboardresult/%s' % 'q123') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -638,8 +627,7 @@ def test_that_valid_exceptions_are_raised(self): with self.swap(feconf, 'CAN_SEND_EMAILS', True): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboardresult/%s' % query_models[0].id, { 'data': { @@ -661,8 +649,7 @@ def test_that_valid_exceptions_are_raised(self): def test_that_correct_emails_are_sent_to_max_n_recipients(self): self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -685,8 +672,7 @@ def test_that_correct_emails_are_sent_to_max_n_recipients(self): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboardresult/%s' % query_models[0].id, { 'data': { @@ -708,8 +694,7 @@ def test_that_correct_emails_are_sent_to_max_n_recipients(self): def test_that_no_emails_are_sent_if_query_is_canceled(self): self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -732,8 +717,7 @@ def test_that_no_emails_are_sent_if_query_is_canceled(self): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboardcancelresult/%s' % query_models[0].id, {}, csrf_token=csrf_token) @@ -747,8 +731,7 @@ def test_that_no_emails_are_sent_if_query_is_canceled(self): def test_that_test_email_for_bulk_emails_is_sent(self): self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -771,8 +754,7 @@ def test_that_test_email_for_bulk_emails_is_sent(self): # Check that correct test email is sent. self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboardtestbulkemailhandler/%s' % query_models[0].id, { 'email_body': email_body, @@ -810,8 +792,7 @@ def test_that_test_email_for_bulk_emails_is_sent(self): def test_that_test_email_is_not_sent_to_query_recipients(self): self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -830,8 +811,7 @@ def test_that_test_email_is_not_sent_to_query_recipients(self): self.process_and_flush_pending_tasks() self.login(self.SUBMITTER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/emaildashboardtestbulkemailhandler/%s' % query_models[0].id, { 'email_body': 'email_body', diff --git a/core/controllers/feedback_test.py b/core/controllers/feedback_test.py index 3dd9aec51e22..499d2ebac688 100644 --- a/core/controllers/feedback_test.py +++ b/core/controllers/feedback_test.py @@ -54,8 +54,7 @@ def setUp(self): # The corresponding user has already registered as an editor, and has a # username. self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - self.csrf_token = response['token'] + self.csrf_token = self.get_csrf_token() self.post_json('%s/%s' % ( feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID ), { @@ -131,8 +130,7 @@ def setUp(self): def test_create_thread(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { 'subject': u'New Thread ¡unicode!', @@ -164,8 +162,7 @@ def test_create_thread(self): def test_missing_thread_subject_raises_400_error(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response_dict = self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { 'state_name': None, @@ -177,8 +174,7 @@ def test_missing_thread_subject_raises_400_error(self): def test_missing_thread_text_raises_400_error(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response_dict = self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { @@ -192,8 +188,7 @@ def test_missing_thread_text_raises_400_error(self): def test_post_message_to_existing_thread(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # First, create a thread. self.post_json( @@ -252,8 +247,7 @@ def test_no_username_shown_for_logged_out_learners(self): exp_services.save_new_exploration(self.editor_id, exploration) rights_manager.publish_exploration(self.editor, new_exp_id) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/explorehandler/give_feedback/%s' % new_exp_id, { @@ -275,8 +269,7 @@ def test_no_username_shown_for_logged_out_learners(self): def test_message_id_assignment_for_multiple_posts_to_same_thread(self): # Create a thread for others to post to. self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { 'state_name': None, @@ -323,8 +316,7 @@ def _get_email(index): # Each of these users posts a new message to the same thread. for num in range(num_users): self.login(_get_email(num)) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( thread_url, { 'text': 'New Message %s' % num @@ -411,8 +403,7 @@ def _get_message_ids_in_a_thread(self, thread_id): def test_feedback_threads(self): self.login(self.USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json('%s/%s' % ( feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID @@ -438,8 +429,7 @@ def test_feedback_threads(self): self.logout() self.login(self.OWNER_EMAIL_1) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # The owner opens the feedback thread. thread_url = '%s/%s' % (feconf.FEEDBACK_THREAD_URL_PREFIX, thread_id) @@ -468,8 +458,7 @@ def test_feedback_threads(self): self.logout() self.login(self.USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # The user opens the feedback thread. thread_url = '%s/%s' % (feconf.FEEDBACK_THREAD_URL_PREFIX, thread_id) @@ -498,8 +487,7 @@ def test_feedback_threads(self): # Another owner logs in. self.login(self.OWNER_EMAIL_2) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # The second owner opens the feedback thread. thread_url = '%s/%s' % (feconf.FEEDBACK_THREAD_URL_PREFIX, thread_id) diff --git a/core/controllers/learner_dashboard_test.py b/core/controllers/learner_dashboard_test.py index ba4f643bc839..30466d25b9b1 100644 --- a/core/controllers/learner_dashboard_test.py +++ b/core/controllers/learner_dashboard_test.py @@ -290,8 +290,7 @@ def setUp(self): self.editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL) # Get the CSRF token and create a single thread with a single message. self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - self.csrf_token = response['token'] + self.csrf_token = self.get_csrf_token() self.post_json('%s/%s' % ( feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID_1 ), { diff --git a/core/controllers/learner_playlist_test.py b/core/controllers/learner_playlist_test.py index 92179dea2f80..fd9f28b3694c 100644 --- a/core/controllers/learner_playlist_test.py +++ b/core/controllers/learner_playlist_test.py @@ -71,8 +71,7 @@ def setUp(self): def test_add_exploration_to_learner_playlist(self): self.login(self.VIEWER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Add one exploration to the playlist. self.post_json( @@ -169,8 +168,7 @@ def test_add_exploration_to_learner_playlist(self): def test_add_collection_to_learner_playlist(self): self.login(self.VIEWER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Add one collection to the playlist. self.post_json( diff --git a/core/controllers/library_test.py b/core/controllers/library_test.py index 376e8e11b6f3..7e635bab7c8a 100644 --- a/core/controllers/library_test.py +++ b/core/controllers/library_test.py @@ -273,8 +273,7 @@ def test_library_index_handler_for_user_preferred_language(self): 'preferred_language_codes': ['en'], }, response_dict) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Change the user's preferred language to de. self.put_json( @@ -402,8 +401,7 @@ def test_library_group_page_for_user_preferred_language(self): 'preferred_language_codes': ['en'], }, response_dict) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json( feconf.PREFERENCES_DATA_URL, diff --git a/core/controllers/moderator_test.py b/core/controllers/moderator_test.py index b2d79c5d44e4..d72afaf11798 100644 --- a/core/controllers/moderator_test.py +++ b/core/controllers/moderator_test.py @@ -69,8 +69,7 @@ def setUp(self): def test_unpublished_activities_cannot_be_added_to_featured_list(self): self.login(self.MODERATOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Posting a list that includes private activities results in an error. self.post_json( diff --git a/core/controllers/profile_test.py b/core/controllers/profile_test.py index c21874b19c22..33fc7912e54e 100644 --- a/core/controllers/profile_test.py +++ b/core/controllers/profile_test.py @@ -49,8 +49,7 @@ def test_going_somewhere_else_while_signing_in_logs_user_out(self): def test_to_check_url_redirection_in_signup(self): """To validate the redirections from return_url.""" self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Registering this user fully. self.post_json( @@ -93,8 +92,7 @@ def strip_domain_from_location_header(url): def test_accepting_terms_is_handled_correctly(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response_dict = self.post_json( feconf.SIGNUP_DATA_URL, {'agreed_to_terms': False}, @@ -117,8 +115,7 @@ def test_accepting_terms_is_handled_correctly(self): def test_username_is_handled_correctly(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response_dict = self.post_json( feconf.SIGNUP_DATA_URL, {'agreed_to_terms': True}, @@ -154,8 +151,7 @@ def test_username_is_handled_correctly(self): def test_default_dashboard_for_new_users(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # This user should have the creator dashboard as default. self.post_json( @@ -173,8 +169,7 @@ def test_default_dashboard_for_new_users(self): self.logout() self.login(self.VIEWER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # This user should have the learner dashboard as default. self.post_json( @@ -225,8 +220,7 @@ def test_username_check(self): self.signup('abc@example.com', username='abc') self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response_dict = self.post_json( feconf.USERNAME_CHECK_DATA_URL, {'username': 'abc'}, @@ -264,8 +258,7 @@ class EmailPreferencesTests(test_utils.GenericTestBase): def test_user_not_setting_email_prefs_on_signup(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, {'username': 'abc', 'agreed_to_terms': True}, @@ -301,8 +294,7 @@ def test_user_not_setting_email_prefs_on_signup(self): def test_user_allowing_emails_on_signup(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, {'username': 'abc', 'agreed_to_terms': True, @@ -338,8 +330,7 @@ def test_user_allowing_emails_on_signup(self): def test_user_disallowing_emails_on_signup(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, {'username': 'abc', 'agreed_to_terms': True, @@ -382,8 +373,7 @@ def test_email_preferences_updates(self): self.signup(self.EDITOR_EMAIL, username=self.EDITOR_USERNAME) editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL) self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() payload = { 'update_type': 'email_preferences', @@ -462,8 +452,7 @@ def test_can_see_subscriptions(self): def test_can_update_profile_picture_data_url(self): self.login(self.OWNER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() user_settings = user_services.get_user_settings(self.owner_id) self.assertTrue( user_settings.profile_picture_data_url.startswith( @@ -481,8 +470,7 @@ def test_can_update_profile_picture_data_url(self): def test_can_update_default_dashboard(self): self.login(self.OWNER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() user_settings = user_services.get_user_settings(self.owner_id) self.assertIsNone(user_settings.default_dashboard) self.put_json( @@ -497,8 +485,7 @@ def test_can_update_default_dashboard(self): def test_update_preferences_with_invalid_update_type_raises_exception(self): self.login(self.OWNER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with self.assertRaisesRegexp(Exception, 'Invalid update type:'): self.put_json( feconf.PREFERENCES_DATA_URL, @@ -534,8 +521,7 @@ class ProfileDataHandlerTests(test_utils.GenericTestBase): def test_preference_page_updates(self): self.signup(self.EDITOR_EMAIL, username=self.EDITOR_USERNAME) self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() original_preferences = self.get_json('/preferenceshandler/data') self.assertEqual( ['en'], original_preferences['preferred_language_codes']) @@ -562,8 +548,7 @@ def test_preference_page_updates(self): def test_profile_data_is_independent_of_currently_logged_in_user(self): self.signup(self.EDITOR_EMAIL, username=self.EDITOR_USERNAME) self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json( '/preferenceshandler/data', {'update_type': 'user_bio', 'data': 'My new editor bio'}, @@ -576,8 +561,7 @@ def test_profile_data_is_independent_of_currently_logged_in_user(self): self.signup(self.VIEWER_EMAIL, username=self.VIEWER_USERNAME) self.login(self.VIEWER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json( '/preferenceshandler/data', {'update_type': 'user_bio', 'data': 'My new viewer bio'}, @@ -775,8 +759,7 @@ def test_save_site_language_handler(self): """ language_code = 'es' self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json( '/preferenceshandler/data', { 'update_type': 'preferred_site_language_code', @@ -795,8 +778,7 @@ def test_can_update_site_language_code(self): user_settings = user_services.get_user_settings( self.editor_id, strict=True) self.assertIsNone(user_settings.preferred_site_language_code) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json( feconf.SITE_LANGUAGE_DATA_URL, payload={'site_language_code': 'en'}, csrf_token=csrf_token) @@ -815,8 +797,7 @@ class LongUserBioHandlerTests(test_utils.GenericTestBase): def test_userbio_within_limit(self): self.signup(self.EMAIL_A, self.USERNAME_A) self.login(self.EMAIL_A) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json( '/preferenceshandler/data', { 'update_type': 'user_bio', @@ -831,8 +812,7 @@ def test_userbio_within_limit(self): def test_user_bio_exceeds_limit(self): self.signup(self.EMAIL_B, self.USERNAME_B) self.login(self.EMAIL_B) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() user_bio_response = self.put_json( '/preferenceshandler/data', { 'update_type': 'user_bio', diff --git a/core/controllers/question_editor_test.py b/core/controllers/question_editor_test.py index c1b80fb7e338..9cb770bdf2ff 100644 --- a/core/controllers/question_editor_test.py +++ b/core/controllers/question_editor_test.py @@ -68,8 +68,7 @@ def setUp(self): def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): self.login(self.NEW_USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/%s' % (feconf.NEW_QUESTION_URL, self.skill_id), {}, csrf_token=csrf_token, expected_status_int=401) @@ -77,8 +76,7 @@ def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): def test_post_with_editor_email_does_not_allow_question_creation(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() question_dict = self.question.to_dict() question_dict['id'] = None self.post_json( @@ -89,8 +87,7 @@ def test_post_with_editor_email_does_not_allow_question_creation(self): def test_post_with_incorrect_skill_id_returns_404(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() incorrect_skill_id = 'abc123456789' self.post_json( '%s/%s' % (feconf.NEW_QUESTION_URL, incorrect_skill_id), @@ -99,8 +96,7 @@ def test_post_with_incorrect_skill_id_returns_404(self): def test_post_with_incorrect_question_id_returns_400(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() question_dict = self.question.to_dict() question_dict['id'] = 'abc123456789' self.post_json( @@ -111,8 +107,7 @@ def test_post_with_incorrect_question_id_returns_400(self): def test_post_with_incorrect_question_schema_returns_400(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() question_dict = self.question.to_dict() del question_dict['question_state_data']['content'] self.post_json( @@ -123,8 +118,7 @@ def test_post_with_incorrect_question_schema_returns_400(self): def test_post_with_admin_email_allows_question_creation(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() question_dict = self.question.to_dict() question_dict['id'] = None self.post_json( @@ -141,8 +135,7 @@ def test_post_with_admin_email_allows_question_creation(self): def test_post_with_topic_manager_email_allows_question_creation(self): self.login(self.TOPIC_MANAGER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() question_dict = self.question.to_dict() question_dict['id'] = None self.post_json( @@ -159,8 +152,7 @@ def test_post_with_topic_manager_email_allows_question_creation(self): def test_post_with_invalid_question_returns_400_status(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() question_dict = self.question.to_dict() question_dict['id'] = None question_dict['question_state_data'] = 'invalid_question_state_data' @@ -186,8 +178,7 @@ def setUp(self): def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): self.login(self.NEW_USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/%s/%s' % ( feconf.QUESTION_SKILL_LINK_URL_PREFIX, self.question_id, @@ -197,8 +188,7 @@ def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): def test_post_with_incorrect_skill_id_returns_404(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() incorrect_skill_id = 'abc123456789' self.post_json( '%s/%s/%s' % ( @@ -209,8 +199,7 @@ def test_post_with_incorrect_skill_id_returns_404(self): def test_post_with_admin_email_allows_question_linking(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/%s/%s' % ( feconf.QUESTION_SKILL_LINK_URL_PREFIX, self.question_id, @@ -228,8 +217,7 @@ def test_post_with_admin_email_allows_question_linking(self): def test_post_with_topic_manager_email_allows_question_linking(self): self.login(self.TOPIC_MANAGER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/%s/%s' % ( feconf.QUESTION_SKILL_LINK_URL_PREFIX, self.question_id, @@ -443,8 +431,7 @@ def test_put_with_admin_email_allows_question_editing(self): payload['commit_message'] = 'update question data' self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response_json = self.put_json( '%s/%s' % ( feconf.QUESTION_EDITOR_DATA_URL_PREFIX, self.question_id), @@ -489,8 +476,7 @@ def test_put_with_topic_manager_email_allows_question_editing(self): payload['commit_message'] = 'update question data' self.login(self.TOPIC_MANAGER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() payload = {} new_question_data = self._create_valid_question_data('GHI') change_list = [{ @@ -528,8 +514,7 @@ def test_put_with_editor_email_allows_question_editing(self): payload['commit_message'] = 'update question data' self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() payload = {} new_question_data = self._create_valid_question_data('GHI') change_list = [{ @@ -565,8 +550,7 @@ def test_put_with_creating_new_fully_specified_question_returns_400(self): payload['change_list'] = change_list payload['commit_message'] = 'update question data' self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json( '%s/%s' % ( feconf.QUESTION_EDITOR_DATA_URL_PREFIX, self.question_id), diff --git a/core/controllers/reader_test.py b/core/controllers/reader_test.py index b3b7b3b61e9d..85ddf8b722e8 100644 --- a/core/controllers/reader_test.py +++ b/core/controllers/reader_test.py @@ -436,8 +436,7 @@ def test_assign_and_read_ratings(self): self.signup('user@example.com', 'user') self.login('user@example.com') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # User checks rating. ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) @@ -478,8 +477,7 @@ def test_non_logged_in_users_cannot_rate(self): self.signup('user@example.com', 'user') self.login('user@example.com') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.logout() ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) @@ -501,8 +499,7 @@ def test_ratings_by_different_users(self): self.signup('b@example.com', 'b') self.login('a@example.com') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json( '/explorehandler/rating/%s' % self.EXP_ID, { 'user_rating': 4 @@ -511,8 +508,7 @@ def test_ratings_by_different_users(self): self.logout() self.login('b@example.com') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) self.assertEqual(ratings['user_rating'], None) self.put_json( @@ -1016,8 +1012,7 @@ def test_that_emails_are_sent(self): # Login and flag exploration. self.login(self.NEW_USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/%s' % (feconf.FLAG_EXPLORATION_URL_PREFIX, self.EXP_ID), { @@ -1071,8 +1066,7 @@ def test_non_logged_in_users_cannot_report(self): """Check that non-logged in users cannot report.""" self.login(self.NEW_USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.logout() # Create report for exploration. @@ -1157,8 +1151,7 @@ def test_independent_exp_complete_event_handler(self): """ self.login(self.USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() payload = { 'client_time_spent_in_secs': 0, @@ -1195,8 +1188,7 @@ def test_exp_complete_event_in_collection(self): """ self.login(self.USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() payload = { 'client_time_spent_in_secs': 0, @@ -1240,8 +1232,7 @@ def test_exp_incomplete_event_handler(self): """Test handler for leaving an exploration incomplete.""" self.login(self.USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() payload = { 'client_time_spent_in_secs': 0, @@ -1434,8 +1425,7 @@ def setUp(self): }] } - response = self.get_json('/csrf') - self.csrf_token = response['token'] + self.csrf_token = self.get_csrf_token() def test_new_playthrough_gets_stored(self): """Test that a new playthrough gets created and is added to an existing diff --git a/core/controllers/resources_test.py b/core/controllers/resources_test.py index 031e21f93e2d..7619698a72a5 100644 --- a/core/controllers/resources_test.py +++ b/core/controllers/resources_test.py @@ -51,8 +51,7 @@ def setUp(self): def test_image_upload_with_no_filename_raises_error(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -69,8 +68,7 @@ def test_image_upload_with_no_filename_raises_error(self): def test_image_upload_with_invalid_filename_raises_error(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -88,8 +86,7 @@ def test_image_upload_with_invalid_filename_raises_error(self): def test_cannot_upload_duplicate_image(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -122,8 +119,7 @@ def test_image_upload_and_download(self): """Test image uploading and downloading.""" self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -144,8 +140,7 @@ def test_image_upload_and_download(self): def test_non_matching_extensions_are_detected(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() filename_without_extension = 'test' supplied_filename = ('%s.jpg' % filename_without_extension) @@ -183,8 +178,7 @@ def test_upload_empty_image(self): """Test upload of an empty image.""" self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Upload an empty image. response_dict = self.post_json( @@ -203,8 +197,7 @@ def test_upload_bad_image(self): """Test upload of a malformed image.""" self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Upload an invalid image. response_dict = self.post_json( @@ -230,8 +223,7 @@ def test_bad_filenames_are_detected(self): # TODO(sll): Add more tests here. self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -250,8 +242,7 @@ def test_bad_filenames_are_detected(self): def test_missing_extensions_are_detected(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: raw_image = f.read() @@ -270,8 +261,7 @@ def test_missing_extensions_are_detected(self): def test_bad_extensions_are_detected(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -336,8 +326,7 @@ def setUp(self): mock_accepted_audio_extensions) def test_guest_can_not_upload(self): - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: @@ -355,8 +344,7 @@ def test_guest_can_not_upload(self): def test_cannot_upload_audio_with_invalid_exp_id(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: @@ -372,8 +360,7 @@ def test_cannot_upload_audio_with_invalid_exp_id(self): def test_audio_upload(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: @@ -388,8 +375,7 @@ def test_audio_upload(self): def test_audio_upload_with_non_mp3_file(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() file_system_class = fs_services.get_exploration_file_system_class() fs = fs_domain.AbstractFileSystem(file_system_class( @@ -416,8 +402,7 @@ def test_audio_upload_with_non_mp3_file(self): def test_detect_non_matching_extensions(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Use an accepted audio extension in mismatched_filename # that differs from the uploaded file's audio type. @@ -448,8 +433,7 @@ def test_detect_non_audio_file(self): """ self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), @@ -470,8 +454,7 @@ def test_detect_non_audio_file(self): def test_audio_upload_mpeg_container(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join( feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MPEG_CONTAINER), @@ -489,8 +472,7 @@ def test_invalid_extension_is_detected(self): """Test that invalid extensions are caught.""" self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() filename_without_extension = 'test' invalid_extension = 'wav' @@ -519,8 +501,7 @@ def test_upload_empty_audio(self): """Test upload of empty audio.""" self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Upload empty audio. response_dict = self.post_json( '%s/0' % self.AUDIO_UPLOAD_URL_PREFIX, @@ -537,8 +518,7 @@ def test_upload_bad_audio(self): """Test upload of malformed audio.""" self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response_dict = self.post_json( '%s/0' % self.AUDIO_UPLOAD_URL_PREFIX, {'filename': 'test.mp3'}, @@ -556,8 +536,7 @@ def test_missing_extensions_are_detected(self): """Test upload of filenames with no extensions are caught.""" self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() missing_extension_filename = 'test' with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), @@ -582,8 +561,7 @@ def test_exceed_max_length_detected(self): """Test that audio file is less than max playback length.""" self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_OVER_MAX_LENGTH), @@ -608,8 +586,7 @@ def test_non_matching_extensions_are_detected(self): """ self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Use an accepted audio extension in mismatched_filename # that differs from the uploaded file's audio type. diff --git a/core/controllers/skill_editor_test.py b/core/controllers/skill_editor_test.py index 20cdecdb9431..38298d532ab0 100644 --- a/core/controllers/skill_editor_test.py +++ b/core/controllers/skill_editor_test.py @@ -50,8 +50,7 @@ def setUp(self): def _get_csrf_token_for_put(self): """Gets the csrf token.""" - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() return csrf_token def _delete_skill_model_and_memcache(self, user_id, skill_id): diff --git a/core/controllers/story_editor_test.py b/core/controllers/story_editor_test.py index 6957c2bfbefa..2c2f2178caeb 100644 --- a/core/controllers/story_editor_test.py +++ b/core/controllers/story_editor_test.py @@ -107,8 +107,7 @@ def test_editable_story_handler_put(self): }] } self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() json_response = self.put_json( '%s/%s/%s' % ( diff --git a/core/controllers/subscriptions_test.py b/core/controllers/subscriptions_test.py index 01c452b73476..996aa3be1134 100644 --- a/core/controllers/subscriptions_test.py +++ b/core/controllers/subscriptions_test.py @@ -44,8 +44,7 @@ def test_subscribe_handler(self): """Test handler for new subscriptions to creators.""" self.login(self.USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() payload = { 'creator_username': self.EDITOR_USERNAME @@ -77,8 +76,7 @@ def test_subscribe_handler(self): # Test another user subscription. self.login(self.USER2_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.SUBSCRIBE_URL_PREFIX, payload, @@ -99,8 +97,7 @@ def test_unsubscribe_handler(self): # Add one subscription to editor. self.login(self.USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.SUBSCRIBE_URL_PREFIX, payload, csrf_token=csrf_token) @@ -108,8 +105,7 @@ def test_unsubscribe_handler(self): # Add another subscription. self.login(self.USER2_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.SUBSCRIBE_URL_PREFIX, payload, csrf_token=csrf_token) @@ -140,8 +136,7 @@ def test_unsubscribe_handler(self): # Unsubscribing another user. self.login(self.USER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.UNSUBSCRIBE_URL_PREFIX, payload, csrf_token=csrf_token) diff --git a/core/controllers/suggestion_test.py b/core/controllers/suggestion_test.py index 6a72fa8e5c67..872b25ebec72 100644 --- a/core/controllers/suggestion_test.py +++ b/core/controllers/suggestion_test.py @@ -91,8 +91,7 @@ def setUp(self): self.logout() self.login(self.AUTHOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -116,8 +115,7 @@ def setUp(self): self.logout() self.login(self.AUTHOR_EMAIL_2) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -162,8 +160,7 @@ def setUp(self): def test_create_suggestion(self): self.login(self.AUTHOR_EMAIL_2) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() exploration = exp_services.get_exploration_by_id(self.EXP_ID) self.post_json( @@ -193,16 +190,14 @@ def test_create_suggestion(self): def test_suggestion_to_exploration_handler_with_invalid_suggestion_id(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Invalid format of suggestion id. response = self.put_json( @@ -218,8 +213,7 @@ def test_suggestion_to_exploration_handler_with_invalid_suggestion_id(self): 'Invalid format for suggestion_id. It must contain 3 parts ' 'separated by \'.\'') - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Suggestion does not exist. self.put_json( @@ -263,8 +257,7 @@ def test_suggestion_to_exploration_handler_with_invalid_target_type(self): [('author_id', self.author_id), ( 'target_id', exp_id)])[0].suggestion_id - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.put_json( '%s/exploration/%s/%s' % ( @@ -283,8 +276,7 @@ def test_suggestion_to_exploration_handler_with_invalid_target_type(self): def test_suggestion_to_exploration_handler_with_invalid_target_id(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( @@ -293,8 +285,7 @@ def test_suggestion_to_exploration_handler_with_invalid_target_id(self): self.save_new_default_exploration('exp_id', self.editor_id) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.put_json( '%s/exploration/%s/%s' % ( @@ -334,8 +325,7 @@ def test_owner_of_exploration_cannot_repond_to_own_suggestion(self): [('author_id', self.editor_id), ( 'target_id', exp_id)])[0].suggestion_id - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.put_json( '%s/exploration/%s/%s' % ( @@ -353,16 +343,14 @@ def test_owner_of_exploration_cannot_repond_to_own_suggestion(self): def test_suggestion_to_exploration_handler_with_invalid_action(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.put_json( '%s/exploration/%s/%s' % ( @@ -380,8 +368,7 @@ def test_suggestion_to_exploration_handler_with_invalid_action(self): def test_reject_suggestion_to_exploration(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() suggestion_to_reject = self.get_json( '%s?author_id=%s' % ( @@ -394,10 +381,9 @@ def test_reject_suggestion_to_exploration(self): self.assertEqual( suggestion.status, suggestion_models.STATUS_IN_REVIEW) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() - response = self.put_json('%s/exploration/%s/%s' % ( + self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_reject['target_id'], suggestion_to_reject['suggestion_id']), { @@ -418,16 +404,14 @@ def test_accept_suggestion(self): # Test editor can accept successfully. self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -457,8 +441,7 @@ def test_accept_suggestion(self): feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id_2))['suggestions'][0] - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -476,8 +459,7 @@ def test_accept_suggestion(self): feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id_2))['suggestions'][0] - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -492,8 +474,7 @@ def test_accept_suggestion(self): suggestion_services.increment_score_for_user( self.author_id, 'content.Algebra', 15) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -514,8 +495,7 @@ def test_accept_suggestion(self): # Testing admins can accept suggestions. self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, @@ -555,8 +535,7 @@ def test_suggestion_list_handler(self): self.assertEqual(len(suggestions), 2) def test_cannot_resubmit_suggestion_with_invalid_suggestion_id(self): - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.put_json( '%s/resubmit/%s' % ( @@ -571,8 +550,7 @@ def test_cannot_resubmit_suggestion_with_invalid_suggestion_id(self): def test_resubmit_rejected_suggestion(self): self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() suggestion = suggestion_services.query_suggestions( [('author_id', self.author_id), ('target_id', self.EXP_ID)])[0] @@ -581,8 +559,7 @@ def test_resubmit_rejected_suggestion(self): self.logout() self.login(self.AUTHOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json('%s/resubmit/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion.suggestion_id), { @@ -641,8 +618,7 @@ def setUp(self): feconf.CURRENT_STATE_SCHEMA_VERSION) } self.login(self.AUTHOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -688,8 +664,7 @@ def test_accept_question_suggestion(self): )['suggestions'][0] self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): self.put_json('%s/topic/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, @@ -754,8 +729,7 @@ def setUp(self): } self.login(self.AUTHOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -783,8 +757,7 @@ def test_cannot_access_suggestion_to_topic_handler(self): suggestion_models.TARGET_TYPE_QUESTION, self.topic_id, self.author_id, 'description', '', has_suggestion=True) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', False): self.put_json( @@ -820,8 +793,7 @@ def test_suggestion_to_topic_handler_with_invalid_target_type(self): [('author_id', self.author_id), ( 'target_id', exp_id)])[0].suggestion_id - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): response = self.put_json( @@ -841,8 +813,7 @@ def test_suggestion_to_topic_handler_with_invalid_target_type(self): def test_suggestion_to_topic_handler_with_invalid_target_id(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( @@ -853,8 +824,7 @@ def test_suggestion_to_topic_handler_with_invalid_target_id(self): 'topic_id', self.admin_id, 'Name1', 'Description', [], [], [], [], 1) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): response = self.put_json( @@ -877,16 +847,14 @@ def test_suggestion_to_topic_handler_with_invalid_target_id(self): def test_suggestion_to_topic_handler_with_invalid_action(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): response = self.put_json( @@ -905,8 +873,7 @@ def test_suggestion_to_topic_handler_with_invalid_action(self): def test_reject_suggestion_to_topic(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() suggestion_to_reject = self.get_json( '%s?author_id=%s' % ( @@ -919,8 +886,7 @@ def test_reject_suggestion_to_topic(self): self.assertEqual( suggestion.status, suggestion_models.STATUS_IN_REVIEW) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): self.put_json('%s/topic/%s/%s' % ( @@ -942,8 +908,7 @@ def test_reject_suggestion_to_topic(self): def test_accept_suggestion_to_topic(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( @@ -956,8 +921,7 @@ def test_accept_suggestion_to_topic(self): self.assertEqual( suggestion.status, suggestion_models.STATUS_IN_REVIEW) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): self.put_json('%s/topic/%s/%s' % ( diff --git a/core/controllers/topic_editor_test.py b/core/controllers/topic_editor_test.py index 2c2504a98a18..71c6f11b116f 100644 --- a/core/controllers/topic_editor_test.py +++ b/core/controllers/topic_editor_test.py @@ -66,8 +66,7 @@ class TopicEditorStoryHandlerTests(BaseTopicEditorControllerTests): def test_story_creation(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() json_response = self.post_json( '%s/%s' % (feconf.TOPIC_EDITOR_STORY_URL, self.topic_id), {'title': 'Story title'}, @@ -337,8 +336,7 @@ def test_editable_topic_handler_put(self): }] } self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() json_response = self.put_json( '%s/%s' % ( @@ -476,8 +474,7 @@ def test_editable_topic_handler_put_for_assigned_topic_manager(self): self.topic_id) self.login(self.TOPIC_MANAGER_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Check that the topic manager can edit the topic now. json_response = self.put_json( '%s/%s' % ( @@ -520,8 +517,7 @@ class TopicManagerRightsHandlerTests(BaseTopicEditorControllerTests): def test_assign_topic_manager_role(self): """Test the assign topic manager role for a topic functionality.""" self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Test for when assignee does not have sufficient rights to become a # manager for a topic. @@ -552,8 +548,7 @@ class TopicPublishSendMailHandlerTests(BaseTopicEditorControllerTests): def test_send_mail(self): self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with self.swap(feconf, 'CAN_SEND_EMAILS', True): self.put_json( '%s/%s' % ( @@ -598,8 +593,7 @@ class TopicPublishHandlerTests(BaseTopicEditorControllerTests): def test_publish_and_unpublish_topic(self): """Test the publish and unpublish functionality.""" self.login(self.ADMIN_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # Test whether admin can publish and unpublish a topic. self.put_json( '%s/%s' % ( diff --git a/core/controllers/topics_and_skills_dashboard_test.py b/core/controllers/topics_and_skills_dashboard_test.py index 33cb07027225..70971a9d978a 100644 --- a/core/controllers/topics_and_skills_dashboard_test.py +++ b/core/controllers/topics_and_skills_dashboard_test.py @@ -48,8 +48,7 @@ def setUp(self): def _get_csrf_token_for_put(self): """Gets the csrf token.""" - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() return csrf_token diff --git a/core/controllers/voice_artist_test.py b/core/controllers/voice_artist_test.py index d196decac1c6..46835b1aad67 100644 --- a/core/controllers/voice_artist_test.py +++ b/core/controllers/voice_artist_test.py @@ -70,8 +70,7 @@ def setUp(self): self.login(self.VOICE_ARTIST_EMAIL) # Generate CSRF token. - response = self.get_json('/csrf') - self.csrf_token = response['token'] + self.csrf_token = self.get_csrf_token() def test_put_with_no_payload_version_raises_error(self): with self.assertRaisesRegexp( @@ -197,8 +196,7 @@ def setUp(self): draft_change_list_id=1).put() # Generate CSRF token. - response = self.get_json('/csrf') - self.csrf_token = response['token'] + self.csrf_token = self.get_csrf_token() def test_draft_updated_version_valid(self): payload = { @@ -277,8 +275,7 @@ def setUp(self): self.login(self.VOICE_ARTIST_EMAIL) # Generate CSRF token. - response = self.get_json('/csrf') - self.csrf_token = response['token'] + self.csrf_token = self.get_csrf_token() def test_firsttime_translation_tutorial(self): """Testing of the firsttime translation tutorial http requests.""" diff --git a/core/domain/email_manager_test.py b/core/domain/email_manager_test.py index 35fe24d5812c..2e736492bc9a 100644 --- a/core/domain/email_manager_test.py +++ b/core/domain/email_manager_test.py @@ -202,8 +202,7 @@ def test_role_email_is_sent_when_editor_assigns_role(self): with self.can_send_emails_ctx, self.can_send_editor_role_email_ctx: self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.put_json('%s/%s' % ( feconf.EXPLORATION_RIGHTS_PREFIX, self.exploration.id), { 'version': self.exploration.version, @@ -570,8 +569,7 @@ def test_email_not_sent_if_config_does_not_permit_it(self): self.new_email_content) self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, { @@ -601,8 +599,7 @@ def _log_error_for_tests(error_message): self.assertEqual(log_new_error_counter.times_called, 0) self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # No user-facing error should surface. self.post_json( @@ -649,8 +646,7 @@ def _log_error_for_tests(error_message): self.assertEqual(log_new_error_counter.times_called, 0) self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # No user-facing error should surface. self.post_json( @@ -695,8 +691,7 @@ def _log_error_for_tests(error_message): self.assertEqual(log_new_error_counter.times_called, 0) self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() # No user-facing error should surface. self.post_json( @@ -727,8 +722,7 @@ def test_contents_of_signup_email_are_correct(self): 'Email Sender') self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, { @@ -760,8 +754,7 @@ def test_email_only_sent_once_for_repeated_signups_by_same_user(self): self.new_email_content) self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, { @@ -794,8 +787,7 @@ def test_email_only_sent_if_signup_was_successful(self): self.new_email_content) self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, @@ -836,8 +828,7 @@ def test_record_of_sent_email_is_written_to_datastore(self): self.assertEqual(len(all_models), 0) self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, { diff --git a/core/domain/feedback_services_test.py b/core/domain/feedback_services_test.py index 69f0e3153570..7e11eaa0cd6e 100644 --- a/core/domain/feedback_services_test.py +++ b/core/domain/feedback_services_test.py @@ -946,8 +946,7 @@ def test_that_emails_are_not_sent_if_already_seen(self): thread_id = threadlist[0].id self.login(self.EDITOR_EMAIL) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '%s/%s' % ( feconf.FEEDBACK_THREAD_VIEW_EVENT_URL, thread_id), diff --git a/core/domain/summary_services_test.py b/core/domain/summary_services_test.py index 835b8231f007..a0730cdb620c 100644 --- a/core/domain/summary_services_test.py +++ b/core/domain/summary_services_test.py @@ -258,8 +258,7 @@ def setUp(self): super(LibraryGroupsTest, self).setUp() self.login(self.ADMIN_EMAIL, is_super_admin=True) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() with self.swap( html_validation_service, 'get_filename_with_dimensions', diff --git a/core/tests/test_utils.py b/core/tests/test_utils.py index 463506fe0680..a563a8a7e3b9 100644 --- a/core/tests/test_utils.py +++ b/core/tests/test_utils.py @@ -22,10 +22,10 @@ import itertools import json import os -import re import unittest from constants import constants +from core.controllers import base from core.domain import collection_domain from core.domain import collection_services from core.domain import exp_domain @@ -59,8 +59,6 @@ models.NAMES.story, models.NAMES.topic])) current_user_services = models.Registry.import_current_user_services() -CSRF_REGEX = ( - r'csrf_token: JSON\.parse\(\'\\\"([A-Za-z0-9/=_-]+)\\\"\'\)') # Prefix to append to all lines printed by tests to the console. LOG_LINE_PREFIX = 'LOG_INFO_TEST: ' @@ -824,9 +822,10 @@ def put_json(self, url, payload, csrf_token=None, expected_status_int=200): self.assertEqual(json_response.status_int, expected_status_int) return self._parse_json_response(json_response, expect_errors) - def get_csrf_token_from_response(self, response): - """Retrieve the CSRF token from a GET response.""" - return re.search(CSRF_REGEX, response.body).group(1) + def get_csrf_token(self): + """Generates csrf token for test.""" + return base.CsrfTokenManager.create_csrf_token( + self.get_current_logged_in_user_id()) def signup(self, email, username): """Complete the signup process for the user with the given username. @@ -844,8 +843,7 @@ def signup(self, email, username): with self.urlfetch_mock(): response = self.get_html_response(feconf.SIGNUP_URL) self.assertEqual(response.status_int, 200) - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() response = self.testapp.post( feconf.SIGNUP_DATA_URL, params={ 'csrf_token': csrf_token, @@ -863,8 +861,7 @@ def set_config_property(self, config_obj, new_config_value): """ with self.login_context('tmpsuperadmin@example.com', is_super_admin=True): - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/adminhandler', { 'action': 'save_config_properties', @@ -882,8 +879,7 @@ def set_user_role(self, username, user_role): """ with self.login_context('tmpsuperadmin@example.com', is_super_admin=True): - response = self.get_json('/csrf') - csrf_token = response['token'] + csrf_token = self.get_csrf_token() self.post_json( '/adminrolehandler', { 'username': username, From 5bd0884ec321372d7c4586665152ff35577ab30c Mon Sep 17 00:00:00 2001 From: James John James Date: Tue, 18 Jun 2019 12:26:51 +0100 Subject: [PATCH 07/40] work on e2e tests --- core/templates/dev/head/pages/Base.ts | 18 +++++++++++------- .../pages/admin-page/admin-page.directive.ts | 4 +++- .../templates/dev/head/services/CsrfService.ts | 8 -------- 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/core/templates/dev/head/pages/Base.ts b/core/templates/dev/head/pages/Base.ts index 4e83be756dc5..edbc439a0689 100644 --- a/core/templates/dev/head/pages/Base.ts +++ b/core/templates/dev/head/pages/Base.ts @@ -24,12 +24,14 @@ require('services/stateful/BackgroundMaskService.ts'); */ oppia.controller('Base', [ - '$document', '$rootScope', '$scope', 'AlertsService', 'BackgroundMaskService', - 'CsrfService', 'SidebarStatusService', 'UrlInterpolationService', - 'UrlService', 'DEV_MODE', 'SITE_FEEDBACK_FORM_URL', 'SITE_NAME', - function($document, $rootScope, $scope, AlertsService, BackgroundMaskService, - CsrfService, SidebarStatusService, UrlInterpolationService, - UrlService, DEV_MODE, SITE_FEEDBACK_FORM_URL, SITE_NAME) { + '$document', '$rootScope', '$http', '$scope', 'AlertsService', + 'BackgroundMaskService', 'CsrfService', 'SidebarStatusService', + 'UrlInterpolationService', 'UrlService', 'DEV_MODE', 'SITE_FEEDBACK_FORM_URL', + 'SITE_NAME', + function($document, $rootScope, $http, $scope, AlertsService, + BackgroundMaskService, CsrfService, SidebarStatusService, + UrlInterpolationService, UrlService, DEV_MODE, SITE_FEEDBACK_FORM_URL, + SITE_NAME) { $scope.siteName = SITE_NAME; $scope.AlertsService = AlertsService; $scope.currentLang = 'en'; @@ -55,7 +57,9 @@ oppia.controller('Base', [ }); if (UrlService.getPathname() !== '/signup') { - CsrfService.fetchToken(); + $http.get('/csrf').then(function(response) { + CsrfService.setToken(response.data.token); + }); } // TODO(sll): use 'touchstart' for mobile. $document.on('click', function() { diff --git a/core/templates/dev/head/pages/admin-page/admin-page.directive.ts b/core/templates/dev/head/pages/admin-page/admin-page.directive.ts index 1c1eda18cd4b..b9157d5d3f73 100644 --- a/core/templates/dev/head/pages/admin-page/admin-page.directive.ts +++ b/core/templates/dev/head/pages/admin-page/admin-page.directive.ts @@ -105,7 +105,9 @@ oppia.directive('adminPage', ['UrlInterpolationService', ctrl.isRolesTabOpen = AdminRouterService.isRolesTabOpen; ctrl.isMiscTabOpen = AdminRouterService.isMiscTabOpen; - CsrfService.fetchToken(); + $http.get('/csrf').then(function(response) { + CsrfService.setToken(response.token); + }) ctrl.setStatusMessage = function(statusMessage) { ctrl.statusMessage = statusMessage; }; diff --git a/core/templates/dev/head/services/CsrfService.ts b/core/templates/dev/head/services/CsrfService.ts index 2c5b169d52d7..f71511824336 100644 --- a/core/templates/dev/head/services/CsrfService.ts +++ b/core/templates/dev/head/services/CsrfService.ts @@ -23,14 +23,6 @@ oppia.factory('CsrfService', [function() { }; return { - fetchToken: function() { - fetch('/csrf').then(function(response) { - return response.text(); - }).then(function(response) { - setToken(JSON.parse(response.substring(5)).token); - }); - }, - setToken: setToken, getToken: function() { From 9e5a5e4bc1a9e8d76c3738556fa7680df42a18aa Mon Sep 17 00:00:00 2001 From: James John James Date: Tue, 18 Jun 2019 12:58:21 +0100 Subject: [PATCH 08/40] minor issue in admin --- .../templates/dev/head/pages/admin-page/admin-page.directive.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/templates/dev/head/pages/admin-page/admin-page.directive.ts b/core/templates/dev/head/pages/admin-page/admin-page.directive.ts index b9157d5d3f73..2e695508c9f9 100644 --- a/core/templates/dev/head/pages/admin-page/admin-page.directive.ts +++ b/core/templates/dev/head/pages/admin-page/admin-page.directive.ts @@ -106,7 +106,7 @@ oppia.directive('adminPage', ['UrlInterpolationService', ctrl.isMiscTabOpen = AdminRouterService.isMiscTabOpen; $http.get('/csrf').then(function(response) { - CsrfService.setToken(response.token); + CsrfService.setToken(response.data.token); }) ctrl.setStatusMessage = function(statusMessage) { ctrl.statusMessage = statusMessage; From 427ea8edd6915b21608cb930de068192e847fa78 Mon Sep 17 00:00:00 2001 From: James John James Date: Tue, 18 Jun 2019 13:16:38 +0100 Subject: [PATCH 09/40] address some review comments --- core/controllers/base_test.py | 7 +++---- core/controllers/skill_editor_test.py | 10 +++++----- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/core/controllers/base_test.py b/core/controllers/base_test.py index 1adfb41595fe..5ef6a1e1c030 100644 --- a/core/controllers/base_test.py +++ b/core/controllers/base_test.py @@ -670,9 +670,8 @@ def test_every_method_has_decorator(self): # Following handler are present in base.py where acl_decorators # cannot be imported. - if (handler.__name__ == 'LogoutPage' or - handler.__name__ == 'Error404Handler' or - handler.__name__ == 'CsrfTokenHandler'): + if (handler.__name__ in ( + 'CsrfTokenHandler', 'Error404Handler', 'LogoutPage'): continue if handler.get != base.BaseHandler.get: @@ -891,7 +890,7 @@ def test_no_error_is_raised_on_opening_new_tab_after_signup(self): class CsrfTokenHandlerTests(test_utils.GenericTestBase): def test_valid_token_is_returned(self): - """Test that a valid csrf token is returned by + """Test that a valid CSRF token is returned by the handler. """ diff --git a/core/controllers/skill_editor_test.py b/core/controllers/skill_editor_test.py index 38298d532ab0..1602d00a6611 100644 --- a/core/controllers/skill_editor_test.py +++ b/core/controllers/skill_editor_test.py @@ -190,7 +190,7 @@ def test_editable_skill_handler_get_fails(self): def test_editable_skill_handler_put_succeeds(self): self.login(self.ADMIN_EMAIL) - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.self.get_csrf_token() # Check that admins can edit a skill. json_response = self.put_json( self.url, self.put_payload, csrf_token=csrf_token) @@ -201,7 +201,7 @@ def test_editable_skill_handler_put_succeeds(self): def test_editable_skill_handler_put_fails(self): self.login(self.ADMIN_EMAIL) - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.self.get_csrf_token() # Check PUT returns 400 when an exception is raised updating the # skill. update_skill_swap = self.swap( @@ -244,14 +244,14 @@ def setUp(self): def test_skill_publish_handler_succeeds(self): self.login(self.ADMIN_EMAIL) # Check that an admin can publish a skill. - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.self.get_csrf_token() self.put_json(self.url, {'version': 1}, csrf_token=csrf_token) self.logout() def test_skill_publish_handler_fails(self): self.login(self.ADMIN_EMAIL) - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.self.get_csrf_token() # Check that a skill cannot be published when the payload has no # version. self.put_json( @@ -273,7 +273,7 @@ def test_skill_publish_handler_fails(self): skill_services, 'publish_skill', self._mock_publish_skill_raise_exception) with skill_services_swap: - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.self.get_csrf_token() self.put_json( self.url, {'version': 1}, csrf_token=csrf_token, expected_status_int=401) From bf8372605e8d0a45e2bcb4826fdcfa7f1adf17d6 Mon Sep 17 00:00:00 2001 From: James John James Date: Tue, 18 Jun 2019 14:33:48 +0100 Subject: [PATCH 10/40] work on failing tests --- core/controllers/editor_test.py | 3 ++- core/controllers/reader_test.py | 3 ++- core/controllers/suggestion_test.py | 1 + .../dev/head/pages/admin-page/admin-page.directive.ts | 3 ++- core/tests/test_utils.py | 9 +++++++-- 5 files changed, 14 insertions(+), 5 deletions(-) diff --git a/core/controllers/editor_test.py b/core/controllers/editor_test.py index 762264ecda75..868b2ae3f1d8 100644 --- a/core/controllers/editor_test.py +++ b/core/controllers/editor_test.py @@ -2039,7 +2039,8 @@ def setUp(self): 'is_valid': True } - self.csrf_token = self.get_csrf_token() + self.csrf_token = self.get_csrf_token_for_id( + self.get_user_id_from_email(self.MODERATOR_EMAIL)) def test_resolve_issue_handler(self): """Test that resolving an issue deletes associated playthroughs.""" diff --git a/core/controllers/reader_test.py b/core/controllers/reader_test.py index 85ddf8b722e8..0ec6d9de96f9 100644 --- a/core/controllers/reader_test.py +++ b/core/controllers/reader_test.py @@ -1363,8 +1363,9 @@ def setUp(self): super(StorePlaythroughHandlerTest, self).setUp() self.exp_id = '15' - self.login(self.VIEWER_EMAIL) self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) + self.login(self.VIEWER_EMAIL) + exp_services.load_demo(self.exp_id) self.exploration = exp_services.get_exploration_by_id(self.exp_id) playthrough_id = stats_models.PlaythroughModel.create( diff --git a/core/controllers/suggestion_test.py b/core/controllers/suggestion_test.py index 872b25ebec72..33625bbe5b24 100644 --- a/core/controllers/suggestion_test.py +++ b/core/controllers/suggestion_test.py @@ -535,6 +535,7 @@ def test_suggestion_list_handler(self): self.assertEqual(len(suggestions), 2) def test_cannot_resubmit_suggestion_with_invalid_suggestion_id(self): + self.login(self.EDITOR_EMAIL) csrf_token = self.get_csrf_token() response = self.put_json( diff --git a/core/templates/dev/head/pages/admin-page/admin-page.directive.ts b/core/templates/dev/head/pages/admin-page/admin-page.directive.ts index 2e695508c9f9..bf93dd341f92 100644 --- a/core/templates/dev/head/pages/admin-page/admin-page.directive.ts +++ b/core/templates/dev/head/pages/admin-page/admin-page.directive.ts @@ -107,7 +107,8 @@ oppia.directive('adminPage', ['UrlInterpolationService', $http.get('/csrf').then(function(response) { CsrfService.setToken(response.data.token); - }) + }); + ctrl.setStatusMessage = function(statusMessage) { ctrl.statusMessage = statusMessage; }; diff --git a/core/tests/test_utils.py b/core/tests/test_utils.py index a563a8a7e3b9..50120f5edb7f 100644 --- a/core/tests/test_utils.py +++ b/core/tests/test_utils.py @@ -823,10 +823,15 @@ def put_json(self, url, payload, csrf_token=None, expected_status_int=200): return self._parse_json_response(json_response, expect_errors) def get_csrf_token(self): - """Generates csrf token for test.""" - return base.CsrfTokenManager.create_csrf_token( + """Generates CSRF token for test.""" + return self.get_csrf_token_for_id( self.get_current_logged_in_user_id()) + def get_csrf_token_for_id(self, id): + """Generates CSRF token for specific id.""" + return base.CsrfTokenManager.create_csrf_token(id) + + def signup(self, email, username): """Complete the signup process for the user with the given username. From dfac34f23f4cd668143b62185c0b633fc06c7340 Mon Sep 17 00:00:00 2001 From: James John James Date: Tue, 18 Jun 2019 14:58:20 +0100 Subject: [PATCH 11/40] erroring tests --- core/controllers/base_test.py | 2 +- core/controllers/skill_editor_test.py | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/core/controllers/base_test.py b/core/controllers/base_test.py index 5ef6a1e1c030..d495cf54250c 100644 --- a/core/controllers/base_test.py +++ b/core/controllers/base_test.py @@ -671,7 +671,7 @@ def test_every_method_has_decorator(self): # Following handler are present in base.py where acl_decorators # cannot be imported. if (handler.__name__ in ( - 'CsrfTokenHandler', 'Error404Handler', 'LogoutPage'): + 'CsrfTokenHandler', 'Error404Handler', 'LogoutPage')): continue if handler.get != base.BaseHandler.get: diff --git a/core/controllers/skill_editor_test.py b/core/controllers/skill_editor_test.py index 1602d00a6611..edaa7f945eca 100644 --- a/core/controllers/skill_editor_test.py +++ b/core/controllers/skill_editor_test.py @@ -190,7 +190,7 @@ def test_editable_skill_handler_get_fails(self): def test_editable_skill_handler_put_succeeds(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.self.get_csrf_token() + csrf_token = self.get_csrf_token() # Check that admins can edit a skill. json_response = self.put_json( self.url, self.put_payload, csrf_token=csrf_token) @@ -201,7 +201,7 @@ def test_editable_skill_handler_put_succeeds(self): def test_editable_skill_handler_put_fails(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.self.get_csrf_token() + csrf_token = self.get_csrf_token() # Check PUT returns 400 when an exception is raised updating the # skill. update_skill_swap = self.swap( @@ -244,14 +244,14 @@ def setUp(self): def test_skill_publish_handler_succeeds(self): self.login(self.ADMIN_EMAIL) # Check that an admin can publish a skill. - csrf_token = self.self.get_csrf_token() + csrf_token = self.get_csrf_token() self.put_json(self.url, {'version': 1}, csrf_token=csrf_token) self.logout() def test_skill_publish_handler_fails(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.self.get_csrf_token() + csrf_token = self.get_csrf_token() # Check that a skill cannot be published when the payload has no # version. self.put_json( @@ -273,7 +273,7 @@ def test_skill_publish_handler_fails(self): skill_services, 'publish_skill', self._mock_publish_skill_raise_exception) with skill_services_swap: - csrf_token = self.self.get_csrf_token() + csrf_token = self.get_csrf_token() self.put_json( self.url, {'version': 1}, csrf_token=csrf_token, expected_status_int=401) From f96400206c255ba31613f426ba4e889e57aeb1e8 Mon Sep 17 00:00:00 2001 From: James John James Date: Tue, 18 Jun 2019 15:02:15 +0100 Subject: [PATCH 12/40] still on tests --- core/controllers/editor_test.py | 4 ++-- core/controllers/resources_test.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/controllers/editor_test.py b/core/controllers/editor_test.py index 868b2ae3f1d8..a91fed5fbd03 100644 --- a/core/controllers/editor_test.py +++ b/core/controllers/editor_test.py @@ -2039,8 +2039,8 @@ def setUp(self): 'is_valid': True } - self.csrf_token = self.get_csrf_token_for_id( - self.get_user_id_from_email(self.MODERATOR_EMAIL)) + self.login(self.MODERATOR_EMAIL) + self.csrf_token = self.get_csrf_token() def test_resolve_issue_handler(self): """Test that resolving an issue deletes associated playthroughs.""" diff --git a/core/controllers/resources_test.py b/core/controllers/resources_test.py index 7619698a72a5..bd7b60f689e6 100644 --- a/core/controllers/resources_test.py +++ b/core/controllers/resources_test.py @@ -326,7 +326,7 @@ def setUp(self): mock_accepted_audio_extensions) def test_guest_can_not_upload(self): - csrf_token = self.get_csrf_token() + csrf_token = self.get_csrf_token_for_id('') with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: From bca6d723476236b5a87f3b8686d090b1681c0069 Mon Sep 17 00:00:00 2001 From: James John James Date: Tue, 18 Jun 2019 15:05:57 +0100 Subject: [PATCH 13/40] address more review comments --- core/controllers/skill_editor_test.py | 5 ----- core/templates/dev/head/services/CsrfService.ts | 1 - 2 files changed, 6 deletions(-) diff --git a/core/controllers/skill_editor_test.py b/core/controllers/skill_editor_test.py index edaa7f945eca..fac2a22af4fb 100644 --- a/core/controllers/skill_editor_test.py +++ b/core/controllers/skill_editor_test.py @@ -48,11 +48,6 @@ def setUp(self): self.topic_id, self.admin_id, 'Name', 'Description', [], [], [self.skill_id], [], 1) - def _get_csrf_token_for_put(self): - """Gets the csrf token.""" - csrf_token = self.get_csrf_token() - return csrf_token - def _delete_skill_model_and_memcache(self, user_id, skill_id): """Deletes skill model and memcache corresponding to the given skill id. diff --git a/core/templates/dev/head/services/CsrfService.ts b/core/templates/dev/head/services/CsrfService.ts index f71511824336..82de898dc48c 100644 --- a/core/templates/dev/head/services/CsrfService.ts +++ b/core/templates/dev/head/services/CsrfService.ts @@ -24,7 +24,6 @@ oppia.factory('CsrfService', [function() { return { setToken: setToken, - getToken: function() { return token; } From 828e48652801887fcb7358a2e61fbdc6b77cf57f Mon Sep 17 00:00:00 2001 From: James John James Date: Wed, 19 Jun 2019 13:07:03 +0100 Subject: [PATCH 14/40] still on the test issue --- core/controllers/base_test.py | 2 +- core/controllers/profile_test.py | 35 ++++++++++++++++++------------ core/controllers/resources_test.py | 3 ++- 3 files changed, 24 insertions(+), 16 deletions(-) diff --git a/core/controllers/base_test.py b/core/controllers/base_test.py index d495cf54250c..dc6f7a15b069 100644 --- a/core/controllers/base_test.py +++ b/core/controllers/base_test.py @@ -671,7 +671,7 @@ def test_every_method_has_decorator(self): # Following handler are present in base.py where acl_decorators # cannot be imported. if (handler.__name__ in ( - 'CsrfTokenHandler', 'Error404Handler', 'LogoutPage')): + ('CsrfTokenHandler', 'Error404Handler', 'LogoutPage'))): continue if handler.get != base.BaseHandler.get: diff --git a/core/controllers/profile_test.py b/core/controllers/profile_test.py index 33fc7912e54e..ef69c73af8f9 100644 --- a/core/controllers/profile_test.py +++ b/core/controllers/profile_test.py @@ -188,28 +188,35 @@ def test_default_dashboard_for_new_users(self): def test_user_settings_of_non_existing_user(self): self.login(self.OWNER_EMAIL) - values_dict = { - u'can_send_emails': False, - u'has_agreed_to_latest_terms': False, - u'has_ever_registered': False, - u'username': None, - } + can_send_emails = False, + has_agreed_to_latest_terms = False, + has_ever_registered = False, + username = None, + response = self.get_json(feconf.SIGNUP_DATA_URL) - self.assertDictContainsSubset(response, values_dict) + self.assertEqual(can_send_emails, response['can_send_email']) + self.assertEqual(has_agreed_to_latest_terms, + response['has_agreed_to_latest_terms']) + self.assertEqual(has_ever_registered, + response['has_ever_registered']) + self.assertEqual(username, response['username']) self.logout() def test_user_settings_of_existing_user(self): self.signup(self.OWNER_EMAIL, self.OWNER_USERNAME) self.login(self.OWNER_EMAIL) - values_dict = { - u'can_send_emails': True, - u'has_agreed_to_latest_terms': True, - u'has_ever_registered': True, - u'username': 'owner', - } + can_send_emails = True, + has_agreed_to_latest_terms = True, + has_ever_registered = True, + username = 'owner', with self.swap(feconf, 'CAN_SEND_EMAILS', True): response = self.get_json(feconf.SIGNUP_DATA_URL) - self.assertDictContainsSubset(response, values_dict) + self.assertEqual(can_send_emails, response['can_send_email']) + self.assertEqual(has_agreed_to_latest_terms, + response['has_agreed_to_latest_terms']) + self.assertEqual(has_ever_registered, + response['has_ever_registered']) + self.assertEqual(username, response['username']) self.logout() diff --git a/core/controllers/resources_test.py b/core/controllers/resources_test.py index bd7b60f689e6..71be8df49bd9 100644 --- a/core/controllers/resources_test.py +++ b/core/controllers/resources_test.py @@ -326,7 +326,8 @@ def setUp(self): mock_accepted_audio_extensions) def test_guest_can_not_upload(self): - csrf_token = self.get_csrf_token_for_id('') + self.logout() + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: From f9daa2cb19b4c014dda9c0b46b9c4d303d49828f Mon Sep 17 00:00:00 2001 From: James John James Date: Wed, 19 Jun 2019 13:24:30 +0100 Subject: [PATCH 15/40] fix error --- core/controllers/profile_test.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/controllers/profile_test.py b/core/controllers/profile_test.py index ef69c73af8f9..89c51b9fe283 100644 --- a/core/controllers/profile_test.py +++ b/core/controllers/profile_test.py @@ -192,9 +192,9 @@ def test_user_settings_of_non_existing_user(self): has_agreed_to_latest_terms = False, has_ever_registered = False, username = None, - + response = self.get_json(feconf.SIGNUP_DATA_URL) - self.assertEqual(can_send_emails, response['can_send_email']) + self.assertEqual(can_send_emails, response['can_send_emails']) self.assertEqual(has_agreed_to_latest_terms, response['has_agreed_to_latest_terms']) self.assertEqual(has_ever_registered, @@ -211,7 +211,7 @@ def test_user_settings_of_existing_user(self): username = 'owner', with self.swap(feconf, 'CAN_SEND_EMAILS', True): response = self.get_json(feconf.SIGNUP_DATA_URL) - self.assertEqual(can_send_emails, response['can_send_email']) + self.assertEqual(can_send_emails, response['can_send_emails']) self.assertEqual(has_agreed_to_latest_terms, response['has_agreed_to_latest_terms']) self.assertEqual(has_ever_registered, From b975bfda74da6242adaabae0618de5fe79872051 Mon Sep 17 00:00:00 2001 From: James John James Date: Wed, 19 Jun 2019 14:25:23 +0100 Subject: [PATCH 16/40] still on tests --- core/controllers/profile_test.py | 16 ++++++++-------- core/controllers/resources_test.py | 3 +-- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/core/controllers/profile_test.py b/core/controllers/profile_test.py index 89c51b9fe283..6ee9cd67af53 100644 --- a/core/controllers/profile_test.py +++ b/core/controllers/profile_test.py @@ -188,10 +188,10 @@ def test_default_dashboard_for_new_users(self): def test_user_settings_of_non_existing_user(self): self.login(self.OWNER_EMAIL) - can_send_emails = False, - has_agreed_to_latest_terms = False, - has_ever_registered = False, - username = None, + can_send_emails = False + has_agreed_to_latest_terms = False + has_ever_registered = False + username = None response = self.get_json(feconf.SIGNUP_DATA_URL) self.assertEqual(can_send_emails, response['can_send_emails']) @@ -205,10 +205,10 @@ def test_user_settings_of_non_existing_user(self): def test_user_settings_of_existing_user(self): self.signup(self.OWNER_EMAIL, self.OWNER_USERNAME) self.login(self.OWNER_EMAIL) - can_send_emails = True, - has_agreed_to_latest_terms = True, - has_ever_registered = True, - username = 'owner', + can_send_emails = True + has_agreed_to_latest_terms = True + has_ever_registered = True + username = 'owner' with self.swap(feconf, 'CAN_SEND_EMAILS', True): response = self.get_json(feconf.SIGNUP_DATA_URL) self.assertEqual(can_send_emails, response['can_send_emails']) diff --git a/core/controllers/resources_test.py b/core/controllers/resources_test.py index 71be8df49bd9..615d6ac44a98 100644 --- a/core/controllers/resources_test.py +++ b/core/controllers/resources_test.py @@ -326,8 +326,7 @@ def setUp(self): mock_accepted_audio_extensions) def test_guest_can_not_upload(self): - self.logout() - csrf_token = self.get_csrf_token() + csrf_token = self.get_csrf_token(self.get_user_id_from_email(self.EDITOR_EMAIL)) with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: From 6510b3957bee818c8f599fac6004a11065500bb9 Mon Sep 17 00:00:00 2001 From: James John James Date: Fri, 21 Jun 2019 13:26:26 +0100 Subject: [PATCH 17/40] work on erroring tests --- core/controllers/resources_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/controllers/resources_test.py b/core/controllers/resources_test.py index 615d6ac44a98..15acb1b8509b 100644 --- a/core/controllers/resources_test.py +++ b/core/controllers/resources_test.py @@ -326,7 +326,7 @@ def setUp(self): mock_accepted_audio_extensions) def test_guest_can_not_upload(self): - csrf_token = self.get_csrf_token(self.get_user_id_from_email(self.EDITOR_EMAIL)) + csrf_token = self.get_csrf_token_for_id(self.get_user_id_from_email(self.EDITOR_EMAIL)) with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: From 261a101abed66e032abdfaa5d019c2e1452fdce0 Mon Sep 17 00:00:00 2001 From: James John James Date: Fri, 21 Jun 2019 16:57:08 +0100 Subject: [PATCH 18/40] still on failing tests --- core/controllers/question_editor_test.py | 6 ++---- core/controllers/resources_test.py | 2 +- core/tests/test_utils.py | 11 +++++------ 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/core/controllers/question_editor_test.py b/core/controllers/question_editor_test.py index 572f2b4cbd1c..1369b70e632d 100644 --- a/core/controllers/question_editor_test.py +++ b/core/controllers/question_editor_test.py @@ -95,8 +95,7 @@ def test_post_with_incorrect_skill_id_returns_404(self): def test_post_with_incorrect_list_of_skill_ids_returns_400(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + csrf_token = self.get_csrf_token() incorrect_skill_id = [1, 2] self.post_json( '%s/%s' % (feconf.NEW_QUESTION_URL, incorrect_skill_id), @@ -105,8 +104,7 @@ def test_post_with_incorrect_list_of_skill_ids_returns_400(self): def test_post_with_incorrect_type_of_skill_ids_returns_400(self): self.login(self.ADMIN_EMAIL) - response = self.get_html_response(feconf.CREATOR_DASHBOARD_URL) - csrf_token = self.get_csrf_token_from_response(response) + csrf_token = self.get_csrf_token() incorrect_skill_id = 1 self.post_json( '%s/%s' % (feconf.NEW_QUESTION_URL, incorrect_skill_id), diff --git a/core/controllers/resources_test.py b/core/controllers/resources_test.py index 15acb1b8509b..7619698a72a5 100644 --- a/core/controllers/resources_test.py +++ b/core/controllers/resources_test.py @@ -326,7 +326,7 @@ def setUp(self): mock_accepted_audio_extensions) def test_guest_can_not_upload(self): - csrf_token = self.get_csrf_token_for_id(self.get_user_id_from_email(self.EDITOR_EMAIL)) + csrf_token = self.get_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: diff --git a/core/tests/test_utils.py b/core/tests/test_utils.py index dadc2208eea6..a0a2405c824c 100644 --- a/core/tests/test_utils.py +++ b/core/tests/test_utils.py @@ -824,13 +824,12 @@ def put_json(self, url, payload, csrf_token=None, expected_status_int=200): def get_csrf_token(self): """Generates CSRF token for test.""" - return self.get_csrf_token_for_id( - self.get_current_logged_in_user_id()) - - def get_csrf_token_for_id(self, id): - """Generates CSRF token for specific id.""" - return base.CsrfTokenManager.create_csrf_token(id) + if self.get_current_logged_in_user_id() == '': + return base.CsrfTokenManager.create_csrf_token( + ('non_logged_in_user')) + return base.CsrfTokenManager.create_csrf_token( + self.get_current_logged_in_user_id()) def signup(self, email, username): """Complete the signup process for the user with the given username. From def2e129f7e8ff91046378f02797021690d496e4 Mon Sep 17 00:00:00 2001 From: James John James Date: Sat, 22 Jun 2019 17:07:39 +0100 Subject: [PATCH 19/40] address review comments --- .github/CODEOWNERS | 2 +- core/controllers/admin_test.py | 14 ++-- core/controllers/base.py | 12 +--- core/controllers/base_test.py | 8 +-- core/controllers/collection_editor_test.py | 16 ++--- core/controllers/creator_dashboard_test.py | 12 ++-- core/controllers/editor_test.py | 50 ++++++------- core/controllers/email_dashboard_test.py | 40 +++++------ core/controllers/feedback_test.py | 24 +++---- core/controllers/learner_dashboard_test.py | 2 +- core/controllers/learner_playlist_test.py | 4 +- core/controllers/library_test.py | 4 +- core/controllers/moderator_test.py | 2 +- core/controllers/profile.py | 3 + core/controllers/profile_test.py | 54 +++++++------- core/controllers/question_editor_test.py | 36 +++++----- core/controllers/reader_test.py | 20 +++--- core/controllers/resources_test.py | 46 ++++++------ core/controllers/skill_editor_test.py | 10 +-- core/controllers/story_editor_test.py | 2 +- core/controllers/subscriptions_test.py | 10 +-- core/controllers/suggestion_test.py | 72 +++++++++---------- core/controllers/topic_editor_test.py | 12 ++-- .../topics_and_skills_dashboard_test.py | 19 ++--- core/controllers/voice_artist_test.py | 6 +- core/domain/email_manager_test.py | 18 ++--- core/domain/feedback_services_test.py | 2 +- core/domain/summary_services_test.py | 2 +- core/templates/dev/head/App.ts | 14 ++-- .../exploration-creation.service.ts | 8 +-- core/templates/dev/head/pages/Base.ts | 16 +++-- .../pages/admin-page/admin-page.directive.ts | 16 +++-- core/templates/dev/head/pages/base.html | 1 - .../signup-page/signup-page.controller.ts | 8 +-- .../head/services/AssetsBackendApiService.ts | 8 +-- .../{CsrfService.ts => CsrfTokenService.ts} | 10 ++- ...ServiceSpec.ts => CsrfTokenServiceSpec.ts} | 12 ++-- core/tests/test_utils.py | 17 ++--- .../templates/FilepathEditorDirective.ts | 8 +-- main.py | 2 +- 40 files changed, 305 insertions(+), 317 deletions(-) rename core/templates/dev/head/services/{CsrfService.ts => CsrfTokenService.ts} (85%) rename core/templates/dev/head/services/{CsrfServiceSpec.ts => CsrfTokenServiceSpec.ts} (75%) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 69f316453b4e..f4e7c003b198 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -409,7 +409,7 @@ /core/templates/dev/head/pages/footer_js_libs.html @vojtechjelinek /core/templates/dev/head/pages/header_css_libs.html @vojtechjelinek /core/templates/dev/head/pages/header_js_libs.html @vojtechjelinek -/core/templates/dev/head/services/CsrfService*.ts @jamesjay4199 @vojtechjelinek +/core/templates/dev/head/services/CsrfTokenService*.ts @jamesjay4199 @vojtechjelinek /gulpfile.js @vojtechjelinek /jinja_utils*.py @vojtechjelinek /webpack.config.ts @vojtechjelinek diff --git a/core/controllers/admin_test.py b/core/controllers/admin_test.py index 8cb707993e86..6e5eea23709c 100644 --- a/core/controllers/admin_test.py +++ b/core/controllers/admin_test.py @@ -56,7 +56,7 @@ def test_change_configuration_property(self): """Test that configuration properties can be changed.""" self.login(self.ADMIN_EMAIL, is_super_admin=True) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() new_config_value = True response_dict = self.get_json('/adminhandler') @@ -91,7 +91,7 @@ class GenerateDummyExplorationsTest(test_utils.GenericTestBase): def test_generate_count_greater_than_publish_count(self): self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/adminhandler', { 'action': 'generate_dummy_explorations', @@ -106,7 +106,7 @@ def test_generate_count_greater_than_publish_count(self): def test_generate_count_equal_to_publish_count(self): self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/adminhandler', { 'action': 'generate_dummy_explorations', @@ -121,7 +121,7 @@ def test_generate_count_equal_to_publish_count(self): def test_generate_count_less_than_publish_count(self): self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() generated_exps_response = self.post_json( '/adminhandler', { 'action': 'generate_dummy_explorations', @@ -160,7 +160,7 @@ def test_view_and_update_role(self): response_dict, {'user1': feconf.ROLE_ID_EXPLORATION_EDITOR}) # Check role correctly gets updated. - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response_dict = self.post_json( feconf.ADMIN_ROLE_HANDLER_URL, {'role': feconf.ROLE_ID_MODERATOR, 'username': username}, @@ -187,7 +187,7 @@ def test_invalid_username_in_view_and_update_role(self): expected_status_int=400) # Trying to update role of non-existent user. - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.ADMIN_ROLE_HANDLER_URL, {'role': feconf.ROLE_ID_MODERATOR, 'username': username}, @@ -288,7 +288,7 @@ def test_clear_search_index(self): self.assertEqual(result_collections, ['0']) self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.login(self.ADMIN_EMAIL, is_super_admin=True) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() generated_exps_response = self.post_json( '/adminhandler', { 'action': 'clear_search_index' diff --git a/core/controllers/base.py b/core/controllers/base.py index 32d8983f32d6..b80b39896e63 100755 --- a/core/controllers/base.py +++ b/core/controllers/base.py @@ -325,11 +325,6 @@ def render_template(self, filepath, iframe_restriction='DENY'): # Create a new csrf token for inclusion in HTML responses. This assumes # that tokens generated in one handler will be sent back to a handler # with the same page name. - values['csrf_token'] = '' - - if self.REQUIRE_PAYLOAD_CSRF_CHECK: - values['csrf_token'] = CsrfTokenManager.create_csrf_token( - self.user_id) self.response.cache_control.no_cache = True self.response.cache_control.must_revalidate = True @@ -502,7 +497,7 @@ def _create_token(cls, user_id, issued_on): """Creates a new CSRF token. Args: - user_id: str. The user_id for which the token is generated. + user_id: str|None. The user_id for which the token is generated. issued_on: float. The timestamp at which the token was issued. Returns: @@ -543,7 +538,7 @@ def create_csrf_token(cls, user_id): """Creates a CSRF token for the given user_id. Args: - user_id: str. The user_id for whom the token is generated. + user_id: str|None. The user_id for whom the token is generated. Returns: str. The generated CSRF token. @@ -555,7 +550,7 @@ def is_csrf_token_valid(cls, user_id, token): """Validates a given CSRF token. Args: - user_id: str. The user_id to validate the CSRF token against. + user_id: str|None. The user_id to validate the CSRF token against. token: str. The CSRF token to validate. Returns: @@ -584,7 +579,6 @@ class CsrfTokenHandler(BaseHandler): """Handles sending CSRF tokens to the frontend.""" GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON - REQUIRE_PAYLOAD_CSRF_CHECK = False def get(self): csrf_token = CsrfTokenManager.create_csrf_token( diff --git a/core/controllers/base_test.py b/core/controllers/base_test.py index dc6f7a15b069..48a691761f31 100644 --- a/core/controllers/base_test.py +++ b/core/controllers/base_test.py @@ -671,7 +671,7 @@ def test_every_method_has_decorator(self): # Following handler are present in base.py where acl_decorators # cannot be imported. if (handler.__name__ in ( - ('CsrfTokenHandler', 'Error404Handler', 'LogoutPage'))): + ('CsrfTokenHandler', 'Error404Handler', 'LogoutPage'))): continue if handler.get != base.BaseHandler.get: @@ -856,7 +856,7 @@ def test_error_is_raised_on_opening_new_tab_during_signup(self): during signup. """ self.login('abc@example.com') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.get_html_response('/about', expected_status_int=302) self.assertIn('Logout', response.location) @@ -876,7 +876,7 @@ def test_no_error_is_raised_on_opening_new_tab_after_signup(self): after signup. """ self.login('abc@example.com') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, { 'username': 'abc', @@ -894,7 +894,7 @@ def test_valid_token_is_returned(self): the handler. """ - response = self.get_json('/csrf') + response = self.get_json('/csrfhandler') csrf_token = response['token'] self.assertTrue(base.CsrfTokenManager.is_csrf_token_valid( diff --git a/core/controllers/collection_editor_test.py b/core/controllers/collection_editor_test.py index 415f16b0e5a4..b7858d4d4e3c 100644 --- a/core/controllers/collection_editor_test.py +++ b/core/controllers/collection_editor_test.py @@ -132,7 +132,7 @@ def test_editable_collection_handler_put_with_invalid_payload_version(self): self.login(self.EDITOR_EMAIL) # Call get handler to return the csrf token. - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Raises error as version is None. json_response = self.put_json( @@ -176,7 +176,7 @@ def test_editable_collection_handler_put_cannot_access(self): self.login(self.VIEWER_EMAIL) # Call get handler to return the csrf token. - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Ensure viewers do not have access to the PUT Handler. self.put_json( @@ -203,7 +203,7 @@ def test_editable_collection_handler_put_can_access(self): self.login(self.EDITOR_EMAIL) # Call get handler to return the csrf token. - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() json_response = self.put_json( '%s/%s' % ( feconf.COLLECTION_EDITOR_DATA_URL_PREFIX, @@ -280,7 +280,7 @@ def test_can_not_publish_collection_with_invalid_payload_version(self): self.save_new_valid_collection( collection_id, self.owner_id, exploration_id=exploration_id) rights_manager.publish_exploration(self.owner, exploration_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Raises error as version is None. response_dict = self.put_json( @@ -316,7 +316,7 @@ def test_can_not_unpublish_collection_with_invalid_payload_version(self): collection_id, self.owner_id, exploration_id=exploration_id) rights_manager.publish_exploration(self.owner, exploration_id) collection = collection_services.get_collection_by_id(collection_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response_dict = self.put_json( '/collection_editor_handler/publish/%s' % collection_id, {'version': collection.version}, @@ -326,7 +326,7 @@ def test_can_not_unpublish_collection_with_invalid_payload_version(self): # Login as admin and try to unpublish the collection. self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Raises error as version is None. response_dict = self.put_json( @@ -363,7 +363,7 @@ def test_publish_unpublish_collection(self): collection_id, self.owner_id, exploration_id=exploration_id) rights_manager.publish_exploration(self.owner, exploration_id) collection = collection_services.get_collection_by_id(collection_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response_dict = self.put_json( '/collection_editor_handler/publish/%s' % collection_id, {'version': collection.version}, @@ -373,7 +373,7 @@ def test_publish_unpublish_collection(self): # Login as admin and unpublish the collection. self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response_dict = self.put_json( '/collection_editor_handler/unpublish/%s' % collection_id, {'version': collection.version}, diff --git a/core/controllers/creator_dashboard_test.py b/core/controllers/creator_dashboard_test.py index 96a07b7c18ce..e2142db8806c 100644 --- a/core/controllers/creator_dashboard_test.py +++ b/core/controllers/creator_dashboard_test.py @@ -726,7 +726,7 @@ def test_can_update_display_preference(self): display_preference = self.get_json( feconf.CREATOR_DASHBOARD_DATA_URL)['display_preference'] self.assertEqual(display_preference, 'card') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.CREATOR_DASHBOARD_DATA_URL, {'display_preference': 'list'}, @@ -739,7 +739,7 @@ def test_can_update_display_preference(self): def test_can_create_collections(self): self.set_admins([self.OWNER_USERNAME]) self.login(self.OWNER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() collection_id = self.post_json( feconf.NEW_COLLECTION_URL, {}, csrf_token=csrf_token)[ creator_dashboard.COLLECTION_ID_KEY] @@ -884,7 +884,7 @@ def test_new_exploration_ids(self): """Test generation of exploration ids.""" self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() exp_a_id = self.post_json( feconf.NEW_EXPLORATION_URL, {}, csrf_token=csrf_token )[creator_dashboard.EXPLORATION_ID_KEY] @@ -894,7 +894,7 @@ def test_new_exploration_ids(self): def test_can_non_admins_can_not_upload_exploration(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.post_json( feconf.UPLOAD_EXPLORATION_URL, {}, csrf_token=csrf_token, @@ -910,7 +910,7 @@ def test_can_upload_exploration(self): self.set_admins([self.ADMIN_USERNAME]) self.login(self.ADMIN_EMAIL, is_super_admin=True) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() explorations_list = self.get_json( feconf.CREATOR_DASHBOARD_DATA_URL)['explorations_list'] self.assertEqual(explorations_list, []) @@ -930,7 +930,7 @@ def test_can_not_upload_exploration_when_server_does_not_allow_file_upload( self): self.set_admins([self.ADMIN_USERNAME]) self.login(self.ADMIN_EMAIL, is_super_admin=True) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s?yaml_file=%s' % ( feconf.UPLOAD_EXPLORATION_URL, diff --git a/core/controllers/editor_test.py b/core/controllers/editor_test.py index a91fed5fbd03..5ad694573478 100644 --- a/core/controllers/editor_test.py +++ b/core/controllers/editor_test.py @@ -143,12 +143,12 @@ def test_that_default_exploration_cannot_be_published(self): """ self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() exp_id = self.post_json( feconf.NEW_EXPLORATION_URL, {}, csrf_token=csrf_token )[creator_dashboard.EXPLORATION_ID_KEY] - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() publish_url = '%s/%s' % (feconf.EXPLORATION_STATUS_PREFIX, exp_id) self.put_json( publish_url, { @@ -162,7 +162,7 @@ def test_add_new_state_error_cases(self): current_version = 1 self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() def _get_payload(new_state_name, version=None): """Gets the payload in the dict format.""" @@ -237,7 +237,7 @@ def test_publish_exploration(self): exp_id = exp_services.get_new_exploration_id() self.save_new_valid_exploration( exp_id, self.admin_id, end_state_name='end state') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() publish_url = '%s/%s' % (feconf.EXPLORATION_STATUS_PREFIX, exp_id) exploration_rights = self.put_json( @@ -593,7 +593,7 @@ def test_state_yaml_handler(self): exploration.add_states(['State A', 'State 2', 'State 3']) exploration.states['State A'].update_interaction_id('TextInput') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.post_json('/createhandler/state_yaml/%s' % exp_id, { 'state_dict': exploration.states['State A'].to_dict(), 'width': 50, @@ -610,7 +610,7 @@ def test_state_yaml_handler_with_no_state_dict_raises_error(self): owner_id = self.get_user_id_from_email(self.OWNER_EMAIL) self.save_new_valid_exploration(exp_id, owner_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/createhandler/state_yaml/%s' % exp_id, {}, @@ -760,7 +760,7 @@ def test_record_user_saw_tutorial(self): self.save_new_valid_exploration(exp_id, owner_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() user_settings = user_services.get_user_settings(owner_id) @@ -1106,7 +1106,7 @@ def test_get_with_disabled_exploration_id_raises_error(self): def test_reverting_to_old_exploration(self): """Test reverting to old exploration versions.""" # Open editor page. - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # May not revert to any version that's not 1. for rev_version in (-1, 0, 2, 3, 4, '1', ()): @@ -1190,7 +1190,7 @@ def test_versioning_for_default_exploration(self): expected_status_int=404) def test_revert_with_invalid_current_version_raises_error(self): - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.post_json( '/createhandler/revert/%s' % self.EXP_ID, { @@ -1278,7 +1278,7 @@ def test_for_assign_role_for_exploration(self): exploration.states['State 2'].update_interaction_id('TextInput') exploration.states['State 3'].update_interaction_id('TextInput') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Owner adds rights for other users. rights_url = '%s/%s' % (feconf.EXPLORATION_RIGHTS_PREFIX, exp_id) @@ -1321,7 +1321,7 @@ def test_for_assign_role_for_exploration(self): response = self.get_html_response('/create/%s' % exp_id) self.assert_can_edit(response.body) self.assert_can_voiceover(response.body) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Check that collaborator can add a new state called 'State 4'. add_url = '%s/%s' % (feconf.EXPLORATION_DATA_PREFIX, exp_id) @@ -1362,7 +1362,7 @@ def test_for_assign_role_for_exploration(self): self.login(self.COLLABORATOR2_EMAIL) response = self.get_html_response('/create/%s' % exp_id) self.assert_can_edit(response.body) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Check that collaborator2 can add a new state called 'State 5'. add_url = '%s/%s' % (feconf.EXPLORATION_DATA_PREFIX, exp_id) @@ -1403,7 +1403,7 @@ def test_for_assign_role_for_exploration(self): response = self.get_html_response('/create/%s' % exp_id) self.assert_cannot_edit(response.body) self.assert_can_voiceover(response.body) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Check that voice artist cannot add new members. exploration = exp_services.get_exploration_by_id(exp_id) @@ -1427,7 +1427,7 @@ def test_transfering_ownership_to_the_community(self): self.save_new_valid_exploration( exp_id, self.owner_id, title='My Exploration', end_state_name='END') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() rights_manager.publish_exploration(self.owner, exp_id) # Owner transfers ownership to the community. @@ -1480,7 +1480,7 @@ def test_cannot_transfer_ownership_of_invalid_exp_to_the_community(self): # The exploration is now invalid due to invalid language code. # Therefore, the following PUT request will raise an exception after # creating a domain object from the exploration model and validating it. - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() rights_url = '%s/%s' % (feconf.EXPLORATION_RIGHTS_PREFIX, exp_id) response = self.put_json( @@ -1505,7 +1505,7 @@ def test_put_with_invalid_new_member_raises_error(self): self.login(self.OWNER_EMAIL) exp_id = 'exp_id' self.save_new_valid_exploration(exp_id, self.owner_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() exploration = exp_services.get_exploration_by_id(exp_id) response = self.put_json( @@ -1523,7 +1523,7 @@ def test_make_private_exploration_viewable(self): self.login(self.OWNER_EMAIL) exp_id = 'exp_id' self.save_new_valid_exploration(exp_id, self.owner_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() exploration = exp_services.get_exploration_by_id(exp_id) exploration_rights = rights_manager.get_exploration_rights(exp_id) self.assertFalse(exploration_rights.viewable_if_private) @@ -1540,7 +1540,7 @@ def test_put_with_no_specified_changes_raise_error(self): self.login(self.OWNER_EMAIL) exp_id = 'exp_id' self.save_new_valid_exploration(exp_id, self.owner_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() exploration = exp_services.get_exploration_by_id(exp_id) response = self.put_json( @@ -1567,7 +1567,7 @@ def test_user_exploration_emails_handler(self): exploration = exp_services.get_exploration_by_id(exp_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() exp_email_preferences = ( user_services.get_email_preferences_for_exploration( self.owner_id, exp_id)) @@ -1614,7 +1614,7 @@ def test_put_with_invalid_message_type_raises_error(self): self.login(self.OWNER_EMAIL) exp_id = 'eid' self.save_new_valid_exploration(exp_id, self.owner_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.put_json( '%s/%s' % (feconf.USER_EXPLORATION_EMAILS_PREFIX, exp_id), @@ -1662,7 +1662,7 @@ def test_error_cases_for_email_sending(self): self.login(self.MODERATOR_EMAIL) # Get csrf token. - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Try to unpublish the exploration without an email body. This # should cause an error. @@ -1714,7 +1714,7 @@ def test_email_is_sent_correctly_when_unpublishing(self): self.login(self.MODERATOR_EMAIL) # Go to the exploration editor page. - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() new_email_body = 'Your exploration is unpublished :(' @@ -1774,7 +1774,7 @@ def test_email_functionality_cannot_be_used_by_non_moderators(self): self.login(self.EDITOR_EMAIL) # Go to the exploration editor page. - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() new_email_body = 'Your exploration is unpublished :(' @@ -2040,7 +2040,7 @@ def setUp(self): } self.login(self.MODERATOR_EMAIL) - self.csrf_token = self.get_csrf_token() + self.csrf_token = self.get_new_csrf_token() def test_resolve_issue_handler(self): """Test that resolving an issue deletes associated playthroughs.""" @@ -2161,7 +2161,7 @@ def setUp(self): self._create_exp_user_data_model_objects_for_tests() # Generate CSRF token. - self.csrf_token = self.get_csrf_token() + self.csrf_token = self.get_new_csrf_token() def test_exploration_loaded_with_draft_applied(self): response = self.get_json( diff --git a/core/controllers/email_dashboard_test.py b/core/controllers/email_dashboard_test.py index 22651dbaaa9d..5a5ee248a94c 100644 --- a/core/controllers/email_dashboard_test.py +++ b/core/controllers/email_dashboard_test.py @@ -45,7 +45,7 @@ def setUp(self): def test_that_handler_works_correctly(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -126,7 +126,7 @@ def test_that_page_is_accessible_to_authorised_users_only(self): def test_that_exception_is_raised_for_invalid_input(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -258,7 +258,7 @@ def test_email_dashboard_result_page_with_invalid_query_id_raises_400(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.post_json( '/emaildashboardresult/%s' % 'invalid_query_id', {}, @@ -301,7 +301,7 @@ def test_email_dashboard_result_page_with_mismatch_of_query_id_raises_401( taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Raises authorization error when passing a query id whose associated # query model is not created by the logged in user. @@ -339,7 +339,7 @@ def test_cancel_email_handler_with_invalid_query_id_raises_400(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.post_json( '/emaildashboardcancelresult/%s' % 'invalid_query_id', {}, @@ -381,7 +381,7 @@ def test_cancel_email_handler_with_mismatch_of_query_id_raises_401(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Raises authorization error when passing a query id whose associated # query model is not created by the logged in user. response = self.post_json( @@ -418,7 +418,7 @@ def test_bulk_email_handler_with_invalid_query_id_raises_400(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.post_json( '/emaildashboardtestbulkemailhandler/%s' % 'invalid_query_id', {}, @@ -460,7 +460,7 @@ def test_bulk_email_handler_with_mismatch_of_query_id_raises_401(self): taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 0) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Raises authorization error when passing a query id whose associated # query model is not created by the logged in user. @@ -475,7 +475,7 @@ def test_bulk_email_handler_with_mismatch_of_query_id_raises_401(self): def test_that_correct_emails_are_sent_to_all_users(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -512,7 +512,7 @@ def test_that_correct_emails_are_sent_to_all_users(self): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboardresult/%s' % query_model.id, { 'data': { @@ -575,7 +575,7 @@ def test_that_valid_exceptions_are_raised(self): with self.assertRaisesRegexp(Exception, '400 Bad Request'): self.get_html_response('/emaildashboardresult/%s' % 'q123') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -627,7 +627,7 @@ def test_that_valid_exceptions_are_raised(self): with self.swap(feconf, 'CAN_SEND_EMAILS', True): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboardresult/%s' % query_models[0].id, { 'data': { @@ -649,7 +649,7 @@ def test_that_valid_exceptions_are_raised(self): def test_that_correct_emails_are_sent_to_max_n_recipients(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -672,7 +672,7 @@ def test_that_correct_emails_are_sent_to_max_n_recipients(self): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboardresult/%s' % query_models[0].id, { 'data': { @@ -694,7 +694,7 @@ def test_that_correct_emails_are_sent_to_max_n_recipients(self): def test_that_no_emails_are_sent_if_query_is_canceled(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -717,7 +717,7 @@ def test_that_no_emails_are_sent_if_query_is_canceled(self): # Send email from email dashboard result page. self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboardcancelresult/%s' % query_models[0].id, {}, csrf_token=csrf_token) @@ -731,7 +731,7 @@ def test_that_no_emails_are_sent_if_query_is_canceled(self): def test_that_test_email_for_bulk_emails_is_sent(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -754,7 +754,7 @@ def test_that_test_email_for_bulk_emails_is_sent(self): # Check that correct test email is sent. self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboardtestbulkemailhandler/%s' % query_models[0].id, { 'email_body': email_body, @@ -792,7 +792,7 @@ def test_that_test_email_for_bulk_emails_is_sent(self): def test_that_test_email_is_not_sent_to_query_recipients(self): self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboarddatahandler', { 'data': { @@ -811,7 +811,7 @@ def test_that_test_email_is_not_sent_to_query_recipients(self): self.process_and_flush_pending_tasks() self.login(self.SUBMITTER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/emaildashboardtestbulkemailhandler/%s' % query_models[0].id, { 'email_body': 'email_body', diff --git a/core/controllers/feedback_test.py b/core/controllers/feedback_test.py index 499d2ebac688..9220f9dc9808 100644 --- a/core/controllers/feedback_test.py +++ b/core/controllers/feedback_test.py @@ -54,7 +54,7 @@ def setUp(self): # The corresponding user has already registered as an editor, and has a # username. self.login(self.EDITOR_EMAIL) - self.csrf_token = self.get_csrf_token() + self.csrf_token = self.get_new_csrf_token() self.post_json('%s/%s' % ( feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID ), { @@ -130,7 +130,7 @@ def setUp(self): def test_create_thread(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { 'subject': u'New Thread ¡unicode!', @@ -162,7 +162,7 @@ def test_create_thread(self): def test_missing_thread_subject_raises_400_error(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response_dict = self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { 'state_name': None, @@ -174,7 +174,7 @@ def test_missing_thread_subject_raises_400_error(self): def test_missing_thread_text_raises_400_error(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response_dict = self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { @@ -188,7 +188,7 @@ def test_missing_thread_text_raises_400_error(self): def test_post_message_to_existing_thread(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # First, create a thread. self.post_json( @@ -247,7 +247,7 @@ def test_no_username_shown_for_logged_out_learners(self): exp_services.save_new_exploration(self.editor_id, exploration) rights_manager.publish_exploration(self.editor, new_exp_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/explorehandler/give_feedback/%s' % new_exp_id, { @@ -269,7 +269,7 @@ def test_no_username_shown_for_logged_out_learners(self): def test_message_id_assignment_for_multiple_posts_to_same_thread(self): # Create a thread for others to post to. self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/%s' % (feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID), { 'state_name': None, @@ -316,7 +316,7 @@ def _get_email(index): # Each of these users posts a new message to the same thread. for num in range(num_users): self.login(_get_email(num)) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( thread_url, { 'text': 'New Message %s' % num @@ -403,7 +403,7 @@ def _get_message_ids_in_a_thread(self, thread_id): def test_feedback_threads(self): self.login(self.USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json('%s/%s' % ( feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID @@ -429,7 +429,7 @@ def test_feedback_threads(self): self.logout() self.login(self.OWNER_EMAIL_1) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # The owner opens the feedback thread. thread_url = '%s/%s' % (feconf.FEEDBACK_THREAD_URL_PREFIX, thread_id) @@ -458,7 +458,7 @@ def test_feedback_threads(self): self.logout() self.login(self.USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # The user opens the feedback thread. thread_url = '%s/%s' % (feconf.FEEDBACK_THREAD_URL_PREFIX, thread_id) @@ -487,7 +487,7 @@ def test_feedback_threads(self): # Another owner logs in. self.login(self.OWNER_EMAIL_2) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # The second owner opens the feedback thread. thread_url = '%s/%s' % (feconf.FEEDBACK_THREAD_URL_PREFIX, thread_id) diff --git a/core/controllers/learner_dashboard_test.py b/core/controllers/learner_dashboard_test.py index 30466d25b9b1..f7f590838942 100644 --- a/core/controllers/learner_dashboard_test.py +++ b/core/controllers/learner_dashboard_test.py @@ -290,7 +290,7 @@ def setUp(self): self.editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL) # Get the CSRF token and create a single thread with a single message. self.login(self.EDITOR_EMAIL) - self.csrf_token = self.get_csrf_token() + self.csrf_token = self.get_new_csrf_token() self.post_json('%s/%s' % ( feconf.FEEDBACK_THREADLIST_URL_PREFIX, self.EXP_ID_1 ), { diff --git a/core/controllers/learner_playlist_test.py b/core/controllers/learner_playlist_test.py index fd9f28b3694c..17f2ca068bca 100644 --- a/core/controllers/learner_playlist_test.py +++ b/core/controllers/learner_playlist_test.py @@ -71,7 +71,7 @@ def setUp(self): def test_add_exploration_to_learner_playlist(self): self.login(self.VIEWER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Add one exploration to the playlist. self.post_json( @@ -168,7 +168,7 @@ def test_add_exploration_to_learner_playlist(self): def test_add_collection_to_learner_playlist(self): self.login(self.VIEWER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Add one collection to the playlist. self.post_json( diff --git a/core/controllers/library_test.py b/core/controllers/library_test.py index 7e635bab7c8a..8cbfd20f3625 100644 --- a/core/controllers/library_test.py +++ b/core/controllers/library_test.py @@ -273,7 +273,7 @@ def test_library_index_handler_for_user_preferred_language(self): 'preferred_language_codes': ['en'], }, response_dict) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Change the user's preferred language to de. self.put_json( @@ -401,7 +401,7 @@ def test_library_group_page_for_user_preferred_language(self): 'preferred_language_codes': ['en'], }, response_dict) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json( feconf.PREFERENCES_DATA_URL, diff --git a/core/controllers/moderator_test.py b/core/controllers/moderator_test.py index d72afaf11798..486c3d9f834c 100644 --- a/core/controllers/moderator_test.py +++ b/core/controllers/moderator_test.py @@ -69,7 +69,7 @@ def setUp(self): def test_unpublished_activities_cannot_be_added_to_featured_list(self): self.login(self.MODERATOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Posting a list that includes private activities results in an error. self.post_json( diff --git a/core/controllers/profile.py b/core/controllers/profile.py index 5c7cfc760a1c..ebf19ec63c57 100644 --- a/core/controllers/profile.py +++ b/core/controllers/profile.py @@ -284,6 +284,9 @@ def get(self): 'has_ever_registered': bool( user_settings.username and user_settings.last_agreed_to_terms), 'username': user_settings.username, + + # Send CSRF token here because any + # request from signup page invalidates the session. 'csrf_token': base.CsrfTokenManager.create_csrf_token( self.user_id), }) diff --git a/core/controllers/profile_test.py b/core/controllers/profile_test.py index 6ee9cd67af53..323efad341c6 100644 --- a/core/controllers/profile_test.py +++ b/core/controllers/profile_test.py @@ -49,7 +49,7 @@ def test_going_somewhere_else_while_signing_in_logs_user_out(self): def test_to_check_url_redirection_in_signup(self): """To validate the redirections from return_url.""" self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Registering this user fully. self.post_json( @@ -92,7 +92,7 @@ def strip_domain_from_location_header(url): def test_accepting_terms_is_handled_correctly(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response_dict = self.post_json( feconf.SIGNUP_DATA_URL, {'agreed_to_terms': False}, @@ -115,7 +115,7 @@ def test_accepting_terms_is_handled_correctly(self): def test_username_is_handled_correctly(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response_dict = self.post_json( feconf.SIGNUP_DATA_URL, {'agreed_to_terms': True}, @@ -151,7 +151,7 @@ def test_username_is_handled_correctly(self): def test_default_dashboard_for_new_users(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # This user should have the creator dashboard as default. self.post_json( @@ -169,7 +169,7 @@ def test_default_dashboard_for_new_users(self): self.logout() self.login(self.VIEWER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # This user should have the learner dashboard as default. self.post_json( @@ -195,10 +195,9 @@ def test_user_settings_of_non_existing_user(self): response = self.get_json(feconf.SIGNUP_DATA_URL) self.assertEqual(can_send_emails, response['can_send_emails']) - self.assertEqual(has_agreed_to_latest_terms, - response['has_agreed_to_latest_terms']) - self.assertEqual(has_ever_registered, - response['has_ever_registered']) + self.assertEqual( + has_agreed_to_latest_terms, response['has_agreed_to_latest_terms']) + self.assertEqual(has_ever_registered, response['has_ever_registered']) self.assertEqual(username, response['username']) self.logout() @@ -212,10 +211,11 @@ def test_user_settings_of_existing_user(self): with self.swap(feconf, 'CAN_SEND_EMAILS', True): response = self.get_json(feconf.SIGNUP_DATA_URL) self.assertEqual(can_send_emails, response['can_send_emails']) - self.assertEqual(has_agreed_to_latest_terms, + self.assertEqual( + has_agreed_to_latest_terms, response['has_agreed_to_latest_terms']) - self.assertEqual(has_ever_registered, - response['has_ever_registered']) + self.assertEqual( + has_ever_registered, response['has_ever_registered']) self.assertEqual(username, response['username']) self.logout() @@ -227,7 +227,7 @@ def test_username_check(self): self.signup('abc@example.com', username='abc') self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response_dict = self.post_json( feconf.USERNAME_CHECK_DATA_URL, {'username': 'abc'}, @@ -265,7 +265,7 @@ class EmailPreferencesTests(test_utils.GenericTestBase): def test_user_not_setting_email_prefs_on_signup(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, {'username': 'abc', 'agreed_to_terms': True}, @@ -301,7 +301,7 @@ def test_user_not_setting_email_prefs_on_signup(self): def test_user_allowing_emails_on_signup(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, {'username': 'abc', 'agreed_to_terms': True, @@ -337,7 +337,7 @@ def test_user_allowing_emails_on_signup(self): def test_user_disallowing_emails_on_signup(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, {'username': 'abc', 'agreed_to_terms': True, @@ -380,7 +380,7 @@ def test_email_preferences_updates(self): self.signup(self.EDITOR_EMAIL, username=self.EDITOR_USERNAME) editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL) self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() payload = { 'update_type': 'email_preferences', @@ -459,7 +459,7 @@ def test_can_see_subscriptions(self): def test_can_update_profile_picture_data_url(self): self.login(self.OWNER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() user_settings = user_services.get_user_settings(self.owner_id) self.assertTrue( user_settings.profile_picture_data_url.startswith( @@ -477,7 +477,7 @@ def test_can_update_profile_picture_data_url(self): def test_can_update_default_dashboard(self): self.login(self.OWNER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() user_settings = user_services.get_user_settings(self.owner_id) self.assertIsNone(user_settings.default_dashboard) self.put_json( @@ -492,7 +492,7 @@ def test_can_update_default_dashboard(self): def test_update_preferences_with_invalid_update_type_raises_exception(self): self.login(self.OWNER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with self.assertRaisesRegexp(Exception, 'Invalid update type:'): self.put_json( feconf.PREFERENCES_DATA_URL, @@ -528,7 +528,7 @@ class ProfileDataHandlerTests(test_utils.GenericTestBase): def test_preference_page_updates(self): self.signup(self.EDITOR_EMAIL, username=self.EDITOR_USERNAME) self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() original_preferences = self.get_json('/preferenceshandler/data') self.assertEqual( ['en'], original_preferences['preferred_language_codes']) @@ -555,7 +555,7 @@ def test_preference_page_updates(self): def test_profile_data_is_independent_of_currently_logged_in_user(self): self.signup(self.EDITOR_EMAIL, username=self.EDITOR_USERNAME) self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json( '/preferenceshandler/data', {'update_type': 'user_bio', 'data': 'My new editor bio'}, @@ -568,7 +568,7 @@ def test_profile_data_is_independent_of_currently_logged_in_user(self): self.signup(self.VIEWER_EMAIL, username=self.VIEWER_USERNAME) self.login(self.VIEWER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json( '/preferenceshandler/data', {'update_type': 'user_bio', 'data': 'My new viewer bio'}, @@ -766,7 +766,7 @@ def test_save_site_language_handler(self): """ language_code = 'es' self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json( '/preferenceshandler/data', { 'update_type': 'preferred_site_language_code', @@ -785,7 +785,7 @@ def test_can_update_site_language_code(self): user_settings = user_services.get_user_settings( self.editor_id, strict=True) self.assertIsNone(user_settings.preferred_site_language_code) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json( feconf.SITE_LANGUAGE_DATA_URL, payload={'site_language_code': 'en'}, csrf_token=csrf_token) @@ -804,7 +804,7 @@ class LongUserBioHandlerTests(test_utils.GenericTestBase): def test_userbio_within_limit(self): self.signup(self.EMAIL_A, self.USERNAME_A) self.login(self.EMAIL_A) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json( '/preferenceshandler/data', { 'update_type': 'user_bio', @@ -819,7 +819,7 @@ def test_userbio_within_limit(self): def test_user_bio_exceeds_limit(self): self.signup(self.EMAIL_B, self.USERNAME_B) self.login(self.EMAIL_B) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() user_bio_response = self.put_json( '/preferenceshandler/data', { 'update_type': 'user_bio', diff --git a/core/controllers/question_editor_test.py b/core/controllers/question_editor_test.py index 1369b70e632d..01b1c9e1e7ab 100644 --- a/core/controllers/question_editor_test.py +++ b/core/controllers/question_editor_test.py @@ -67,7 +67,7 @@ class QuestionCreationHandlerTest(BaseQuestionEditorControllerTests): def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): self.login(self.NEW_USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/%s' % (feconf.NEW_QUESTION_URL, self.skill_id), {}, csrf_token=csrf_token, expected_status_int=401) @@ -75,7 +75,7 @@ def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): def test_post_with_editor_email_does_not_allow_question_creation(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() question_dict = self.question.to_dict() question_dict['id'] = None self.post_json( @@ -86,7 +86,7 @@ def test_post_with_editor_email_does_not_allow_question_creation(self): def test_post_with_incorrect_skill_id_returns_404(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() incorrect_skill_id = 'abc123456789' self.post_json( '%s/%s' % (feconf.NEW_QUESTION_URL, incorrect_skill_id), @@ -95,7 +95,7 @@ def test_post_with_incorrect_skill_id_returns_404(self): def test_post_with_incorrect_list_of_skill_ids_returns_400(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() incorrect_skill_id = [1, 2] self.post_json( '%s/%s' % (feconf.NEW_QUESTION_URL, incorrect_skill_id), @@ -104,7 +104,7 @@ def test_post_with_incorrect_list_of_skill_ids_returns_400(self): def test_post_with_incorrect_type_of_skill_ids_returns_400(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() incorrect_skill_id = 1 self.post_json( '%s/%s' % (feconf.NEW_QUESTION_URL, incorrect_skill_id), @@ -113,7 +113,7 @@ def test_post_with_incorrect_type_of_skill_ids_returns_400(self): def test_post_with_incorrect_question_id_returns_400(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() question_dict = self.question.to_dict() question_dict['id'] = 'abc123456789' self.post_json( @@ -124,7 +124,7 @@ def test_post_with_incorrect_question_id_returns_400(self): def test_post_with_incorrect_question_schema_returns_400(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() question_dict = self.question.to_dict() del question_dict['question_state_data']['content'] self.post_json( @@ -135,7 +135,7 @@ def test_post_with_incorrect_question_schema_returns_400(self): def test_post_with_admin_email_allows_question_creation(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() question_dict = self.question.to_dict() question_dict['id'] = None self.post_json( @@ -152,7 +152,7 @@ def test_post_with_admin_email_allows_question_creation(self): def test_post_with_topic_manager_email_allows_question_creation(self): self.login(self.TOPIC_MANAGER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() question_dict = self.question.to_dict() question_dict['id'] = None self.post_json( @@ -169,7 +169,7 @@ def test_post_with_topic_manager_email_allows_question_creation(self): def test_post_with_invalid_question_returns_400_status(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() question_dict = self.question.to_dict() question_dict['id'] = None question_dict['question_state_data'] = 'invalid_question_state_data' @@ -195,7 +195,7 @@ def setUp(self): def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): self.login(self.NEW_USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/%s/%s' % ( feconf.QUESTION_SKILL_LINK_URL_PREFIX, self.question_id, @@ -205,7 +205,7 @@ def test_post_with_non_admin_or_topic_manager_email_disallows_access(self): def test_post_with_incorrect_skill_id_returns_404(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() incorrect_skill_id = 'abc123456789' self.post_json( '%s/%s/%s' % ( @@ -216,7 +216,7 @@ def test_post_with_incorrect_skill_id_returns_404(self): def test_post_with_admin_email_allows_question_linking(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/%s/%s' % ( feconf.QUESTION_SKILL_LINK_URL_PREFIX, self.question_id, @@ -234,7 +234,7 @@ def test_post_with_admin_email_allows_question_linking(self): def test_post_with_topic_manager_email_allows_question_linking(self): self.login(self.TOPIC_MANAGER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/%s/%s' % ( feconf.QUESTION_SKILL_LINK_URL_PREFIX, self.question_id, @@ -439,7 +439,7 @@ def test_put_with_admin_email_allows_question_editing(self): payload['commit_message'] = 'update question data' self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response_json = self.put_json( '%s/%s' % ( feconf.QUESTION_EDITOR_DATA_URL_PREFIX, self.question_id), @@ -484,7 +484,7 @@ def test_put_with_topic_manager_email_allows_question_editing(self): payload['commit_message'] = 'update question data' self.login(self.TOPIC_MANAGER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() payload = {} new_question_data = self._create_valid_question_data('GHI') change_list = [{ @@ -522,7 +522,7 @@ def test_put_with_editor_email_allows_question_editing(self): payload['commit_message'] = 'update question data' self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() payload = {} new_question_data = self._create_valid_question_data('GHI') change_list = [{ @@ -558,7 +558,7 @@ def test_put_with_creating_new_fully_specified_question_returns_400(self): payload['change_list'] = change_list payload['commit_message'] = 'update question data' self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json( '%s/%s' % ( feconf.QUESTION_EDITOR_DATA_URL_PREFIX, self.question_id), diff --git a/core/controllers/reader_test.py b/core/controllers/reader_test.py index 86a1691c0352..d4c2327c8e22 100644 --- a/core/controllers/reader_test.py +++ b/core/controllers/reader_test.py @@ -435,7 +435,7 @@ def test_assign_and_read_ratings(self): self.signup('user@example.com', 'user') self.login('user@example.com') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # User checks rating. ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) @@ -476,7 +476,7 @@ def test_non_logged_in_users_cannot_rate(self): self.signup('user@example.com', 'user') self.login('user@example.com') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.logout() ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) @@ -498,7 +498,7 @@ def test_ratings_by_different_users(self): self.signup('b@example.com', 'b') self.login('a@example.com') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json( '/explorehandler/rating/%s' % self.EXP_ID, { 'user_rating': 4 @@ -507,7 +507,7 @@ def test_ratings_by_different_users(self): self.logout() self.login('b@example.com') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) self.assertEqual(ratings['user_rating'], None) self.put_json( @@ -1012,7 +1012,7 @@ def test_that_emails_are_sent(self): # Login and flag exploration. self.login(self.NEW_USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/%s' % (feconf.FLAG_EXPLORATION_URL_PREFIX, self.EXP_ID), { @@ -1066,7 +1066,7 @@ def test_non_logged_in_users_cannot_report(self): """Check that non-logged in users cannot report.""" self.login(self.NEW_USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.logout() # Create report for exploration. @@ -1151,7 +1151,7 @@ def test_independent_exp_complete_event_handler(self): """ self.login(self.USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() payload = { 'client_time_spent_in_secs': 0, @@ -1188,7 +1188,7 @@ def test_exp_complete_event_in_collection(self): """ self.login(self.USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() payload = { 'client_time_spent_in_secs': 0, @@ -1232,7 +1232,7 @@ def test_exp_incomplete_event_handler(self): """Test handler for leaving an exploration incomplete.""" self.login(self.USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() payload = { 'client_time_spent_in_secs': 0, @@ -1426,7 +1426,7 @@ def setUp(self): }] } - self.csrf_token = self.get_csrf_token() + self.csrf_token = self.get_new_csrf_token() def test_new_playthrough_gets_stored(self): """Test that a new playthrough gets created and is added to an existing diff --git a/core/controllers/resources_test.py b/core/controllers/resources_test.py index 7619698a72a5..d636982dc20b 100644 --- a/core/controllers/resources_test.py +++ b/core/controllers/resources_test.py @@ -51,7 +51,7 @@ def setUp(self): def test_image_upload_with_no_filename_raises_error(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -68,7 +68,7 @@ def test_image_upload_with_no_filename_raises_error(self): def test_image_upload_with_invalid_filename_raises_error(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -86,7 +86,7 @@ def test_image_upload_with_invalid_filename_raises_error(self): def test_cannot_upload_duplicate_image(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -119,7 +119,7 @@ def test_image_upload_and_download(self): """Test image uploading and downloading.""" self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -140,7 +140,7 @@ def test_image_upload_and_download(self): def test_non_matching_extensions_are_detected(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() filename_without_extension = 'test' supplied_filename = ('%s.jpg' % filename_without_extension) @@ -178,7 +178,7 @@ def test_upload_empty_image(self): """Test upload of an empty image.""" self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Upload an empty image. response_dict = self.post_json( @@ -197,7 +197,7 @@ def test_upload_bad_image(self): """Test upload of a malformed image.""" self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Upload an invalid image. response_dict = self.post_json( @@ -223,7 +223,7 @@ def test_bad_filenames_are_detected(self): # TODO(sll): Add more tests here. self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -242,7 +242,7 @@ def test_bad_filenames_are_detected(self): def test_missing_extensions_are_detected(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: raw_image = f.read() @@ -261,7 +261,7 @@ def test_missing_extensions_are_detected(self): def test_bad_extensions_are_detected(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), mode='rb') as f: @@ -326,7 +326,7 @@ def setUp(self): mock_accepted_audio_extensions) def test_guest_can_not_upload(self): - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: @@ -344,7 +344,7 @@ def test_guest_can_not_upload(self): def test_cannot_upload_audio_with_invalid_exp_id(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: @@ -360,7 +360,7 @@ def test_cannot_upload_audio_with_invalid_exp_id(self): def test_audio_upload(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), mode='rb') as f: @@ -375,7 +375,7 @@ def test_audio_upload(self): def test_audio_upload_with_non_mp3_file(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() file_system_class = fs_services.get_exploration_file_system_class() fs = fs_domain.AbstractFileSystem(file_system_class( @@ -402,7 +402,7 @@ def test_audio_upload_with_non_mp3_file(self): def test_detect_non_matching_extensions(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Use an accepted audio extension in mismatched_filename # that differs from the uploaded file's audio type. @@ -433,7 +433,7 @@ def test_detect_non_audio_file(self): """ self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), @@ -454,7 +454,7 @@ def test_detect_non_audio_file(self): def test_audio_upload_mpeg_container(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join( feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MPEG_CONTAINER), @@ -472,7 +472,7 @@ def test_invalid_extension_is_detected(self): """Test that invalid extensions are caught.""" self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() filename_without_extension = 'test' invalid_extension = 'wav' @@ -501,7 +501,7 @@ def test_upload_empty_audio(self): """Test upload of empty audio.""" self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Upload empty audio. response_dict = self.post_json( '%s/0' % self.AUDIO_UPLOAD_URL_PREFIX, @@ -518,7 +518,7 @@ def test_upload_bad_audio(self): """Test upload of malformed audio.""" self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response_dict = self.post_json( '%s/0' % self.AUDIO_UPLOAD_URL_PREFIX, {'filename': 'test.mp3'}, @@ -536,7 +536,7 @@ def test_missing_extensions_are_detected(self): """Test upload of filenames with no extensions are caught.""" self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() missing_extension_filename = 'test' with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_MP3), @@ -561,7 +561,7 @@ def test_exceed_max_length_detected(self): """Test that audio file is less than max playback length.""" self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with open(os.path.join(feconf.TESTS_DATA_DIR, self.TEST_AUDIO_FILE_OVER_MAX_LENGTH), @@ -586,7 +586,7 @@ def test_non_matching_extensions_are_detected(self): """ self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Use an accepted audio extension in mismatched_filename # that differs from the uploaded file's audio type. diff --git a/core/controllers/skill_editor_test.py b/core/controllers/skill_editor_test.py index fac2a22af4fb..feb22624f49f 100644 --- a/core/controllers/skill_editor_test.py +++ b/core/controllers/skill_editor_test.py @@ -185,7 +185,7 @@ def test_editable_skill_handler_get_fails(self): def test_editable_skill_handler_put_succeeds(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Check that admins can edit a skill. json_response = self.put_json( self.url, self.put_payload, csrf_token=csrf_token) @@ -196,7 +196,7 @@ def test_editable_skill_handler_put_succeeds(self): def test_editable_skill_handler_put_fails(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Check PUT returns 400 when an exception is raised updating the # skill. update_skill_swap = self.swap( @@ -239,14 +239,14 @@ def setUp(self): def test_skill_publish_handler_succeeds(self): self.login(self.ADMIN_EMAIL) # Check that an admin can publish a skill. - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json(self.url, {'version': 1}, csrf_token=csrf_token) self.logout() def test_skill_publish_handler_fails(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Check that a skill cannot be published when the payload has no # version. self.put_json( @@ -268,7 +268,7 @@ def test_skill_publish_handler_fails(self): skill_services, 'publish_skill', self._mock_publish_skill_raise_exception) with skill_services_swap: - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json( self.url, {'version': 1}, csrf_token=csrf_token, expected_status_int=401) diff --git a/core/controllers/story_editor_test.py b/core/controllers/story_editor_test.py index 2c2f2178caeb..aae34614f787 100644 --- a/core/controllers/story_editor_test.py +++ b/core/controllers/story_editor_test.py @@ -107,7 +107,7 @@ def test_editable_story_handler_put(self): }] } self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() json_response = self.put_json( '%s/%s/%s' % ( diff --git a/core/controllers/subscriptions_test.py b/core/controllers/subscriptions_test.py index 996aa3be1134..63fe65846702 100644 --- a/core/controllers/subscriptions_test.py +++ b/core/controllers/subscriptions_test.py @@ -44,7 +44,7 @@ def test_subscribe_handler(self): """Test handler for new subscriptions to creators.""" self.login(self.USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() payload = { 'creator_username': self.EDITOR_USERNAME @@ -76,7 +76,7 @@ def test_subscribe_handler(self): # Test another user subscription. self.login(self.USER2_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SUBSCRIBE_URL_PREFIX, payload, @@ -97,7 +97,7 @@ def test_unsubscribe_handler(self): # Add one subscription to editor. self.login(self.USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SUBSCRIBE_URL_PREFIX, payload, csrf_token=csrf_token) @@ -105,7 +105,7 @@ def test_unsubscribe_handler(self): # Add another subscription. self.login(self.USER2_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SUBSCRIBE_URL_PREFIX, payload, csrf_token=csrf_token) @@ -136,7 +136,7 @@ def test_unsubscribe_handler(self): # Unsubscribing another user. self.login(self.USER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.UNSUBSCRIBE_URL_PREFIX, payload, csrf_token=csrf_token) diff --git a/core/controllers/suggestion_test.py b/core/controllers/suggestion_test.py index c84435536584..634675709369 100644 --- a/core/controllers/suggestion_test.py +++ b/core/controllers/suggestion_test.py @@ -91,7 +91,7 @@ def setUp(self): self.logout() self.login(self.AUTHOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -115,7 +115,7 @@ def setUp(self): self.logout() self.login(self.AUTHOR_EMAIL_2) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -160,7 +160,7 @@ def setUp(self): def test_create_suggestion(self): self.login(self.AUTHOR_EMAIL_2) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() exploration = exp_services.get_exploration_by_id(self.EXP_ID) self.post_json( @@ -190,14 +190,14 @@ def test_create_suggestion(self): def test_suggestion_to_exploration_handler_with_invalid_suggestion_id(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Invalid format of suggestion id. response = self.put_json( @@ -213,7 +213,7 @@ def test_suggestion_to_exploration_handler_with_invalid_suggestion_id(self): 'Invalid format for suggestion_id. It must contain 3 parts ' 'separated by \'.\'') - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Suggestion does not exist. self.put_json( @@ -257,7 +257,7 @@ def test_suggestion_to_exploration_handler_with_invalid_target_type(self): [('author_id', self.author_id), ( 'target_id', exp_id)])[0].suggestion_id - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.put_json( '%s/exploration/%s/%s' % ( @@ -276,7 +276,7 @@ def test_suggestion_to_exploration_handler_with_invalid_target_type(self): def test_suggestion_to_exploration_handler_with_invalid_target_id(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( @@ -285,7 +285,7 @@ def test_suggestion_to_exploration_handler_with_invalid_target_id(self): self.save_new_default_exploration('exp_id', self.editor_id) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.put_json( '%s/exploration/%s/%s' % ( @@ -325,7 +325,7 @@ def test_owner_of_exploration_cannot_repond_to_own_suggestion(self): [('author_id', self.editor_id), ( 'target_id', exp_id)])[0].suggestion_id - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.put_json( '%s/exploration/%s/%s' % ( @@ -343,14 +343,14 @@ def test_owner_of_exploration_cannot_repond_to_own_suggestion(self): def test_suggestion_to_exploration_handler_with_invalid_action(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.put_json( '%s/exploration/%s/%s' % ( @@ -368,7 +368,7 @@ def test_suggestion_to_exploration_handler_with_invalid_action(self): def test_reject_suggestion_to_exploration(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() suggestion_to_reject = self.get_json( '%s?author_id=%s' % ( @@ -381,7 +381,7 @@ def test_reject_suggestion_to_exploration(self): self.assertEqual( suggestion.status, suggestion_models.STATUS_IN_REVIEW) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, @@ -404,14 +404,14 @@ def test_accept_suggestion(self): # Test editor can accept successfully. self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -441,7 +441,7 @@ def test_accept_suggestion(self): feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id_2))['suggestions'][0] - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -459,7 +459,7 @@ def test_accept_suggestion(self): feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id_2))['suggestions'][0] - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -474,7 +474,7 @@ def test_accept_suggestion(self): suggestion_services.increment_score_for_user( self.author_id, 'content.Algebra', 15) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json('%s/exploration/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion_to_accept['target_id'], @@ -495,7 +495,7 @@ def test_accept_suggestion(self): # Testing admins can accept suggestions. self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, @@ -536,7 +536,7 @@ def test_suggestion_list_handler(self): def test_cannot_resubmit_suggestion_with_invalid_suggestion_id(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.put_json( '%s/resubmit/%s' % ( @@ -551,7 +551,7 @@ def test_cannot_resubmit_suggestion_with_invalid_suggestion_id(self): def test_resubmit_rejected_suggestion(self): self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() suggestion = suggestion_services.query_suggestions( [('author_id', self.author_id), ('target_id', self.EXP_ID)])[0] @@ -560,7 +560,7 @@ def test_resubmit_rejected_suggestion(self): self.logout() self.login(self.AUTHOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json('%s/resubmit/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, suggestion.suggestion_id), { @@ -620,7 +620,7 @@ def setUp(self): 'linked_skill_ids': [self.SKILL_ID] } self.login(self.AUTHOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -666,7 +666,7 @@ def test_accept_question_suggestion(self): )['suggestions'][0] self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): self.put_json('%s/topic/%s/%s' % ( feconf.SUGGESTION_ACTION_URL_PREFIX, @@ -732,7 +732,7 @@ def setUp(self): } self.login(self.AUTHOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/' % feconf.SUGGESTION_URL_PREFIX, { @@ -760,7 +760,7 @@ def test_cannot_access_suggestion_to_topic_handler(self): suggestion_models.TARGET_TYPE_QUESTION, self.topic_id, self.author_id, 'description', '', has_suggestion=True) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', False): self.put_json( @@ -796,7 +796,7 @@ def test_suggestion_to_topic_handler_with_invalid_target_type(self): [('author_id', self.author_id), ( 'target_id', exp_id)])[0].suggestion_id - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): response = self.put_json( @@ -816,7 +816,7 @@ def test_suggestion_to_topic_handler_with_invalid_target_type(self): def test_suggestion_to_topic_handler_with_invalid_target_id(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( @@ -827,7 +827,7 @@ def test_suggestion_to_topic_handler_with_invalid_target_id(self): 'topic_id', self.admin_id, 'Name1', 'Description', [], [], [], [], 1) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): response = self.put_json( @@ -850,14 +850,14 @@ def test_suggestion_to_topic_handler_with_invalid_target_id(self): def test_suggestion_to_topic_handler_with_invalid_action(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( feconf.SUGGESTION_LIST_URL_PREFIX, self.author_id))['suggestions'][0] - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): response = self.put_json( @@ -876,7 +876,7 @@ def test_suggestion_to_topic_handler_with_invalid_action(self): def test_reject_suggestion_to_topic(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() suggestion_to_reject = self.get_json( '%s?author_id=%s' % ( @@ -889,7 +889,7 @@ def test_reject_suggestion_to_topic(self): self.assertEqual( suggestion.status, suggestion_models.STATUS_IN_REVIEW) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): self.put_json('%s/topic/%s/%s' % ( @@ -911,7 +911,7 @@ def test_reject_suggestion_to_topic(self): def test_accept_suggestion_to_topic(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() suggestion_to_accept = self.get_json( '%s?author_id=%s' % ( @@ -924,7 +924,7 @@ def test_accept_suggestion_to_topic(self): self.assertEqual( suggestion.status, suggestion_models.STATUS_IN_REVIEW) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with self.swap(constants, 'ENABLE_NEW_STRUCTURE_PLAYERS', True): self.put_json('%s/topic/%s/%s' % ( diff --git a/core/controllers/topic_editor_test.py b/core/controllers/topic_editor_test.py index bd58b9b76bc1..6ce72cfa9446 100644 --- a/core/controllers/topic_editor_test.py +++ b/core/controllers/topic_editor_test.py @@ -66,7 +66,7 @@ class TopicEditorStoryHandlerTests(BaseTopicEditorControllerTests): def test_story_creation(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() json_response = self.post_json( '%s/%s' % (feconf.TOPIC_EDITOR_STORY_URL, self.topic_id), {'title': 'Story title'}, @@ -336,7 +336,7 @@ def test_editable_topic_handler_put(self): }] } self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() json_response = self.put_json( '%s/%s' % ( @@ -474,7 +474,7 @@ def test_editable_topic_handler_put_for_assigned_topic_manager(self): self.topic_id) self.login(self.TOPIC_MANAGER_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Check that the topic manager can edit the topic now. json_response = self.put_json( '%s/%s' % ( @@ -517,7 +517,7 @@ class TopicManagerRightsHandlerTests(BaseTopicEditorControllerTests): def test_assign_topic_manager_role(self): """Test the assign topic manager role for a topic functionality.""" self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Test for when assignee does not have sufficient rights to become a # manager for a topic. @@ -548,7 +548,7 @@ class TopicPublishSendMailHandlerTests(BaseTopicEditorControllerTests): def test_send_mail(self): self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with self.swap(feconf, 'CAN_SEND_EMAILS', True): self.put_json( '%s/%s' % ( @@ -593,7 +593,7 @@ class TopicPublishHandlerTests(BaseTopicEditorControllerTests): def test_publish_and_unpublish_topic(self): """Test the publish and unpublish functionality.""" self.login(self.ADMIN_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # Test whether admin can publish and unpublish a topic. self.put_json( '%s/%s' % ( diff --git a/core/controllers/topics_and_skills_dashboard_test.py b/core/controllers/topics_and_skills_dashboard_test.py index 3e3313153634..c6f58b690247 100644 --- a/core/controllers/topics_and_skills_dashboard_test.py +++ b/core/controllers/topics_and_skills_dashboard_test.py @@ -46,11 +46,6 @@ def setUp(self): self.topic_id, self.admin_id, 'Name', 'Description', [], [], [self.linked_skill_id], [], 1) - def _get_csrf_token_for_put(self): - """Gets the csrf token.""" - csrf_token = self.get_csrf_token() - return csrf_token - class TopicsAndSkillsDashboardPageDataHandlerTests( BaseTopicsAndSkillsDashboardTests): @@ -149,7 +144,7 @@ def setUp(self): def test_topic_creation(self): self.login(self.ADMIN_EMAIL) - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.get_new_csrf_token() json_response = self.post_json( self.url, {'name': 'Topic name'}, csrf_token=csrf_token) @@ -168,7 +163,7 @@ def setUp(self): def test_skill_creation(self): self.login(self.ADMIN_EMAIL) - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.get_new_csrf_token() json_response = self.post_json( self.url, {'description': 'Skill Description'}, @@ -181,7 +176,7 @@ def test_skill_creation(self): def test_skill_creation_in_invalid_topic(self): self.login(self.ADMIN_EMAIL) - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.get_new_csrf_token() payload = { 'description': 'Skill Description', 'linked_topic_ids': ['topic'] @@ -194,7 +189,7 @@ def test_skill_creation_in_invalid_topic(self): def test_skill_creation_in_valid_topic(self): self.login(self.ADMIN_EMAIL) - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.get_new_csrf_token() payload = { 'description': 'Skill Description', 'linked_topic_ids': [self.topic_id] @@ -240,7 +235,7 @@ def test_merge_skill(self): self.assertEqual(old_links[0].skill_id, old_skill_id) self.assertEqual(len(new_links), 0) - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.get_new_csrf_token() payload = { 'old_skill_id': old_skill_id, 'new_skill_id': new_skill_id @@ -267,7 +262,7 @@ def test_merge_skill_fails_when_new_skill_id_is_invalid(self): 'old_skill_id': old_skill_id, 'new_skill_id': 'invalid_new_skill_id' } - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.get_new_csrf_token() self.post_json( self.url, payload, csrf_token=csrf_token, expected_status_int=404) @@ -282,7 +277,7 @@ def test_merge_skill_fails_when_old_skill_id_is_invalid(self): 'old_skill_id': 'invalid_old_skill_id', 'new_skill_id': new_skill_id } - csrf_token = self._get_csrf_token_for_put() + csrf_token = self.get_new_csrf_token() self.post_json( self.url, payload, csrf_token=csrf_token, expected_status_int=404) diff --git a/core/controllers/voice_artist_test.py b/core/controllers/voice_artist_test.py index 46835b1aad67..2b02d38a9830 100644 --- a/core/controllers/voice_artist_test.py +++ b/core/controllers/voice_artist_test.py @@ -70,7 +70,7 @@ def setUp(self): self.login(self.VOICE_ARTIST_EMAIL) # Generate CSRF token. - self.csrf_token = self.get_csrf_token() + self.csrf_token = self.get_new_csrf_token() def test_put_with_no_payload_version_raises_error(self): with self.assertRaisesRegexp( @@ -196,7 +196,7 @@ def setUp(self): draft_change_list_id=1).put() # Generate CSRF token. - self.csrf_token = self.get_csrf_token() + self.csrf_token = self.get_new_csrf_token() def test_draft_updated_version_valid(self): payload = { @@ -275,7 +275,7 @@ def setUp(self): self.login(self.VOICE_ARTIST_EMAIL) # Generate CSRF token. - self.csrf_token = self.get_csrf_token() + self.csrf_token = self.get_new_csrf_token() def test_firsttime_translation_tutorial(self): """Testing of the firsttime translation tutorial http requests.""" diff --git a/core/domain/email_manager_test.py b/core/domain/email_manager_test.py index 2e736492bc9a..d19f89de1c05 100644 --- a/core/domain/email_manager_test.py +++ b/core/domain/email_manager_test.py @@ -202,7 +202,7 @@ def test_role_email_is_sent_when_editor_assigns_role(self): with self.can_send_emails_ctx, self.can_send_editor_role_email_ctx: self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.put_json('%s/%s' % ( feconf.EXPLORATION_RIGHTS_PREFIX, self.exploration.id), { 'version': self.exploration.version, @@ -569,7 +569,7 @@ def test_email_not_sent_if_config_does_not_permit_it(self): self.new_email_content) self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, { @@ -599,7 +599,7 @@ def _log_error_for_tests(error_message): self.assertEqual(log_new_error_counter.times_called, 0) self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # No user-facing error should surface. self.post_json( @@ -646,7 +646,7 @@ def _log_error_for_tests(error_message): self.assertEqual(log_new_error_counter.times_called, 0) self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # No user-facing error should surface. self.post_json( @@ -691,7 +691,7 @@ def _log_error_for_tests(error_message): self.assertEqual(log_new_error_counter.times_called, 0) self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() # No user-facing error should surface. self.post_json( @@ -722,7 +722,7 @@ def test_contents_of_signup_email_are_correct(self): 'Email Sender') self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, { @@ -754,7 +754,7 @@ def test_email_only_sent_once_for_repeated_signups_by_same_user(self): self.new_email_content) self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, { @@ -787,7 +787,7 @@ def test_email_only_sent_if_signup_was_successful(self): self.new_email_content) self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, @@ -828,7 +828,7 @@ def test_record_of_sent_email_is_written_to_datastore(self): self.assertEqual(len(all_models), 0) self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( feconf.SIGNUP_DATA_URL, { diff --git a/core/domain/feedback_services_test.py b/core/domain/feedback_services_test.py index 7e11eaa0cd6e..2911e15bd1d5 100644 --- a/core/domain/feedback_services_test.py +++ b/core/domain/feedback_services_test.py @@ -946,7 +946,7 @@ def test_that_emails_are_not_sent_if_already_seen(self): thread_id = threadlist[0].id self.login(self.EDITOR_EMAIL) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '%s/%s' % ( feconf.FEEDBACK_THREAD_VIEW_EVENT_URL, thread_id), diff --git a/core/domain/summary_services_test.py b/core/domain/summary_services_test.py index a0730cdb620c..4791f7917d94 100644 --- a/core/domain/summary_services_test.py +++ b/core/domain/summary_services_test.py @@ -258,7 +258,7 @@ def setUp(self): super(LibraryGroupsTest, self).setUp() self.login(self.ADMIN_EMAIL, is_super_admin=True) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() with self.swap( html_validation_service, 'get_filename_with_dimensions', diff --git a/core/templates/dev/head/App.ts b/core/templates/dev/head/App.ts index e4ce0c21db68..af798ded36bc 100644 --- a/core/templates/dev/head/App.ts +++ b/core/templates/dev/head/App.ts @@ -22,7 +22,7 @@ require('pages/Base.ts'); require('services/AlertsService.ts'); require('services/ContextService.ts'); -require('services/CsrfService.ts'); +require('services/CsrfTokenService.ts'); require('services/NavigationService.ts'); require('services/UtilsService.ts'); require('services/DebouncerService.ts'); @@ -104,13 +104,13 @@ oppia.config([ // Add an interceptor to convert requests to strings and to log and show // warnings for error responses. $httpProvider.interceptors.push([ - '$q', '$log', 'AlertsService', 'CsrfService', - function($q, $log, AlertsService, CsrfService) { + '$q', '$log', 'AlertsService', 'CsrfTokenService', + function($q, $log, AlertsService, CsrfTokenService) { return { request: function(config) { if (config.data) { config.data = $.param({ - csrf_token: CsrfService.getToken(), + csrf_token: CsrfTokenService.getToken(), payload: JSON.stringify(config.data), source: document.URL }, true); @@ -183,8 +183,8 @@ oppia.config(['toastrConfig', function(toastrConfig) { // Overwrite the built-in exceptionHandler service to log errors to the backend // (so that they can be fixed). -oppia.factory('$exceptionHandler', ['$log', 'CsrfService', - function($log, CsrfService) { +oppia.factory('$exceptionHandler', ['$log', 'CsrfTokenService', + function($log, CsrfTokenService) { var MIN_TIME_BETWEEN_ERRORS_MSEC = 5000; var timeOfLastPostedError = Date.now() - MIN_TIME_BETWEEN_ERRORS_MSEC; @@ -208,7 +208,7 @@ oppia.factory('$exceptionHandler', ['$log', 'CsrfService', type: 'POST', url: '/frontend_errors', data: $.param({ - csrf_token: CsrfService.getToken(), + csrf_token: CsrfTokenService.getToken(), payload: JSON.stringify({ error: messageAndSourceAndStackTrace }), diff --git a/core/templates/dev/head/components/entity-creation-services/exploration-creation.service.ts b/core/templates/dev/head/components/entity-creation-services/exploration-creation.service.ts index 6968dc384186..993bd2b453ed 100644 --- a/core/templates/dev/head/components/entity-creation-services/exploration-creation.service.ts +++ b/core/templates/dev/head/components/entity-creation-services/exploration-creation.service.ts @@ -19,16 +19,16 @@ require('domain/utilities/UrlInterpolationService.ts'); require('services/AlertsService.ts'); -require('services/CsrfService.ts'); +require('services/CsrfTokenService.ts'); require('services/SiteAnalyticsService.ts'); oppia.factory('ExplorationCreationService', [ '$http', '$rootScope', '$timeout', '$uibModal', '$window', - 'AlertsService', 'CsrfService', 'SiteAnalyticsService', + 'AlertsService', 'CsrfTokenService', 'SiteAnalyticsService', 'UrlInterpolationService', function( $http, $rootScope, $timeout, $uibModal, $window, - AlertsService, CsrfService, SiteAnalyticsService, + AlertsService, CsrfTokenService, SiteAnalyticsService, UrlInterpolationService) { var CREATE_NEW_EXPLORATION_URL_TEMPLATE = '/create/'; @@ -101,7 +101,7 @@ oppia.factory('ExplorationCreationService', [ var form = new FormData(); form.append('yaml_file', yamlFile); form.append('payload', JSON.stringify({})); - form.append('csrf_token', CsrfService.getToken()); + form.append('csrf_token', CsrfTokenService.getToken()); $.ajax({ contentType: false, diff --git a/core/templates/dev/head/pages/Base.ts b/core/templates/dev/head/pages/Base.ts index 05f5d3c762f0..ff58156ab9f9 100644 --- a/core/templates/dev/head/pages/Base.ts +++ b/core/templates/dev/head/pages/Base.ts @@ -15,7 +15,7 @@ require('domain/sidebar/SidebarStatusService.ts'); require('domain/utilities/UrlInterpolationService.ts'); require('services/AlertsService.ts'); -require('services/CsrfService.ts'); +require('services/CsrfTokenService.ts'); require('services/contextual/UrlService.ts'); require('services/stateful/BackgroundMaskService.ts'); @@ -26,12 +26,12 @@ require('app.constants.ts'); */ oppia.controller('Base', [ - '$document', '$rootScope', '$http', '$scope', 'AlertsService', - 'BackgroundMaskService', 'CsrfService', 'SidebarStatusService', + '$document', '$http', '$rootScope', '$scope', 'AlertsService', + 'BackgroundMaskService', 'CsrfTokenService', 'SidebarStatusService', 'UrlInterpolationService', 'UrlService', 'DEV_MODE', 'SITE_FEEDBACK_FORM_URL', 'SITE_NAME', - function($document, $rootScope, $http, $scope, AlertsService, - BackgroundMaskService, CsrfService, SidebarStatusService, + function($document, $http, $rootScope, $scope, AlertsService, + BackgroundMaskService, CsrfTokenService, SidebarStatusService, UrlInterpolationService, UrlService, DEV_MODE, SITE_FEEDBACK_FORM_URL, SITE_NAME) { $scope.siteName = SITE_NAME; @@ -59,8 +59,10 @@ oppia.controller('Base', [ }); if (UrlService.getPathname() !== '/signup') { - $http.get('/csrf').then(function(response) { - CsrfService.setToken(response.data.token); + // This is done outside the service to prevent + // circular dependency issues. + $http.get('/csrfhandler').then(function(response) { + CsrfTokenService.setToken(response.data.token); }); } // TODO(sll): use 'touchstart' for mobile. diff --git a/core/templates/dev/head/pages/admin-page/admin-page.directive.ts b/core/templates/dev/head/pages/admin-page/admin-page.directive.ts index bf93dd341f92..eefa1cfa7012 100644 --- a/core/templates/dev/head/pages/admin-page/admin-page.directive.ts +++ b/core/templates/dev/head/pages/admin-page/admin-page.directive.ts @@ -77,7 +77,7 @@ require('value_generators/valueGeneratorsRequires.ts'); require('domain/objects/NumberWithUnitsObjectFactory.ts'); require('domain/utilities/UrlInterpolationService.ts'); require('pages/admin-page/services/admin-router.service.ts'); -require('services/CsrfService.ts'); +require('services/CsrfTokenService.ts'); require('services/UtilsService.ts'); oppia.directive('adminPage', ['UrlInterpolationService', @@ -90,10 +90,10 @@ oppia.directive('adminPage', ['UrlInterpolationService', '/pages/admin-page/admin-page.directive.html'), controllerAs: '$ctrl', controller: [ - '$http', '$location', '$scope', 'AdminRouterService', 'CsrfService', - 'DEV_MODE', - function($http, $location, $scope, AdminRouterService, CsrfService, - DEV_MODE) { + '$http', '$location', '$scope', 'AdminRouterService', + 'CsrfTokenService', 'DEV_MODE', + function($http, $location, $scope, AdminRouterService, + CsrfTokenService, DEV_MODE) { var ctrl = this; ctrl.userEmail = GLOBALS.USER_EMAIL; ctrl.inDevMode = DEV_MODE; @@ -105,8 +105,10 @@ oppia.directive('adminPage', ['UrlInterpolationService', ctrl.isRolesTabOpen = AdminRouterService.isRolesTabOpen; ctrl.isMiscTabOpen = AdminRouterService.isMiscTabOpen; - $http.get('/csrf').then(function(response) { - CsrfService.setToken(response.data.token); + $http.get('/csrfhandler').then(function(response) { + // This is done outside the service to prevent + // circular dependency issues. + CsrfTokenService.setToken(response.data.token); }); ctrl.setStatusMessage = function(statusMessage) { diff --git a/core/templates/dev/head/pages/base.html b/core/templates/dev/head/pages/base.html index 23619bb43980..84aae6be3dba 100755 --- a/core/templates/dev/head/pages/base.html +++ b/core/templates/dev/head/pages/base.html @@ -80,7 +80,6 @@ var GLOBALS = { ADDITIONAL_ANGULAR_MODULES: JSON.parse( '{{additional_angular_modules|js_string}}'), - csrf_token: JSON.parse('{{csrf_token|js_string}}'), status_code: JSON.parse('{{status_code}}'), GCS_RESOURCE_BUCKET_NAME: JSON.parse('{{GCS_RESOURCE_BUCKET_NAME|js_string}}'), }; diff --git a/core/templates/dev/head/pages/signup-page/signup-page.controller.ts b/core/templates/dev/head/pages/signup-page/signup-page.controller.ts index 34641d473913..0850e6f22e92 100644 --- a/core/templates/dev/head/pages/signup-page/signup-page.controller.ts +++ b/core/templates/dev/head/pages/signup-page/signup-page.controller.ts @@ -18,7 +18,7 @@ require('domain/utilities/UrlInterpolationService.ts'); require('services/AlertsService.ts'); -require('services/CsrfService.ts'); +require('services/CsrfTokenService.ts'); require('services/IdGenerationService.ts'); require('services/SiteAnalyticsService.ts'); require('services/UserService.ts'); @@ -27,12 +27,12 @@ require('services/stateful/FocusManagerService.ts'); oppia.controller('Signup', [ '$http', '$rootScope', '$scope', '$uibModal', 'AlertsService', - 'CsrfService', 'FocusManagerService', 'SiteAnalyticsService', + 'CsrfTokenService', 'FocusManagerService', 'SiteAnalyticsService', 'UrlInterpolationService', 'UrlService', 'SITE_NAME', function( $http, $rootScope, $scope, $uibModal, AlertsService, - CsrfService, FocusManagerService, SiteAnalyticsService, + CsrfTokenService, FocusManagerService, SiteAnalyticsService, UrlInterpolationService, UrlService, SITE_NAME) { var _SIGNUP_DATA_URL = '/signuphandler/data'; @@ -50,7 +50,7 @@ oppia.controller('Signup', [ $scope.showEmailPreferencesForm = data.can_send_emails; $scope.hasUsername = Boolean($scope.username); FocusManagerService.setFocus('usernameInputField'); - CsrfService.setToken(data.csrf_token); + CsrfTokenService.setToken(data.csrf_token); }); $scope.blurredAtLeastOnce = false; diff --git a/core/templates/dev/head/services/AssetsBackendApiService.ts b/core/templates/dev/head/services/AssetsBackendApiService.ts index e7eed275a517..2f5eb74e9794 100644 --- a/core/templates/dev/head/services/AssetsBackendApiService.ts +++ b/core/templates/dev/head/services/AssetsBackendApiService.ts @@ -21,14 +21,14 @@ require('domain/utilities/AudioFileObjectFactory.ts'); require('domain/utilities/FileDownloadRequestObjectFactory.ts'); require('domain/utilities/ImageFileObjectFactory.ts'); require('domain/utilities/UrlInterpolationService.ts'); -require('services/CsrfService.ts'); +require('services/CsrfTokenService.ts'); oppia.factory('AssetsBackendApiService', [ - '$http', '$q', 'AudioFileObjectFactory', 'CsrfService', + '$http', '$q', 'AudioFileObjectFactory', 'CsrfTokenService', 'FileDownloadRequestObjectFactory', 'ImageFileObjectFactory', 'UrlInterpolationService', 'DEV_MODE', function( - $http, $q, AudioFileObjectFactory, CsrfService, + $http, $q, AudioFileObjectFactory, CsrfTokenService, FileDownloadRequestObjectFactory, ImageFileObjectFactory, UrlInterpolationService, DEV_MODE) { if (!DEV_MODE && !GLOBALS.GCS_RESOURCE_BUCKET_NAME) { @@ -155,7 +155,7 @@ oppia.factory('AssetsBackendApiService', [ form.append('payload', JSON.stringify({ filename: filename })); - form.append('csrf_token', CsrfService.getToken()); + form.append('csrf_token', CsrfTokenService.getToken()); $.ajax({ url: _getAudioUploadUrl(explorationId), diff --git a/core/templates/dev/head/services/CsrfService.ts b/core/templates/dev/head/services/CsrfTokenService.ts similarity index 85% rename from core/templates/dev/head/services/CsrfService.ts rename to core/templates/dev/head/services/CsrfTokenService.ts index 82de898dc48c..6a92514ba2bb 100644 --- a/core/templates/dev/head/services/CsrfService.ts +++ b/core/templates/dev/head/services/CsrfTokenService.ts @@ -16,14 +16,12 @@ * @fileoverview Service for managing csrf tokens */ -oppia.factory('CsrfService', [function() { +oppia.factory('CsrfTokenService', [function() { var token = null; - var setToken = function(csrfToken) { - token = csrfToken; - }; - return { - setToken: setToken, + setToken: function (csrfToken) { + token = csrfToken; + }, getToken: function() { return token; } diff --git a/core/templates/dev/head/services/CsrfServiceSpec.ts b/core/templates/dev/head/services/CsrfTokenServiceSpec.ts similarity index 75% rename from core/templates/dev/head/services/CsrfServiceSpec.ts rename to core/templates/dev/head/services/CsrfTokenServiceSpec.ts index 436576527f33..9a38ea6bea34 100644 --- a/core/templates/dev/head/services/CsrfServiceSpec.ts +++ b/core/templates/dev/head/services/CsrfTokenServiceSpec.ts @@ -16,20 +16,20 @@ * @fileoverview Unit tests for the csrf service */ -require('services/CsrfService.ts'); +require('services/CsrfTokenService.ts'); -describe('Csrf Service', function() { - var CsrfService, $httpBackend; +describe('Csrf Token Service', function() { + var CsrfTokenService, $httpBackend; beforeEach(angular.mock.module('oppia')); beforeEach(angular.mock.inject(function($injector) { - CsrfService = $injector.get('CsrfService'); + CsrfTokenService = $injector.get('CsrfTokenService'); $httpBackend = $injector.get('$httpBackend'); })); it('should correctly set the csrf token', function() { - CsrfService.setToken('sample csrf token'); + CsrfTokenService.setToken('sample csrf token'); - expect(CsrfService.getToken()).toBe('sample csrf token'); + expect(CsrfTokenService.getToken()).toBe('sample csrf token'); }); }); diff --git a/core/tests/test_utils.py b/core/tests/test_utils.py index a0a2405c824c..df6b6167a633 100644 --- a/core/tests/test_utils.py +++ b/core/tests/test_utils.py @@ -25,7 +25,6 @@ import unittest from constants import constants -from core.controllers import base from core.domain import collection_domain from core.domain import collection_services from core.domain import exp_domain @@ -822,14 +821,10 @@ def put_json(self, url, payload, csrf_token=None, expected_status_int=200): self.assertEqual(json_response.status_int, expected_status_int) return self._parse_json_response(json_response, expect_errors) - def get_csrf_token(self): + def get_new_csrf_token(self): """Generates CSRF token for test.""" - if self.get_current_logged_in_user_id() == '': - return base.CsrfTokenManager.create_csrf_token( - ('non_logged_in_user')) - - return base.CsrfTokenManager.create_csrf_token( - self.get_current_logged_in_user_id()) + response = self.get_json('/csrfhandler') + return response['token'] def signup(self, email, username): """Complete the signup process for the user with the given username. @@ -847,7 +842,7 @@ def signup(self, email, username): with self.urlfetch_mock(): response = self.get_html_response(feconf.SIGNUP_URL) self.assertEqual(response.status_int, 200) - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() response = self.testapp.post( feconf.SIGNUP_DATA_URL, params={ 'csrf_token': csrf_token, @@ -865,7 +860,7 @@ def set_config_property(self, config_obj, new_config_value): """ with self.login_context('tmpsuperadmin@example.com', is_super_admin=True): - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/adminhandler', { 'action': 'save_config_properties', @@ -883,7 +878,7 @@ def set_user_role(self, username, user_role): """ with self.login_context('tmpsuperadmin@example.com', is_super_admin=True): - csrf_token = self.get_csrf_token() + csrf_token = self.get_new_csrf_token() self.post_json( '/adminrolehandler', { 'username': username, diff --git a/extensions/objects/templates/FilepathEditorDirective.ts b/extensions/objects/templates/FilepathEditorDirective.ts index b1c4410168ac..ad518d6f09e6 100644 --- a/extensions/objects/templates/FilepathEditorDirective.ts +++ b/extensions/objects/templates/FilepathEditorDirective.ts @@ -17,15 +17,15 @@ */ // This directive can only be used in the context of an exploration. -require('services/CsrfService.ts'); +require('services/CsrfTokenService.ts'); oppia.directive('filepathEditor', [ '$http', '$sce', 'AlertsService', 'AssetsBackendApiService', - 'ContextService', 'CsrfService', 'UrlInterpolationService', + 'ContextService', 'CsrfTokenService', 'UrlInterpolationService', 'OBJECT_EDITOR_URL_PREFIX', function( $http, $sce, AlertsService, AssetsBackendApiService, - ContextService, CsrfService, UrlInterpolationService, + ContextService, CsrfTokenService, UrlInterpolationService, OBJECT_EDITOR_URL_PREFIX) { return { restrict: 'E', @@ -637,7 +637,7 @@ oppia.directive('filepathEditor', [ filename: ctrl.generateImageFilename( dimensions.height, dimensions.width) })); - form.append('csrf_token', CsrfService.getToken()); + form.append('csrf_token', CsrfTokenService.getToken()); $.ajax({ url: '/createhandler/imageupload/' + ctrl.explorationId, diff --git a/main.py b/main.py index 834de5821435..44977e82711a 100644 --- a/main.py +++ b/main.py @@ -673,7 +673,7 @@ def ui_access_wrapper(self, *args, **kwargs): r'/resolveissuehandler/', editor.ResolveIssueHandler), get_redirect_route( - r'/csrf', base.CsrfTokenHandler), + r'/csrfhandler', base.CsrfTokenHandler), # 404 error handler. get_redirect_route(r'/<:.*>', base.Error404Handler), From ab957467bd20b7f6536a96016c97207fd82a8818 Mon Sep 17 00:00:00 2001 From: James John James Date: Sat, 22 Jun 2019 22:16:00 +0100 Subject: [PATCH 20/40] address review comment --- core/controllers/editor_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/controllers/editor_test.py b/core/controllers/editor_test.py index 5ad694573478..16692f027d16 100644 --- a/core/controllers/editor_test.py +++ b/core/controllers/editor_test.py @@ -2039,7 +2039,7 @@ def setUp(self): 'is_valid': True } - self.login(self.MODERATOR_EMAIL) + with self.login_context(self.MODERATOR_EMAIL) self.csrf_token = self.get_new_csrf_token() def test_resolve_issue_handler(self): From e42f68c643cf0b4f1f29cd6b8b9028560c5efddb Mon Sep 17 00:00:00 2001 From: James John James Date: Sun, 23 Jun 2019 13:50:19 +0100 Subject: [PATCH 21/40] address review comment and working on tests --- core/controllers/editor_test.py | 2 +- core/tests/test_utils.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/controllers/editor_test.py b/core/controllers/editor_test.py index 16692f027d16..4081d1b8a12a 100644 --- a/core/controllers/editor_test.py +++ b/core/controllers/editor_test.py @@ -2040,7 +2040,7 @@ def setUp(self): } with self.login_context(self.MODERATOR_EMAIL) - self.csrf_token = self.get_new_csrf_token() + self.csrf_token = self.get_new_csrf_token() def test_resolve_issue_handler(self): """Test that resolving an issue deletes associated playthroughs.""" diff --git a/core/tests/test_utils.py b/core/tests/test_utils.py index df6b6167a633..8014536dd6ea 100644 --- a/core/tests/test_utils.py +++ b/core/tests/test_utils.py @@ -1722,7 +1722,7 @@ def setUp(self): # Set up the app to be tested. self.testapp = webtest.TestApp(main.app) - self.signup_superadmin_user() + # self.signup_superadmin_user() def tearDown(self): self.logout() From f7c50c8800b1f607a6bae24247a71f838c665b76 Mon Sep 17 00:00:00 2001 From: James John James Date: Sun, 23 Jun 2019 15:55:38 +0100 Subject: [PATCH 22/40] address review comment --- core/controllers/editor_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/controllers/editor_test.py b/core/controllers/editor_test.py index 4081d1b8a12a..c6bf315e77b6 100644 --- a/core/controllers/editor_test.py +++ b/core/controllers/editor_test.py @@ -2039,7 +2039,7 @@ def setUp(self): 'is_valid': True } - with self.login_context(self.MODERATOR_EMAIL) + with self.login_context(self.MODERATOR_EMAIL): self.csrf_token = self.get_new_csrf_token() def test_resolve_issue_handler(self): From c102738b620b9214fcb4fc23032660ef651d5492 Mon Sep 17 00:00:00 2001 From: James John James Date: Tue, 25 Jun 2019 15:29:36 +0100 Subject: [PATCH 23/40] work on failing tests --- core/controllers/base.py | 1 + core/controllers/editor_test.py | 65 +++++++++++-------- core/controllers/profile.py | 5 -- core/controllers/profile_test.py | 34 ++++------ core/templates/dev/head/pages/Base.ts | 12 ++-- .../signup-page/signup-page.controller.ts | 1 - core/tests/test_utils.py | 2 +- feconf.py | 1 + main.py | 2 +- 9 files changed, 60 insertions(+), 63 deletions(-) diff --git a/core/controllers/base.py b/core/controllers/base.py index b80b39896e63..1c6332d493ee 100755 --- a/core/controllers/base.py +++ b/core/controllers/base.py @@ -579,6 +579,7 @@ class CsrfTokenHandler(BaseHandler): """Handles sending CSRF tokens to the frontend.""" GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON + REDIRECT_UNFINISHED_SIGNUPS = False def get(self): csrf_token = CsrfTokenManager.create_csrf_token( diff --git a/core/controllers/editor_test.py b/core/controllers/editor_test.py index c6bf315e77b6..52279fb1f70f 100644 --- a/core/controllers/editor_test.py +++ b/core/controllers/editor_test.py @@ -2039,17 +2039,17 @@ def setUp(self): 'is_valid': True } - with self.login_context(self.MODERATOR_EMAIL): - self.csrf_token = self.get_new_csrf_token() def test_resolve_issue_handler(self): """Test that resolving an issue deletes associated playthroughs.""" - self.post_json( - '/resolveissuehandler/%s' % (self.EXP_ID), - { - 'exp_issue_dict': self.exp_issue_dict, - 'exp_version': 1 - }, csrf_token=self.csrf_token) + with self.login_context(self.MODERATOR_EMAIL): + csrf_token = self.get_new_csrf_token() + self.post_json( + '/resolveissuehandler/%s' % (self.EXP_ID), + { + 'exp_issue_dict': self.exp_issue_dict, + 'exp_version': 1 + }, csrf_token=csrf_token) exp_issues = stats_services.get_exp_issues(self.EXP_ID, 1) self.assertEqual(exp_issues.unresolved_issues, []) @@ -2065,13 +2065,16 @@ def test_error_on_passing_invalid_exp_issue_dict(self): del self.exp_issue_dict['issue_type'] # Since we deleted the 'issue_type' key in the exploration issue dict, # the dict is invalid now and exception should be raised. - self.post_json( - '/resolveissuehandler/%s' % (self.EXP_ID), - { - 'exp_issue_dict': self.exp_issue_dict, - 'exp_version': 1 - }, csrf_token=self.csrf_token, - expected_status_int=404) + + with self.login_context(self.MODERATOR_EMAIL): + csrf_token = self.get_new_csrf_token() + self.post_json( + '/resolveissuehandler/%s' % (self.EXP_ID), + { + 'exp_issue_dict': self.exp_issue_dict, + 'exp_version': 1 + }, csrf_token=csrf_token, + expected_status_int=404) def test_error_on_passing_non_matching_exp_issue_dict(self): """Test that error is raised on passing an exploration issue dict that @@ -2079,21 +2082,27 @@ def test_error_on_passing_non_matching_exp_issue_dict(self): """ self.exp_issue_dict['issue_customization_args']['state_name'][ 'value'] = 'state_name2' - self.post_json( - '/resolveissuehandler/%s' % (self.EXP_ID), - { - 'exp_issue_dict': self.exp_issue_dict, - 'exp_version': 1 - }, csrf_token=self.csrf_token, - expected_status_int=404) + + with self.login_context(self.MODERATOR_EMAIL): + csrf_token = self.get_new_csrf_token() + self.post_json( + '/resolveissuehandler/%s' % (self.EXP_ID), + { + 'exp_issue_dict': self.exp_issue_dict, + 'exp_version': 1 + }, csrf_token=csrf_token, + expected_status_int=404) def test_error_on_passing_invalid_exploration_version(self): - self.post_json( - '/resolveissuehandler/%s' % (self.EXP_ID), - { - 'exp_issue_dict': self.exp_issue_dict, - 'exp_version': 2 - }, csrf_token=self.csrf_token, expected_status_int=404) + + with self.login_context(self.MODERATOR_EMAIL): + csrf_token = self.get_new_csrf_token() + self.post_json( + '/resolveissuehandler/%s' % (self.EXP_ID), + { + 'exp_issue_dict': self.exp_issue_dict, + 'exp_version': 2 + }, csrf_token=csrf_token, expected_status_int=404) class EditorAutosaveTest(BaseEditorControllerTests): diff --git a/core/controllers/profile.py b/core/controllers/profile.py index ebf19ec63c57..187a100449d3 100644 --- a/core/controllers/profile.py +++ b/core/controllers/profile.py @@ -284,11 +284,6 @@ def get(self): 'has_ever_registered': bool( user_settings.username and user_settings.last_agreed_to_terms), 'username': user_settings.username, - - # Send CSRF token here because any - # request from signup page invalidates the session. - 'csrf_token': base.CsrfTokenManager.create_csrf_token( - self.user_id), }) @acl_decorators.require_user_id_else_redirect_to_homepage diff --git a/core/controllers/profile_test.py b/core/controllers/profile_test.py index b83a4941bf62..798fae90bd3a 100644 --- a/core/controllers/profile_test.py +++ b/core/controllers/profile_test.py @@ -188,35 +188,29 @@ def test_default_dashboard_for_new_users(self): def test_user_settings_of_non_existing_user(self): self.login(self.OWNER_EMAIL) - can_send_emails = False - has_agreed_to_latest_terms = False - has_ever_registered = False - username = None + values_dict = { + 'can_send_emails': False, + 'has_agreed_to_latest_terms': False, + 'has_ever_registered': False, + 'username': None, + } response = self.get_json(feconf.SIGNUP_DATA_URL) - self.assertEqual(can_send_emails, response['can_send_emails']) - self.assertEqual( - has_agreed_to_latest_terms, response['has_agreed_to_latest_terms']) - self.assertEqual(has_ever_registered, response['has_ever_registered']) - self.assertEqual(username, response['username']) + self.assertDictEqual(values_dict, response) self.logout() def test_user_settings_of_existing_user(self): self.signup(self.OWNER_EMAIL, self.OWNER_USERNAME) self.login(self.OWNER_EMAIL) - can_send_emails = True - has_agreed_to_latest_terms = True - has_ever_registered = True - username = 'owner' + values_dict = { + 'can_send_emails': True, + 'has_agreed_to_latest_terms': True, + 'has_ever_registered': True, + 'username': 'owner', + } with self.swap(feconf, 'CAN_SEND_EMAILS', True): response = self.get_json(feconf.SIGNUP_DATA_URL) - self.assertEqual(can_send_emails, response['can_send_emails']) - self.assertEqual( - has_agreed_to_latest_terms, - response['has_agreed_to_latest_terms']) - self.assertEqual( - has_ever_registered, response['has_ever_registered']) - self.assertEqual(username, response['username']) + self.assertDictEqual(values_dict, response) self.logout() diff --git a/core/templates/dev/head/pages/Base.ts b/core/templates/dev/head/pages/Base.ts index ff58156ab9f9..ef5723ed03a8 100644 --- a/core/templates/dev/head/pages/Base.ts +++ b/core/templates/dev/head/pages/Base.ts @@ -58,13 +58,11 @@ oppia.controller('Base', [ $scope.currentLang = response.language; }); - if (UrlService.getPathname() !== '/signup') { - // This is done outside the service to prevent - // circular dependency issues. - $http.get('/csrfhandler').then(function(response) { - CsrfTokenService.setToken(response.data.token); - }); - } + // This is done outside the service to prevent + // circular dependency issues. + $http.get('/csrfhandler').then(function(response) { + CsrfTokenService.setToken(response.data.token); + }); // TODO(sll): use 'touchstart' for mobile. $document.on('click', function() { SidebarStatusService.onDocumentClick(); diff --git a/core/templates/dev/head/pages/signup-page/signup-page.controller.ts b/core/templates/dev/head/pages/signup-page/signup-page.controller.ts index 14bdfdbfcab7..8a32313c90cd 100644 --- a/core/templates/dev/head/pages/signup-page/signup-page.controller.ts +++ b/core/templates/dev/head/pages/signup-page/signup-page.controller.ts @@ -60,7 +60,6 @@ oppia.directive('signupPage', ['UrlInterpolationService', function( ctrl.showEmailPreferencesForm = data.can_send_emails; ctrl.hasUsername = Boolean(ctrl.username); FocusManagerService.setFocus('usernameInputField'); - CsrfTokenService.setToken(data.csrf_token); }); ctrl.blurredAtLeastOnce = false; diff --git a/core/tests/test_utils.py b/core/tests/test_utils.py index 8014536dd6ea..df6b6167a633 100644 --- a/core/tests/test_utils.py +++ b/core/tests/test_utils.py @@ -1722,7 +1722,7 @@ def setUp(self): # Set up the app to be tested. self.testapp = webtest.TestApp(main.app) - # self.signup_superadmin_user() + self.signup_superadmin_user() def tearDown(self): self.logout() diff --git a/feconf.py b/feconf.py index 0aeae7d76683..8aba3e01f21e 100644 --- a/feconf.py +++ b/feconf.py @@ -606,6 +606,7 @@ def get_empty_ratings(): CONCEPT_CARD_DATA_URL_PREFIX = '/concept_card_handler' CREATOR_DASHBOARD_DATA_URL = '/creatordashboardhandler/data' CREATOR_DASHBOARD_URL = '/creator_dashboard' +CSRF_HANDLER_URL = '/csrfhandler' CUSTOM_NONPROFITS_LANDING_PAGE_URL = '/nonprofits' CUSTOM_PARENTS_LANDING_PAGE_URL = '/parents' CUSTOM_PARTNERS_LANDING_PAGE_URL = '/partners' diff --git a/main.py b/main.py index 44977e82711a..883856b8fd0e 100644 --- a/main.py +++ b/main.py @@ -673,7 +673,7 @@ def ui_access_wrapper(self, *args, **kwargs): r'/resolveissuehandler/', editor.ResolveIssueHandler), get_redirect_route( - r'/csrfhandler', base.CsrfTokenHandler), + r'%s' % feconf.CSRF_HANDLER_URL, base.CsrfTokenHandler), # 404 error handler. get_redirect_route(r'/<:.*>', base.Error404Handler), From 30a6694ebe7c2d9ace9fa8ae5743dfd2224b7650 Mon Sep 17 00:00:00 2001 From: James John James Date: Tue, 25 Jun 2019 17:18:47 +0100 Subject: [PATCH 24/40] remove csrf from other pages --- .../dev/head/pages/donate-page/donate-page.mainpage.html | 5 ----- .../email-dashboard-pages/email-dashboard-page.mainpage.html | 5 ----- .../email-dashboard-result.mainpage.html | 5 ----- .../topic-landing-page/topic-landing-page.mainpage.html | 5 ----- .../learner-dashboard-page.mainpage.html | 5 ----- .../head/pages/moderator-page/moderator-page.mainpage.html | 5 ----- .../pages/preferences-page/preferences-page.mainpage.html | 5 ----- .../dev/head/pages/signup-page/signup-page.mainpage.html | 5 ----- .../topics-and-skills-dashboard-page.mainpage.html | 5 ----- core/tests/build_sources/templates/base.html | 1 - 10 files changed, 46 deletions(-) diff --git a/core/templates/dev/head/pages/donate-page/donate-page.mainpage.html b/core/templates/dev/head/pages/donate-page/donate-page.mainpage.html index a47ada6b20a9..1a9225753b1c 100644 --- a/core/templates/dev/head/pages/donate-page/donate-page.mainpage.html +++ b/core/templates/dev/head/pages/donate-page/donate-page.mainpage.html @@ -3,11 +3,6 @@ @require('../../base_components/header.html', {"title": "Donate - Oppia"}) - diff --git a/core/templates/dev/head/pages/email-dashboard-pages/email-dashboard-page.mainpage.html b/core/templates/dev/head/pages/email-dashboard-pages/email-dashboard-page.mainpage.html index 806f1493773b..9f0f131855c5 100644 --- a/core/templates/dev/head/pages/email-dashboard-pages/email-dashboard-page.mainpage.html +++ b/core/templates/dev/head/pages/email-dashboard-pages/email-dashboard-page.mainpage.html @@ -3,11 +3,6 @@ @require('../../base_components/header.html', {"title": "Email Dashboard - Oppia"}) -