|
| 1 | +class MissionControl::Jobs::Authentication < Rails::Command::Base |
| 2 | + def self.configure |
| 3 | + new.configure |
| 4 | + end |
| 5 | + |
| 6 | + def configure |
| 7 | + if credentials_accessible? |
| 8 | + if authentication_configured? |
| 9 | + say "HTTP Basic Authentication is already configured for `#{Rails.env}`. You can edit it using `credentials:edit`" |
| 10 | + else |
| 11 | + say "Setting up credentials for HTTP Basic Authentication for `#{Rails.env}` environment." |
| 12 | + say "" |
| 13 | + |
| 14 | + username = ask "Enter username: " |
| 15 | + password = SecureRandom.base58(64) |
| 16 | + |
| 17 | + store_credentials(username, password) |
| 18 | + say "Username and password stored in Rails encrypted credentials." |
| 19 | + say "" |
| 20 | + say "You can now access Mission Control – Jobs with: " |
| 21 | + say "" |
| 22 | + say " - Username: #{username}" |
| 23 | + say " - password: #{password}" |
| 24 | + say "" |
| 25 | + say "You can also edit these in the future via `credentials:edit`" |
| 26 | + end |
| 27 | + else |
| 28 | + say "Rails credentials haven't been configured or aren't accessible. Configure them following the instructions in `credentials:help`" |
| 29 | + end |
| 30 | + end |
| 31 | + |
| 32 | + private |
| 33 | + attr_reader :environment |
| 34 | + |
| 35 | + def credentials_accessible? |
| 36 | + credentials.read.present? |
| 37 | + end |
| 38 | + |
| 39 | + def authentication_configured? |
| 40 | + %i[ http_basic_auth_user http_basic_auth_password ].any? do |key| |
| 41 | + credentials.dig(:mission_control, key).present? |
| 42 | + end |
| 43 | + end |
| 44 | + |
| 45 | + def store_credentials(username, password) |
| 46 | + content = credentials.read + "\n" + http_authentication_entry(username, password) + "\n" |
| 47 | + credentials.write(content) |
| 48 | + end |
| 49 | + |
| 50 | + def credentials |
| 51 | + @credentials ||= Rails.application.encrypted(config.content_path, key_path: config.key_path) |
| 52 | + end |
| 53 | + |
| 54 | + def config |
| 55 | + Rails.application.config.credentials |
| 56 | + end |
| 57 | + |
| 58 | + def http_authentication_entry(username, password) |
| 59 | + <<~ENTRY |
| 60 | + mission_control: |
| 61 | + http_basic_auth_user: #{username} |
| 62 | + http_basic_auth_password: #{password} |
| 63 | + ENTRY |
| 64 | + end |
| 65 | +end |
0 commit comments