Rails审计系统包含ActiveResource和ActiveRecord

时间:2011-05-13 08:41:38

标签: ruby ruby-on-rails-3 logging observer-pattern auditing

我有一个包含ActiveRecord和ActiveResource模型的庞大项目。我需要使用这些模型实现用户活动的记录,并记录模型属性的更改(保存对象状态或类似的东西)。用户或cron rake任务可以进行更改。

我也必须有可能按日期搜索任何数据,任何字段..etc

使用上一个活动生成可读消息也很不错,例如

  
      
  • 用户Bob将密码更改为 * ,并在2011-08-12 08:12发送电子邮件至 **
  •   
  • 员工杰夫添加新合作伙伴:公司名称于2011-08-12 08:13
  •   
  • Admin Jack已删除产品:产品名称于2011-09-12 11:11
  •   
  • 客户Sam订购了新服务:服务名称于2011-09-12 11:12
  •   

有人实施此类日志记录吗?想法?建议?

我应该使用宝石还是我可以使用不改变模型的观察者来做所有逻辑?


我喜欢gem https://github.com/airblade/paper_trail任何人都可以说我如何才能使用activeresource?

6 个答案:

答案 0 :(得分:4)

您正在寻找

https://github.com/collectiveidea/acts_as_audited

很少有开源项目使用该插件我认为 Red Mine 以及 The Foreman

编辑:不幸的是,它只能执行ActiveRecord,而不能执行ActiveResource。

答案 1 :(得分:4)

Fivell,我刚刚看到这个问题并且没有时间在赏金到期之前进行修改,所以我会给你我的审计代码与ActiveRecord一起使用并且应该与ActiveResource一起使用,也许还有一些调整(我不经常使用ARes来了解随意)。我知道我们使用的回调是存在的,但我不确定ARes是否有ActiveRecord的脏属性changes跟踪。

此代码记录所有模型上的每个CREATE / UPDATE / DELETE(审核日志模型上的CREATE以及您指定的任何其他异常),并将更改存储为JSON。还存储了已清理的回溯,以便您可以确定进行更改的代码(这可以捕获MVC中的任何点以及rake任务和控制台使用情况)。

此代码适用于控制台使用,rake任务和http请求,但通常只有最后一个会记录当前用户。 (如果我没记错的话,ActiveRecord观察者认为这个替换在rake任务或控制台中不起作用。)哦,这个代码来自Rails 2.3应用程序 - 我有几个Rails 3应用程序,但我不需要这种对他们进行审计。

我没有能够构建这些信息的良好显示的代码(我们只需要在查看问题时深入研究数据),但由于更改存储为JSON,因此应该相当简单。

首先,我们将当前用户存储在User.current中,以便随处可访问,因此在app/models/user.rb

Class User < ActiveRecord::Base
  cattr_accessor :current
  ...
end

当前用户在应用程序控制器中为每个请求设置如此(并且不会导致并发问题):

def current_user
  User.current = session[:user_id] ? User.find_by_id(session[:user_id]) : nil
end

如果有意义,可以在rake任务中设置User.current

接下来,我们定义模型以存储审核信息app/models/audit_log_entry.rb - 您需要自定义IgnoreClassesRegEx以适合您不希望审核的任何模型:

# == Schema Information
#
# Table name: audit_log_entries
#
#  id         :integer         not null, primary key
#  class_name :string(255)
#  entity_id  :integer
#  user_id    :integer
#  action     :string(255)
#  data       :text
#  call_chain :text
#  created_at :datetime
#  updated_at :datetime
#

class AuditLogEntry < ActiveRecord::Base
  IgnoreClassesRegEx = /^ActiveRecord::Acts::Versioned|ActiveRecord.*::Session|Session|Sequence|SchemaMigration|CronRun|CronRunMessage|FontMetric$/
  belongs_to :user

  def entity (reload = false)
    @entity = nil if reload
    begin
      @entity ||= Kernel.const_get(class_name).find_by_id(entity_id)
    rescue
      nil
    end
  end

  def call_chain
    return if call_chain_before_type_cast.blank?
    if call_chain_before_type_cast.instance_of?(Array)
      call_chain_before_type_cast
    else
      JSON.parse(call_chain_before_type_cast)
    end
  end
  def data
    return if data_before_type_cast.blank?
    if data_before_type_cast.instance_of?(Hash)
      data_before_type_cast
    else
      JSON.parse(data_before_type_cast)
    end
  end

  def self.debug_entity(class_name, entity_id)
    require 'fastercsv'
    FasterCSV.generate do |csv|
      csv << %w[class_name entity_id date action first_name last_name data]
      find_all_by_class_name_and_entity_id(class_name, entity_id,
                                           :order => 'created_at').each do |a|
        csv << [a.class_name, a.entity_id, a.created_at, a.action, 
          (a.user && a.user.first_name), (a.user && a.user.last_name), a.data]
      end
    end
  end
