]> git.openstreetmap.org Git - rails.git/blob - lib/oauth/util.rb
Merge remote-tracking branch 'upstream/pull/6832'
[rails.git] / lib / oauth / util.rb
1 # frozen_string_literal: true
2
3 module Oauth
4   module Util
5     OAUTH_SETTINGS_KEYS = [:id_application, :oauth_application, :oauth_key].freeze
6
7     class ExistingSettingsError < StandardError; end
8
9     def self.register_apps(display_name, generated_by: name, output: $stdout)
10       settings_path = Rails.root.join("config/settings.local.yml")
11
12       check_not_already_registered!(settings_path, :output => output)
13
14       user = User.find_by! :display_name => display_name
15
16       model = Doorkeeper.config.application_model
17
18       id_application = model.create(
19         :name => "Local iD",
20         :redirect_uri => "http://localhost:3000",
21         :scopes => %w[read_prefs write_prefs write_api read_gpx write_gpx write_notes],
22         :confidential => false,
23         :owner => user
24       )
25
26       web_application = model.create(
27         :name => "OpenStreetMap Web Site",
28         :redirect_uri => "http://localhost:3000",
29         :scopes => %w[write_api write_notes],
30         :owner => user
31       )
32
33       File.open settings_path, "a" do |file|
34         file << "\n" if settings_path.exist?
35         file << <<~SETTINGS
36           # generated by #{generated_by}
37           # OAuth 2 Client ID for iD
38           id_application: "#{id_application.uid}"
39           # OAuth 2 Client ID for the web site
40           oauth_application: "#{web_application.uid}"
41           # OAuth 2 Client Secret for the web site
42           oauth_key: "#{web_application.plaintext_secret}"
43         SETTINGS
44       end
45
46       output.puts "Updated settings in #{settings_path}"
47     end
48
49     def self.check_not_already_registered!(path, opts = {})
50       output = opts.fetch(:output, $stdout)
51       already_defined_keys = OAUTH_SETTINGS_KEYS & Settings.keys
52
53       return if already_defined_keys.empty?
54
55       if path.exist?
56         output.puts "The following settings are already defined (likely in #{path}):"
57       else
58         output.puts "The following settings are already defined:"
59       end
60
61       already_defined_keys.each do |key|
62         output.puts "- #{key}"
63       end
64
65       output.puts "Delete or comment them out to regenerate."
66
67       raise ExistingSettingsError
68     end
69   end
70 end