Skip to content

Commit

Permalink
Reset audited_user when yield raises exception
Browse files Browse the repository at this point in the history
Because if it's not set to nil, all audits made from the sweeper will
use the user from this block instead of current_user, until
Audit.as_user is called again.
  • Loading branch information
flugsio committed Nov 11, 2012
1 parent 2d6330a commit 8a52b0f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
7 changes: 2 additions & 5 deletions lib/audited/audit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,9 @@ def audited_classes
# for background operations that require audit information.
def as_user(user, &block)
Thread.current[:audited_user] = user

yieldval = yield

yield
ensure
Thread.current[:audited_user] = nil

yieldval
end

# @private
Expand Down
9 changes: 9 additions & 0 deletions spec/audited/adapters/active_record/audit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,15 @@ class Models::ActiveRecord::CustomUserSubclass < Models::ActiveRecord::CustomUse
end.should == 42
end

it "should reset audited_user when the yield block raises an exception" do
expect {
Audited.audit_class.as_user('foo') do
raise StandardError
end
}.to raise_exception
Thread.current[:audited_user].should be_nil
end

end

describe "mass assignment" do
Expand Down
9 changes: 9 additions & 0 deletions spec/audited/adapters/mongo_mapper/audit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,15 @@ class Models::MongoMapper::CustomUserSubclass < Models::MongoMapper::CustomUser
end.should == 42
end

it "should reset audited_user when the yield block raises an exception" do
expect {
Audited.audit_class.as_user('foo') do
raise StandardError
end
}.to raise_exception
Thread.current[:audited_user].should be_nil
end

end

end

0 comments on commit 8a52b0f

Please sign in to comment.