From 8cb086bed1be786ab0d69f7a8782f31c97a56d02 Mon Sep 17 00:00:00 2001 From: Leonidas Apostolidis Date: Wed, 16 Jun 2021 16:04:02 +0100 Subject: [PATCH] Redirect non GET referers to root_path When the rerefer is not a GET route, the app throws a 404 because there is nothing to serve. --- .../cookie_preferences_controller.rb | 21 ++++++++++---- spec/features/cookie_preferences_spec.rb | 28 +++++++++++++++++++ 2 files changed, 43 insertions(+), 6 deletions(-) create mode 100644 spec/features/cookie_preferences_spec.rb diff --git a/app/controllers/cookie_preferences_controller.rb b/app/controllers/cookie_preferences_controller.rb index 1dcbd5c494..e6b1be27dd 100644 --- a/app/controllers/cookie_preferences_controller.rb +++ b/app/controllers/cookie_preferences_controller.rb @@ -1,7 +1,7 @@ class CookiePreferencesController < ApplicationController - REFERER_BLACKLIST = %r{/(cookie_preference|cookies_policy)}.freeze + REFERER_BLACKLIST = %r{/(cookie_preference)}.freeze skip_before_action :verify_authenticity_token, only: %i[update] - before_action :save_refererer + before_action :save_referer def show redirect_to edit_cookie_preference_path @@ -42,10 +42,19 @@ def remove_rejected_cookies(preferences) end end - def save_refererer - if request.referer.present? && request.referer !~ REFERER_BLACKLIST - session[:cookie_preference_referer] = request.referer - end + def save_referer + session[:cookie_preference_referer] = + if non_get_referer? + root_url + elsif request.referer.present? && request.referer !~ REFERER_BLACKLIST + request.referer + end + end + + def non_get_referer? + Rails.application.routes.recognize_path(request.referer).blank? + rescue ActionController::RoutingError + true end def return_url diff --git a/spec/features/cookie_preferences_spec.rb b/spec/features/cookie_preferences_spec.rb new file mode 100644 index 0000000000..ee1797c120 --- /dev/null +++ b/spec/features/cookie_preferences_spec.rb @@ -0,0 +1,28 @@ +require 'rails_helper' + +feature "Save the referer" do + scenario "a user accepts the cookies from invalid path" do + visit new_candidates_feedback_path + + click_on "Submit feedback" + click_on "Accept cookies" + + expect(page.current_path).to eq(root_path) + end + + scenario "a user accepts the cookies from valid path" do + visit candidates_signin_path + + click_on "Accept cookies" + + expect(page.current_path).to eq(candidates_signin_path) + end + + scenario "a user accepts the cookies from a blacklisted path" do + visit edit_cookie_preference_path + + click_on "Accept cookies" + + expect(page.current_path).to eq(edit_cookie_preference_path) + end +end