aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/rails/commands/credentials/credentials_command.rb
blob: fa54c0362aef080977bb0c560be1a0ce5f8dc552 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# frozen_string_literal: true

require "active_support"
require "rails/command/helpers/editor"

module Rails
  module Command
    class CredentialsCommand < Rails::Command::Base # :nodoc:
      include Helpers::Editor

      no_commands do
        def help
          say "Usage:\n  #{self.class.banner}"
          say ""
          say self.class.desc
        end
      end

      def edit
        require_application_and_environment!

        ensure_editor_available(command: "bin/rails credentials:edit") || (return)
        ensure_master_key_has_been_added if Rails.application.credentials.key.nil?
        ensure_credentials_have_been_added

        catch_editing_exceptions do
          change_credentials_in_system_editor
        end

        say "New credentials encrypted and saved."
      end

      def show
        require_application_and_environment!

        say Rails.application.credentials.read.presence || missing_credentials_message
      end

      private
        def ensure_master_key_has_been_added
          master_key_generator.add_master_key_file
          master_key_generator.ignore_master_key_file
        end

        def ensure_credentials_have_been_added
          credentials_generator.add_credentials_file_silently
        end

        def change_credentials_in_system_editor
          Rails.application.credentials.change do |tmp_path|
            system("#{ENV["EDITOR"]} #{tmp_path}")
          end
        end


        def master_key_generator
          require "rails/generators"
          require "rails/generators/rails/master_key/master_key_generator"

          Rails::Generators::MasterKeyGenerator.new
        end

        def credentials_generator
          require "rails/generators"
          require "rails/generators/rails/credentials/credentials_generator"

          Rails::Generators::CredentialsGenerator.new
        end

        def missing_credentials_message
          if Rails.application.credentials.key.nil?
            "Missing master key to decrypt credentials. See bin/rails credentials:help"
          else
            "No credentials have been added yet. Use bin/rails credentials:edit to change that."
          end
        end
    end
  end
end