From 8c8c99eb2ccdfe293dc5485601d8718291a85a56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Tue, 25 Jun 2024 18:23:49 +0200 Subject: [PATCH] Correctly check permissions in locales controller We were using `authorize_resource`, passing it an unnamed parameter. When that happens, CanCanCan only checks permissions to read that resource. But, in this case, we want to check the permission to update that resource before the `update` action. Most of the time, it doesn't really matter, but, for example, in our demo we're going to restrict the locales configuration so locales cannot be updated on the main tenant (but they can be updated on other tenants). --- app/controllers/admin/locales_controller.rb | 2 +- .../admin/locales_controller_spec.rb | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 spec/controllers/admin/locales_controller_spec.rb diff --git a/app/controllers/admin/locales_controller.rb b/app/controllers/admin/locales_controller.rb index df822a29b..290e549b2 100644 --- a/app/controllers/admin/locales_controller.rb +++ b/app/controllers/admin/locales_controller.rb @@ -1,6 +1,6 @@ class Admin::LocalesController < Admin::BaseController before_action :set_locales_settings - authorize_resource :locales_settings + authorize_resource instance_name: :locales_settings, class: "Setting::LocalesSettings" def show end diff --git a/spec/controllers/admin/locales_controller_spec.rb b/spec/controllers/admin/locales_controller_spec.rb new file mode 100644 index 000000000..c34928b06 --- /dev/null +++ b/spec/controllers/admin/locales_controller_spec.rb @@ -0,0 +1,17 @@ +require "rails_helper" + +describe Admin::LocalesController do + describe "PATCH update" do + it "checks permissions to update locales settings" do + user = create(:administrator).user + restricted_ability = user.ability.tap { |ability| ability.cannot :update, Setting::LocalesSettings } + + sign_in user + allow(controller).to receive(:current_ability).and_return(restricted_ability) + patch :update, params: { setting_locales_settings: { default: :es, enabled: [:en, :fr] }} + + expect(response).to redirect_to "/" + expect(Setting.default_locale).to eq :en + end + end +end