Skip to content

Commit

Permalink
Call controller's current_user method during audited model creation
Browse files Browse the repository at this point in the history
Restores behaviour prior to 87d402a where the sweeper would call the
controller's current_user method from the audited model callback.

Since 87d402a, the current_user method was called from an around action
callback registered on the base controller which was being called prior
to other callbacks that were authenticating the user. This caused
problems in apps where the user hadn't yet been set (so audit users were
nil), or CSRF issues because current_user was called prior to session
changes.

Fixes collectiveidea#336
  • Loading branch information
domcleal committed Apr 21, 2017
1 parent c3560e5 commit 9014960
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/audited/audit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def set_version_number

def set_audit_user
self.user ||= ::Audited.store[:audited_user] # from .as_user
self.user ||= ::Audited.store[:current_user] # from Sweeper
self.user ||= ::Audited.store[:current_user].try!(:call) # from Sweeper
nil # prevent stopping callback chains
end

Expand Down
2 changes: 1 addition & 1 deletion lib/audited/sweeper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def around(controller)
end

def current_user
controller.send(Audited.current_user_method) if controller.respond_to?(Audited.current_user_method, true)
lambda { controller.send(Audited.current_user_method) if controller.respond_to?(Audited.current_user_method, true) }
end

def remote_ip
Expand Down
20 changes: 20 additions & 0 deletions spec/audited/sweeper_spec.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
require "spec_helper"

class AuditsController < ActionController::Base
if Rails::VERSION::MAJOR == 4
before_filter :populate_user
else
before_action :populate_user
end

attr_reader :company

def create
Expand All @@ -17,6 +23,8 @@ def update

attr_accessor :current_user
attr_accessor :custom_user

def populate_user; end
end

describe AuditsController do
Expand Down Expand Up @@ -69,6 +77,18 @@ def update
expect(controller.company.audits.last.request_uuid).to eq("abc123")
end

it "should call current_user after controller callbacks" do
expect(controller).to receive(:populate_user) do
controller.send(:current_user=, user)
end

expect {
post :create
}.to change( Audited::Audit, :count )

expect(controller.company.audits.last.user).to eq(user)
end

end

describe "PUT update" do
Expand Down

0 comments on commit 9014960

Please sign in to comment.