end

接下来,我们向ActiveRecord::Base添加一些方法,以使审核工作。您需要查看audit_log_clean_backtrace方法并根据需要进行修改。 (FWIW,我们在lib/extensions/*.rb中添加了在初始化程序中加载的现有类。)在lib/extensions/active_record.rb中:

class ActiveRecord::Base
  cattr_accessor :audit_log_backtrace_cleaner
  after_create  :audit_log_on_create
  before_update :save_audit_log_update_diff
  after_update  :audit_log_on_update
  after_destroy :audit_log_on_destroy
  def audit_log_on_create
    return if self.class.name =~ /AuditLogEntry/
    return if self.class.name =~ AuditLogEntry::IgnoreClassesRegEx
    audit_log_create 'CREATE', self, caller
  end
  def save_audit_log_update_diff
    @audit_log_update_diff = changes.reject{ |k,v| 'updated_at' == k }
  end
  def audit_log_on_update
    return if self.class.name =~ AuditLogEntry::IgnoreClassesRegEx
    return if @audit_log_update_diff.empty?
    audit_log_create 'UPDATE', @audit_log_update_diff, caller
  end
  def audit_log_on_destroy
    return if self.class.name =~ AuditLogEntry::IgnoreClassesRegEx
    audit_log_create 'DESTROY', self, caller
  end
  def audit_log_create (action, data, call_chain)
    AuditLogEntry.create :user       => User.current,
                         :action     => action,
                         :class_name => self.class.name,
                         :entity_id  => id,
                         :data       => data.to_json,
                         :call_chain => audit_log_clean_backtrace(call_chain).to_json
  end
  def audit_log_clean_backtrace (backtrace)
    if !ActiveRecord::Base.audit_log_backtrace_cleaner
      ActiveRecord::Base.audit_log_backtrace_cleaner = ActiveSupport::BacktraceCleaner.new
      ActiveRecord::Base.audit_log_backtrace_cleaner.add_silencer { |line| line =~ /\/lib\/rake\.rb/ }
      ActiveRecord::Base.audit_log_backtrace_cleaner.add_silencer { |line| line =~ /\/bin\/rake/ }
      ActiveRecord::Base.audit_log_backtrace_cleaner.add_silencer { |line| line =~ /\/lib\/(action_controller|active_(support|record)|hoptoad_notifier|phusion_passenger|rack|ruby|sass)\// }
      ActiveRecord::Base.audit_log_backtrace_cleaner.add_filter   { |line| line.gsub(RAILS_ROOT, '') }
    end
    ActiveRecord::Base.audit_log_backtrace_cleaner.clean backtrace
  end
end

最后,以下是我们对此进行的测试 - 您当然需要修改实际的测试操作。 test/integration/audit_log_test.rb

require File.dirname(__FILE__) + '/../test_helper'

class AuditLogTest < ActionController::IntegrationTest
  def setup
  end

  def test_audit_log
    u = users(:manager)
    log_in u
    a = Alert.first :order => 'id DESC'
    visit 'alerts/new'
    fill_in 'alert_note'
    click_button 'Send Alert'
    a = Alert.first :order => 'id DESC', :conditions => ['id > ?', a ? a.id : 0]
    ale = AuditLogEntry.first :conditions => {:class_name => 'Alert', :entity_id => a.id }
    assert_equal 'Alert',  ale.class_name
    assert_equal 'CREATE', ale.action
  end

private

  def log_in (user, password = 'test', initial_url = home_path)
    visit initial_url
    assert_contain 'I forgot my password'
    fill_in 'email',    :with => user.email
    fill_in 'password', :with => password
    click_button 'Log In'
  end

  def log_out
    visit logout_path
    assert_contain 'I forgot my password'
  end
end

test/unit/audit_log_entry_test.rb

# == Schema Information
#
# Table name: audit_log_entries
#
#  id         :integer         not null, primary key
#  class_name :string(255)
#  action     :string(255)
#  data       :text
#  user_id    :integer
#  created_at :datetime
#  updated_at :datetime
#  entity_id  :integer
#  call_chain :text
#

require File.dirname(__FILE__) + '/../test_helper'

class AuditLogEntryTest < ActiveSupport::TestCase
  test 'should handle create update and delete' do
    record = Alert.new :note => 'Test Alert'
    assert_difference 'Alert.count' do
      assert_difference 'AuditLogEntry.count' do
        record.save
        ale = AuditLogEntry.first :order => 'created_at DESC'
        assert ale
        assert_equal 'CREATE', ale.action, 'AuditLogEntry.action should be CREATE'
        assert_equal record.class.name, ale.class_name, 'AuditLogEntry.class_name should match record.class.name'
        assert_equal record.id, ale.entity_id, 'AuditLogEntry.entity_id should match record.id'
      end
    end
    assert_difference 'AuditLogEntry.count' do
      record.update_attribute 'note', 'Test Update'
      ale = AuditLogEntry.first :order => 'created_at DESC'
      expected_data = {'note' => ['Test Alert', 'Test Update']}
      assert ale
      assert_equal 'UPDATE', ale.action, 'AuditLogEntry.action should be UPDATE'
      assert_equal expected_data, ale.data
      assert_equal record.class.name, ale.class_name, 'AuditLogEntry.class_name should match record.class.name'
      assert_equal record.id, ale.entity_id, 'AuditLogEntry.entity_id should match record.id'
    end
    assert_difference 'AuditLogEntry.count' do
      record.destroy
      ale = AuditLogEntry.first :order => 'created_at DESC'
      assert ale
      assert_equal 'DESTROY', ale.action, 'AuditLogEntry.action should be CREATE'
      assert_equal record.class.name, ale.class_name, 'AuditLogEntry.class_name should match record.class.name'
      assert_equal record.id, ale.entity_id, 'AuditLogEntry.entity_id should match record.id'
      assert_nil Alert.find_by_id(record.id), 'Alert should be deleted'
    end
  end

  test 'should not log AuditLogEntry create entry and block on update and delete' do
    record = Alert.new :note => 'Test Alert'
    assert_difference 'Alert.count' do
      assert_difference 'AuditLogEntry.count' do
        record.save
      end
    end
    ale = AuditLogEntry.first :order => 'created_at DESC'
    assert_equal 'CREATE', ale.action, 'AuditLogEntry.action should be CREATE'
    assert_equal record.class.name, ale.class_name, 'AuditLogEntry.class_name should match record.class.name'
    assert_equal record.id, ale.entity_id, 'AuditLogEntry.entity_id should match record.id'
    assert_nil AuditLogEntry.first(:conditions => { :class_name => 'AuditLogEntry', :entity_id => ale.id })

    if ale.user_id.nil?
      u = User.first
    else
      u = User.first :conditions => ['id != ?', ale.user_id]
    end
    ale.user_id = u.id
    assert !ale.save

    assert !ale.destroy
  end
end

答案 2 :(得分:3)

https://github.com/collectiveidea/acts_as_audited

https://github.com/airblade/paper_trail

仅适用于ActiveRecord,但由于ActiveRecord的大部分内容已被提取到ActiveModel,因此将ActiveResource扩展为支持paper_trail可能是合理的。好吧,至少对于只读支持。我查看了Github网络图并用Google搜索,似乎没有任何正在进行的此类解决方案的开发,但我希望在这两个插件之一上实现比从头开始更容易实现。 {{1}}似乎处于更积极的开发状态,并且对Rails 3.1有一些提交,所以它可能更新了Rails内部并且更容易扩展,但这只是一种直觉 - 我不熟悉两者的内部。

答案 3 :(得分:1)

acts_as_audited gem应该适合你:
https://github.com/collectiveidea/acts_as_audited

就ActiveResource而言,它也将成为其他应用程序中的模型。您可以在服务器端使用gem,而无需在客户端进行审核。使用ActiveResource的所有CRUD操作最终将转换为ActiveRecord上的CRUD操作(在服务器端)。

所以你可能需要从远处看它,同样的解决方案适用于两种情况,但在不同的地方。

答案 4 :(得分:1)

为了跟踪用户活动(CRUD),我创建了一个继承自Logger的类,现在我计划编写一个用于跟踪用户的litle插件,我可以用它来构建任何ROR应用程序。我已经检查过是否有这样的插件,但我没有看到。我猜有许多宝石像paper-trail,acts_as_audited或itslog但我更喜欢使用插件。有什么建议? 以下链接可能对您有所帮助:http://robaldred.co.uk/2009/01/custom-log-files-for-your-ruby-on-rails-applications/comment-page-1/#comment-342

很好的编码

答案 5 :(得分:0)

看看这个railscast,也许它可以帮助你:Notifications