aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/rails/generators/rails/encryption_key_file/encryption_key_file_generator.rb
blob: e2359e9dedab3f2e81f2f86d4f0d085b2d48cc97 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# frozen_string_literal: true

require "pathname"
require "rails/generators/base"
require "active_support/encrypted_file"

module Rails
  module Generators
    class EncryptionKeyFileGenerator < Base # :nodoc:
      def add_key_file(key_path)
        key_path = Pathname.new(key_path)

        unless key_path.exist?
          key = ActiveSupport::EncryptedFile.generate_key

          log "Adding #{key_path} to store the encryption key: #{key}"
          log ""
          log "Save this in a password manager your team can access."
          log ""
          log "If you lose the key, no one, including you, can access anything encrypted with it."

          log ""
          add_key_file_silently(key_path, key)
          log ""
        end
      end

      def add_key_file_silently(key_path, key = nil)
        create_file key_path, key || ActiveSupport::EncryptedFile.generate_key
        key_path.chmod 0600
      end

      def ignore_key_file(key_path, ignore: key_ignore(key_path))
        if File.exist?(".gitignore")
          unless File.read(".gitignore").include?(ignore)
            log "Ignoring #{key_path} so it won't end up in Git history:"
            log ""
            append_to_file ".gitignore", ignore
            log ""
          end
        else
          log "IMPORTANT: Don't commit #{key_path}. Add this to your ignore file:"
          log ignore, :on_green
          log ""
        end
      end

      def ignore_key_file_silently(key_path, ignore: key_ignore(key_path))
        append_to_file ".gitignore", ignore if File.exist?(".gitignore")
      end

      private
        def key_ignore(key_path)
          [ "", "/#{key_path}", "" ].join("\n")
        end
    end
  end
end