summaryrefslogtreecommitdiff
path: root/config/initializers/secret_token.rb
blob: 5d8124b30b211e25e3b504545a7a84b0507facda (plain)
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
# Be sure to restart your server when you modify this file.

require 'securerandom'

def generate_new_secure_token
  SecureRandom.hex(64)
end

def warn_missing_secret(secret)
  warn "Missing Rails.application.secrets.#{secret} for #{Rails.env} environment. The secret will be generated and stored in config/secrets.yml."
end

def create_tokens
  secret_file = Rails.root.join('.secret')
  file_key = File.read(secret_file).chomp if File.exist?(secret_file)
  env_key = ENV['SECRET_KEY_BASE']
  yaml_additions = {}

  # Ensure environment variable always overrides secrets.yml.
  Rails.application.secrets.secret_key_base = env_key if env_key.present?

  defaults = {
    secret_key_base: file_key || generate_new_secure_token,
    otp_key_base: env_key || file_key || generate_new_secure_token,
    db_key_base: generate_new_secure_token
  }

  defaults.stringify_keys.each do |key, default|
    if Rails.application.secrets[key].blank?
      warn_missing_secret(key)

      yaml_additions[key] = Rails.application.secrets[key] = default
    end
  end

  unless yaml_additions.empty?
    secrets_yml = Rails.root.join('config/secrets.yml')
    all_secrets = YAML.load_file(secrets_yml) if File.exist?(secrets_yml)
    all_secrets ||= {}
    env_secrets = all_secrets[Rails.env.to_s] || {}

    all_secrets[Rails.env.to_s] = env_secrets.merge(yaml_additions) do |key, old, new|
      if old.present?
        warn <<EOM
Rails.application.secrets.#{key} was blank, but the literal value in config/secrets.yml was:
  #{old}

This probably isn't the expected value for this secret. To keep using a literal Erb string in config/secrets.yml, replace `<%` with `<%%`.
EOM

        exit 1
      end

      new
    end

    File.write(secrets_yml, YAML.dump(all_secrets), mode: 'w', perm: 0600)
  end

  begin
    File.delete(secret_file) if file_key
  rescue => e
    warn "Error deleting useless .secret file: #{e}"
  end
end

create_tokens