audit_loggable 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 2e4abe618e6c92a3ffe1c0bb77bd209f6daada37a371a4e82f251c403460c7ac
4
+ data.tar.gz: bce5504334ae400bc74c6b30ba841bd1cfc415797430bd1636c791a2f15bfdcd
5
+ SHA512:
6
+ metadata.gz: a981ea5a538ed5ace3ce70bec24a0d9c2a664b8fcc00d92ec0adf0386bd06df43677d414af3ca9c0ed344d04339ccdd872940bb2d8afe4f10be833fb32335b1a
7
+ data.tar.gz: e614a8b7208a4ddaac957b1362fbd63c4ee2ff1a0402c8edf6810a4266c49ef9da1ccd7eb63225e6aa729b9ab612027cf6996db769356eb148075808354d2c01
@@ -0,0 +1,43 @@
1
+ # This workflow uses actions that are not certified by GitHub.
2
+ # They are provided by a third-party and are governed by
3
+ # separate terms of service, privacy policy, and support
4
+ # documentation.
5
+ # This workflow will download a prebuilt Ruby version, install dependencies and run tests with Rake
6
+ # For more information see: https://github.com/marketplace/actions/setup-ruby-jruby-and-truffleruby
7
+
8
+ name: Build
9
+
10
+ on: [push, pull_request]
11
+
12
+ jobs:
13
+ test:
14
+ runs-on: ubuntu-latest
15
+ strategy:
16
+ matrix:
17
+ ruby: ['2.5', '2.6', '2.7', '3.0']
18
+ activerecord: ['6.0', '6.1']
19
+ experimental: [false]
20
+ exclude:
21
+ - ruby: '3.0'
22
+ activerecord: '6.0'
23
+ experimental: false
24
+ include:
25
+ # waiting for a release of https://github.com/rails/rails/pull/39697
26
+ - ruby: '3.0'
27
+ activerecord: '6.0'
28
+ experimental: true
29
+ continue-on-error: ${{ matrix.experimental }}
30
+ env:
31
+ APPRAISAL: rails_${{ matrix.activerecord }}
32
+ steps:
33
+ - uses: actions/checkout@v2
34
+ - name: Set up Ruby
35
+ uses: ruby/setup-ruby@v1
36
+ with:
37
+ ruby-version: ${{ matrix.ruby }}
38
+ - name: Install dependencies
39
+ run: |
40
+ bundle install
41
+ bundle exec appraisal $APPRAISAL bundle install
42
+ - name: Run tests
43
+ run: bundle exec appraisal $APPRAISAL rake
data/.gitignore ADDED
@@ -0,0 +1,16 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /Gemfile.lock
5
+ /gemfiles/*.lock
6
+ /gemfiles/.bundle/
7
+ /coverage/
8
+ /doc/
9
+ /pkg/
10
+ /spec/reports/
11
+ /tmp/
12
+
13
+ # rspec failure tracking
14
+ .rspec_status
15
+
16
+ /audits.log
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/Appraisals ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ appraise "rails_6.0" do
4
+ gem "rails", "~> 6.0.0"
5
+ end
6
+
7
+ appraise "rails_6.1" do
8
+ gem "rails", "~> 6.1.0"
9
+ end
data/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ ## Unreleased
2
+
3
+
4
+ ## 1.0.0 (2021-03-30)
5
+
6
+ * Initial release
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at info@vivid-garden.co.jp. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
6
+
7
+ # Specify your gem's dependencies in audit_loggable.gemspec
8
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 vivid garden Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,99 @@
1
+ # AuditLoggable
2
+
3
+ [![Build](https://github.com/vividgarden/audit_loggable/actions/workflows/ruby.yml/badge.svg)](https://github.com/vividgarden/audit_loggable/actions/workflows/ruby.yml)
4
+
5
+ AuditLoggable is a Rails plugin gem that logs changes to your models. AuditLoggable can also record who made those changes.
6
+ AuditLoggable is inspired by [Audited](https://github.com/collectiveidea/audited). However AuditLoggable logs to a JSONL file instead of RDB table.
7
+
8
+ ## Installation
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem 'audit_loggable'
14
+ ```
15
+
16
+ And then execute:
17
+
18
+ $ bundle
19
+
20
+ Or install it yourself as:
21
+
22
+ $ gem install audit_loggable
23
+
24
+ ## Usage
25
+
26
+ ### Configuration
27
+ ``` ruby
28
+ # config/initializers/audit_loggable.rb
29
+ AuditLoggable.configure do |config|
30
+ if Rails.env.test?
31
+ config.auditing_enabled = false
32
+ end
33
+ config.audit_log_path = Rails.root.join("log", "audits.log")
34
+ config.audit_log_shift_age = "daily"
35
+ end
36
+ ```
37
+
38
+ Options
39
+ | Name | Type | Description | Default |
40
+ |:--------------------------------|:------------------|:-------------------------------------------------------------------|:----------|
41
+ | `auditing_enabled` | Boolean | Switch to record audit log. | `true` |
42
+ | `audit_log_path` | String | Path of audit log file. | `nil` |
43
+ | `audit_log_shift_age` | Integer or String | Same as `shift_age` option of `Logger` class of stdlib. | `0` |
44
+ | `audit_log_shift_size` | Integer | Same as `shift_size` option of `Logger` class of stdlib. | `1048576` |
45
+ | `audit_log_shift_period_suffix` | String | Same as `shift_period_suffix` options of `Logger` class of stdlib. | `%Y%m%d` |
46
+
47
+ ### Extend your model by `AuditLoggable::Extension`
48
+ ``` ruby
49
+ class ApplicationRecord < ActiveRecord::Base
50
+ extend AuditLoggable::Extension
51
+ end
52
+ ```
53
+
54
+ Active `AuditLoggable` in your model
55
+ ``` ruby
56
+ class Post < ApplicationRecord
57
+ log_audit
58
+ end
59
+ ```
60
+
61
+ if you need to except columns by audit logging, specify `except` option as follow:
62
+ ``` ruby
63
+ class Post < ApplicationRecord
64
+ log_audit except: %w[foo bar]
65
+ end
66
+ ```
67
+
68
+ if you need to record changes but not their values by audit logging, specify `redacted` option as follow:
69
+ ``` ruby
70
+ class Post < ApplicationRecord
71
+ log_audit redacted: %w[foo bar]
72
+ end
73
+ ```
74
+
75
+ ### Extend your controller by `AuditLoggable::Sweeper` to track request info (e.g. current user)
76
+ ``` ruby
77
+ class ApplicationController < ActionController::Base
78
+ around_action AuditLoggable::Sweeper.new(current_user_methods: %i[current_user])
79
+ end
80
+ ```
81
+
82
+
83
+ ## Development
84
+
85
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
86
+
87
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
88
+
89
+ ## Contributing
90
+
91
+ Bug reports and pull requests are welcome on GitHub at https://github.com/vividgarden/audit_loggable. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/vividgarden/audit_loggable/blob/main/CODE_OF_CONDUCT.md).
92
+
93
+ ## License
94
+
95
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
96
+
97
+ ## Code of Conduct
98
+
99
+ Everyone interacting in the AuditLoggable project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/vividgarden/audit_loggable/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rake/clean"
9
+ CLEAN.include("audits.log")
10
+
11
+ task default: :spec
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path("lib", __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require "audit_loggable/version"
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "audit_loggable"
9
+ spec.version = AuditLoggable::VERSION
10
+ spec.authors = ["Yuji Hanamura"]
11
+ spec.email = ["yuji.developer@gmail.com"]
12
+
13
+ spec.summary = "Log changes to your models"
14
+ spec.description = spec.summary
15
+ spec.homepage = "https://github.com/vividgarden/audit_loggable"
16
+ spec.license = "MIT"
17
+
18
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
19
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
20
+ if spec.respond_to?(:metadata)
21
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
22
+
23
+ spec.metadata["homepage_uri"] = spec.homepage
24
+ spec.metadata["source_code_uri"] = spec.homepage
25
+ spec.metadata["changelog_uri"] = "https://github.com/vividgarden/audit_loggable/blob/main/CHANGELOG.md"
26
+ else
27
+ raise "RubyGems 2.0 or newer is required to protect against " \
28
+ "public gem pushes."
29
+ end
30
+
31
+ # Specify which files should be added to the gem when it is released.
32
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
33
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
34
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
35
+ end
36
+ spec.bindir = "exe"
37
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
38
+ spec.require_paths = ["lib"]
39
+
40
+ spec.required_ruby_version = ">= 2.5"
41
+
42
+ spec.add_dependency "activerecord", ">= 6.0"
43
+ spec.add_dependency "activesupport", ">= 6.0"
44
+
45
+ spec.add_development_dependency "appraisal", ">= 2.3.0"
46
+ spec.add_development_dependency "bundler", ">= 1.17"
47
+ spec.add_development_dependency "rails", ">= 6.0"
48
+ spec.add_development_dependency "rake", ">= 10.0"
49
+ spec.add_development_dependency "rspec", "~> 3.10"
50
+ spec.add_development_dependency "sqlite3", "~> 1.4"
51
+ end
data/bin/console ADDED
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "audit_loggable"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ AuditLoggable.configure do |config|
11
+ config.audit_log_path = File.expand_path("../audits.log", __dir__)
12
+ end
13
+
14
+ # (If you use this, don't forget to add pry to your Gemfile!)
15
+ # require "pry"
16
+ # Pry.start
17
+
18
+ require "irb"
19
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,7 @@
1
+ # This file was generated by Appraisal
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gem "rails", "~> 6.0.0"
6
+
7
+ gemspec path: "../"
@@ -0,0 +1,7 @@
1
+ # This file was generated by Appraisal
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gem "rails", "~> 6.1.0"
6
+
7
+ gemspec path: "../"
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "active_support/core_ext/object/blank"
5
+ require "active_support/core_ext/object/json"
6
+ require "active_support/core_ext/module/attr_internal"
7
+ require "active_support/core_ext/module/delegation"
8
+
9
+ require "audit_loggable/version"
10
+ require "audit_loggable/configuration"
11
+ require "audit_loggable/logger"
12
+ require "audit_loggable/store"
13
+ require "audit_loggable/change_set"
14
+ require "audit_loggable/audit_record"
15
+ require "audit_loggable/audit_record_set"
16
+ require "audit_loggable/sweeper"
17
+ require "audit_loggable/extension"
18
+
19
+ module AuditLoggable
20
+ class << self
21
+ attr_reader :logger
22
+
23
+ delegate :audit_log_path, :audit_log_shift_age, :audit_log_shift_size, :audit_log_shift_period_suffix,
24
+ :auditing_enabled,
25
+ to: :configuration
26
+
27
+ def configure
28
+ yield configuration
29
+ initialize_logger
30
+
31
+ self
32
+ end
33
+
34
+ private
35
+
36
+ attr_reader :configuration
37
+
38
+ def initialize_logger
39
+ @logger = Logger.new(
40
+ self.audit_log_path,
41
+ shift_age: self.audit_log_shift_age,
42
+ shift_size: self.audit_log_shift_size,
43
+ shift_period_suffix: self.audit_log_shift_period_suffix
44
+ )
45
+ end
46
+ end
47
+
48
+ @configuration = Configuration.new
49
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AuditLoggable
4
+ class AuditRecord
5
+ def initialize(auditable, user, action, changeset, remote_address, request_uuid)
6
+ @auditable = auditable
7
+ @user = user
8
+ @action = action
9
+ @changeset = changeset
10
+ @remote_address = remote_address
11
+ @request_uuid = request_uuid
12
+ end
13
+
14
+ def as_json(*)
15
+ {
16
+ auditable: { id: auditable.id, type: auditable.class.polymorphic_name },
17
+ user: user ? { id: user.id, type: user.class.polymorphic_name } : nil,
18
+ action: action,
19
+ changes: changeset.to_json, # serialize to JSON string
20
+ remote_address: remote_address,
21
+ request_uuid: request_uuid
22
+ }
23
+ end
24
+
25
+ private
26
+
27
+ attr_reader :auditable, :user, :action, :changeset, :remote_address, :request_uuid
28
+ end
29
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AuditLoggable
4
+ class AuditRecordSet
5
+ include ::Enumerable
6
+
7
+ delegate :empty?, to: :set
8
+
9
+ def initialize
10
+ clear
11
+ end
12
+
13
+ def <<(audit_record)
14
+ set << audit_record
15
+ self
16
+ end
17
+
18
+ def clear
19
+ @set = []
20
+ self
21
+ end
22
+
23
+ def each(&block)
24
+ return to_enum unless block
25
+
26
+ set.each(&block)
27
+ self
28
+ end
29
+
30
+ def flush
31
+ ::AuditLoggable.logger.log(set)
32
+ clear
33
+ end
34
+
35
+ private
36
+
37
+ attr_reader :set
38
+ end
39
+ end
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AuditLoggable
4
+ module ChangeSet
5
+ class AttributesFilter
6
+ IGNORED_ATTRIBUTES = %w[created_at updated_at created_on updated_on].freeze
7
+
8
+ def initialize(klass, ignored_attributes, changes)
9
+ @klass = klass
10
+ @ignored_attributes = ignored_attributes
11
+ @changes = changes
12
+ end
13
+
14
+ def call
15
+ @changes
16
+ .except(
17
+ @klass.primary_key,
18
+ @klass.inheritance_column,
19
+ @klass.locking_column,
20
+ *@ignored_attributes,
21
+ *IGNORED_ATTRIBUTES
22
+ )
23
+ end
24
+ end
25
+
26
+ class EnumAttributesNormalizer
27
+ def initialize(klass, changes)
28
+ @klass = klass
29
+ @changes = changes
30
+ end
31
+
32
+ def call
33
+ @klass.defined_enums.each_pair.with_object(@changes.dup) do |(name, values), changes|
34
+ next unless changes.key?(name)
35
+
36
+ changes[name] =
37
+ if changes[name].is_a? ::Array
38
+ changes[name].map { |v| values[v] }
39
+ else
40
+ changes[name] = values[changes[name]]
41
+ end
42
+ end
43
+ end
44
+ end
45
+
46
+ class AttributesRedactor
47
+ REDACTED_VALUE = "[REDACTED]"
48
+
49
+ def initialize(redacted_attributes, changes)
50
+ @redacted_attributes = redacted_attributes
51
+ @changes = changes
52
+ end
53
+
54
+ def call
55
+ @redacted_attributes.each.with_object(@changes.dup) do |name, changes|
56
+ next unless changes.key?(name)
57
+
58
+ changes[name] =
59
+ if changes[name].is_a? ::Array
60
+ ::Array.new(changes[name].size, REDACTED_VALUE)
61
+ else
62
+ REDACTED_VALUE
63
+ end
64
+ end
65
+ end
66
+ end
67
+
68
+ class Base
69
+ def initialize(model, changes_method:, ignored_attributes: [], redacted_attributes: [])
70
+ klass = model.class
71
+ @changes =
72
+ model
73
+ .public_send(changes_method)
74
+ .yield_self { |changes| AttributesFilter.new(klass, ignored_attributes, changes).call }
75
+ .yield_self { |changes| EnumAttributesNormalizer.new(klass, changes).call }
76
+ .yield_self { |changes| AttributesRedactor.new(redacted_attributes, changes).call }
77
+ end
78
+
79
+ delegate :as_json, :empty?, to: :changes
80
+
81
+ private
82
+
83
+ attr_reader :changes
84
+ end
85
+
86
+ class Create < Base
87
+ def initialize(*args, **kwargs)
88
+ super(*args, changes_method: :attributes, **kwargs)
89
+ end
90
+ end
91
+
92
+ class Update < Base
93
+ def initialize(*args, **kwargs)
94
+ super(*args, changes_method: :previous_changes, **kwargs)
95
+ end
96
+ end
97
+
98
+ class Destroy < Base
99
+ def initialize(*args, **kwargs)
100
+ super(*args, changes_method: :attributes, **kwargs)
101
+ end
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AuditLoggable
4
+ class Configuration
5
+ attr_accessor :audit_log_path, :audit_log_shift_age, :audit_log_shift_size, :audit_log_shift_period_suffix,
6
+ :auditing_enabled
7
+
8
+ def initialize
9
+ self.auditing_enabled = true
10
+ self.audit_log_shift_age = 0
11
+ self.audit_log_shift_size = 1024 * 1024
12
+ self.audit_log_shift_period_suffix = "%Y%m%d"
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AuditLoggable
4
+ module Extension
5
+ def log_audit(except: [], redacted: [])
6
+ self.class_eval do
7
+ attr_internal :audit_loggable_audit_record_set
8
+
9
+ callbacks = Callbacks.new(except: except, redacted: redacted)
10
+ after_create callbacks
11
+ after_update callbacks
12
+ after_destroy callbacks
13
+ after_rollback callbacks
14
+ after_commit callbacks
15
+ end
16
+ end
17
+
18
+ class Callbacks
19
+ def initialize(except: [], redacted: [])
20
+ @ignored_attributes = ::Array.wrap(except).map(&:to_s)
21
+ @redacted_attributes = ::Array.wrap(redacted).map(&:to_s)
22
+ end
23
+
24
+ def after_create(model)
25
+ changeset = build_changeset_for_create(model)
26
+
27
+ audit_record = build_audit_record(model, :create, changeset)
28
+ add_audit_record(model, audit_record)
29
+ end
30
+
31
+ def after_update(model)
32
+ changeset = build_changeset_for_update(model)
33
+ return if changeset.blank?
34
+
35
+ audit_record = build_audit_record(model, :update, changeset)
36
+ add_audit_record(model, audit_record)
37
+ end
38
+
39
+ def after_destroy(model)
40
+ changeset = build_changeset_for_destroy(model)
41
+
42
+ audit_record = build_audit_record(model, :destroy, changeset)
43
+ add_audit_record(model, audit_record)
44
+ end
45
+
46
+ def after_rollback(model)
47
+ return if model.audit_loggable_audit_record_set.blank?
48
+
49
+ clear_audit_record_set(model)
50
+ end
51
+
52
+ def after_commit(model)
53
+ return if model.audit_loggable_audit_record_set.blank?
54
+
55
+ persist_audit_record_set(model)
56
+ end
57
+
58
+ private
59
+
60
+ attr_reader :ignored_attributes, :redacted_attributes
61
+
62
+ def build_changeset_for_create(model)
63
+ ChangeSet::Create.new(model, ignored_attributes: ignored_attributes, redacted_attributes: redacted_attributes)
64
+ end
65
+
66
+ def build_changeset_for_update(model)
67
+ ChangeSet::Update.new(model, ignored_attributes: ignored_attributes, redacted_attributes: redacted_attributes)
68
+ end
69
+
70
+ def build_changeset_for_destroy(model)
71
+ ChangeSet::Destroy.new(model, ignored_attributes: ignored_attributes, redacted_attributes: redacted_attributes)
72
+ end
73
+
74
+ def build_audit_record(model, action, changeset)
75
+ user = Store.current_user
76
+ address = Store.current_remote_address
77
+ uuid = Store.current_request_uuid
78
+
79
+ AuditRecord.new(model, user, action, changeset, address, uuid)
80
+ end
81
+
82
+ def add_audit_record(model, audit_record)
83
+ model.audit_loggable_audit_record_set ||= AuditRecordSet.new
84
+ model.audit_loggable_audit_record_set << audit_record
85
+ end
86
+
87
+ def clear_audit_record_set(model)
88
+ model.audit_loggable_audit_record_set.clear
89
+ end
90
+
91
+ def persist_audit_record_set(model)
92
+ model.audit_loggable_audit_record_set.flush
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "logger"
4
+
5
+ module AuditLoggable
6
+ class Logger
7
+ class JSONFormatter < ::Logger::Formatter
8
+ def call(_severity, time, _progname, message)
9
+ h = { timestamp: time, record: message }
10
+ "#{h.to_json}\n"
11
+ end
12
+ end
13
+
14
+ class NoHeaderLogDevice < ::Logger::LogDevice
15
+ private
16
+
17
+ def add_log_header(*)
18
+ # Suppress header output when creating a log file
19
+ end
20
+ end
21
+
22
+ class InternalLogger < ::Logger
23
+ def initialize(logdev, shift_age:, shift_size:, shift_period_suffix:)
24
+ super(nil, level: :info, formatter: JSONFormatter.new)
25
+
26
+ return unless logdev
27
+
28
+ @logdev =
29
+ NoHeaderLogDevice.new(logdev,
30
+ shift_age: shift_age,
31
+ shift_size: shift_size,
32
+ shift_period_suffix: shift_period_suffix)
33
+ end
34
+ end
35
+
36
+ def initialize(*args, **kwargs)
37
+ @logger = InternalLogger.new(*args, **kwargs)
38
+ end
39
+
40
+ def log(audit_record_set)
41
+ return unless ::AuditLoggable.auditing_enabled
42
+
43
+ audit_record_set.each do |audit_record|
44
+ @logger.info(audit_record)
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/current_attributes"
4
+
5
+ module AuditLoggable
6
+ class Store < ::ActiveSupport::CurrentAttributes
7
+ attribute :current_controller, :current_user, :current_remote_address, :current_request_uuid
8
+
9
+ def current_user
10
+ super&.yield_self do |user|
11
+ if user.is_a?(::Proc) || user.is_a?(::Method) || user.respond_to?(:call)
12
+ user.call
13
+ else
14
+ user
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AuditLoggable
4
+ class Sweeper
5
+ STORED_DATA = {
6
+ current_remote_address: :remote_ip,
7
+ current_request_uuid: :request_uuid,
8
+ current_user: :current_user
9
+ }.freeze
10
+
11
+ def initialize(current_user_methods: %i[current_user])
12
+ @current_user_methods = ::Array.wrap(current_user_methods).map(&:to_sym)
13
+ end
14
+
15
+ def around(controller, &block)
16
+ Store.set({ current_controller: controller }) do
17
+ Store.set(
18
+ STORED_DATA
19
+ .each_pair
20
+ .with_object({}) { |(k, m), h| h[k] = __send__(m) },
21
+ &block
22
+ )
23
+ end
24
+ end
25
+
26
+ private
27
+
28
+ attr_reader :current_user_methods
29
+
30
+ delegate :request, to: :controller, private: true, allow_nil: true
31
+ delegate :remote_ip, to: :request, private: true, allow_nil: true
32
+ delegate :uuid, to: :request, private: true, allow_nil: true, prefix: true
33
+
34
+ def current_user
35
+ lambda do
36
+ current_user_methods
37
+ .lazy.map { |m| controller.__send__(m) if controller.respond_to?(m, true) }
38
+ .find(&:present?)
39
+ end
40
+ end
41
+
42
+ def controller
43
+ Store.current_controller
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AuditLoggable
4
+ VERSION = "1.0.0"
5
+ end
metadata ADDED
@@ -0,0 +1,184 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: audit_loggable
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Yuji Hanamura
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-03-29 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '6.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '6.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: activesupport
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '6.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '6.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: appraisal
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: 2.3.0
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: 2.3.0
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '1.17'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '1.17'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rails
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '6.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '6.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rake
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '10.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '10.0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rspec
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '3.10'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '3.10'
111
+ - !ruby/object:Gem::Dependency
112
+ name: sqlite3
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '1.4'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '1.4'
125
+ description: Log changes to your models
126
+ email:
127
+ - yuji.developer@gmail.com
128
+ executables: []
129
+ extensions: []
130
+ extra_rdoc_files: []
131
+ files:
132
+ - ".github/workflows/ruby.yml"
133
+ - ".gitignore"
134
+ - ".rspec"
135
+ - Appraisals
136
+ - CHANGELOG.md
137
+ - CODE_OF_CONDUCT.md
138
+ - Gemfile
139
+ - LICENSE.txt
140
+ - README.md
141
+ - Rakefile
142
+ - audit_loggable.gemspec
143
+ - bin/console
144
+ - bin/setup
145
+ - gemfiles/rails_6.0.gemfile
146
+ - gemfiles/rails_6.1.gemfile
147
+ - lib/audit_loggable.rb
148
+ - lib/audit_loggable/audit_record.rb
149
+ - lib/audit_loggable/audit_record_set.rb
150
+ - lib/audit_loggable/change_set.rb
151
+ - lib/audit_loggable/configuration.rb
152
+ - lib/audit_loggable/extension.rb
153
+ - lib/audit_loggable/logger.rb
154
+ - lib/audit_loggable/store.rb
155
+ - lib/audit_loggable/sweeper.rb
156
+ - lib/audit_loggable/version.rb
157
+ homepage: https://github.com/vividgarden/audit_loggable
158
+ licenses:
159
+ - MIT
160
+ metadata:
161
+ allowed_push_host: https://rubygems.org
162
+ homepage_uri: https://github.com/vividgarden/audit_loggable
163
+ source_code_uri: https://github.com/vividgarden/audit_loggable
164
+ changelog_uri: https://github.com/vividgarden/audit_loggable/blob/main/CHANGELOG.md
165
+ post_install_message:
166
+ rdoc_options: []
167
+ require_paths:
168
+ - lib
169
+ required_ruby_version: !ruby/object:Gem::Requirement
170
+ requirements:
171
+ - - ">="
172
+ - !ruby/object:Gem::Version
173
+ version: '2.5'
174
+ required_rubygems_version: !ruby/object:Gem::Requirement
175
+ requirements:
176
+ - - ">="
177
+ - !ruby/object:Gem::Version
178
+ version: '0'
179
+ requirements: []
180
+ rubygems_version: 3.2.3
181
+ signing_key:
182
+ specification_version: 4
183
+ summary: Log changes to your models
184
+ test_files: []