Class: LcpRuby::Generators::InstallAuthGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Includes:
ActiveRecord::Generators::Migration, FormatSupport
Defined in:
lib/generators/lcp_ruby/install_auth_generator.rb

Constant Summary collapse

VALID_MODES =
%w[built_in oidc].freeze
VALID_PROVIDERS =
%w[entra google okta keycloak generic].freeze

Constants included from FormatSupport

FormatSupport::VALID_FORMATS

Instance Method Summary collapse

Methods included from FormatSupport

included, #validate_format

Instance Method Details

#activate_user_menu_in_menu_ymlObject

Idempotent: marker block is consumed on first run; absence on re-run (or in customized files) is a silent no-op.



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/generators/lcp_ruby/install_auth_generator.rb', line 185

def activate_user_menu_in_menu_yml
  return unless devise_used?

  menu_path = "config/lcp_ruby/menu.yml"
  full_path = File.join(destination_root, menu_path)
  return unless File.exist?(full_path)

  unless File.read(full_path).match?(USER_MENU_BLOCK_RE)
    say_status :skip, "#{menu_path} (user-menu marker block not found)"
    return
  end

  # Replacement preserves the `# lcp:menu top` insertion marker so
  # `rails g lcp_ruby:entity ... --menu=ROOT|<Label>` keeps working
  # after install_auth runs (D7 entity-gen --menu flag). The marker
  # lands at the bottom of top_menu, mirroring the install template.
  #
  # Indentation: `top_menu:` lives at the 2-space indent under the
  # top-level `menu:` key — same level as the matched LCP_USER_MENU_BLOCK
  # sentinels. Plain `<<-YAML` (non-dedenting) keeps the leading 2 spaces.
  gsub_file menu_path, USER_MENU_BLOCK_RE, <<-YAML
  top_menu:
    - render: lcp_ruby/user_menu
render_panel: lcp_ruby/user_menu_panel
position: right
aria_label: "User menu"
children:
  # Add `presenter: my_settings, alias: me, action: edit`
  # once you ship a my_settings presenter (see
  # docs/design/my_settings_on_user.md). For impersonate
  # entries, wire up host-side routes first and gate them
  # with service: current_user_role / impersonating.

  - url: "{lcp_ruby.destroy_user_session_path}"
    method: delete
    label: "Sign out"
    icon: log-out
    # lcp:menu top  # entity generator marker - do not edit/delete
  YAML
end

#add_devise_initializerObject



100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/generators/lcp_ruby/install_auth_generator.rb', line 100

def add_devise_initializer
  return unless devise_used?
  return if File.exist?(File.join(destination_root, "config", "initializers", "devise.rb"))

  create_file "config/initializers/devise.rb", <<~RUBY
    # frozen_string_literal: true

    # Devise secret key — required for production.
    # Generate with: rails secret
    # Devise.secret_key = ENV["DEVISE_SECRET_KEY"]
  RUBY
end

#copy_user_metadata_modelObject

Writes the LCP metadata model file that exposes ‘LcpRuby::User` to LCP-side concerns (presenters, `belongs_to :user, model: :user`, permission scopes referencing user fields). Idempotent — skips when the file already exists, so configurators who pre-customised `user.rb` keep their version on re-run.

Replaces the buggy ‘copy_user_model_if_absent` previously hand-rolled in `api_tokens_generator` (which bound to `::User`, mismatching `user_class = “LcpRuby::User”` after install_auth).



90
91
92
93
94
95
96
97
98
# File 'lib/generators/lcp_ruby/install_auth_generator.rb', line 90

def 
  dsl_path  = File.join(destination_root, "config/lcp_ruby/models/user.rb")
  yaml_path = File.join(destination_root, "config/lcp_ruby/models/user.yml")
  return if File.exist?(dsl_path) || File.exist?(yaml_path)

  copy_dsl_or_yaml "install_auth/user.rb",
    dsl_target:  "config/lcp_ruby/models/user.rb",
    yaml_target: "config/lcp_ruby/models/user.yml"
end

#create_users_migrationObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/generators/lcp_ruby/install_auth_generator.rb', line 52

def create_users_migration
  # When the host already has the lcp_ruby_users table (typical: ran
  # `--mode=built_in` first, now adding `--mode=oidc`), skip the create
  # migration and emit a smaller add-columns migration instead. The
  # detection runs against the host's schema.rb / structure.sql so it
  # works without a live DB connection.
  if auth_mode == "oidc" && lcp_ruby_users_table_exists?
    migration_template(
      "add_oidc_columns_to_lcp_ruby_users.rb.erb",
      "db/migrate/add_oidc_columns_to_lcp_ruby_users.rb"
    )
  else
    migration_template(
      "create_lcp_ruby_users.rb.erb",
      "db/migrate/create_lcp_ruby_users.rb"
    )
  end
end

#remove_current_user_stubObject



71
72
73
74
75
76
77
78
79
# File 'lib/generators/lcp_ruby/install_auth_generator.rb', line 71

def remove_current_user_stub
  controller_path = "app/controllers/application_controller.rb"
  full_path = File.join(destination_root, controller_path)
  return unless File.exist?(full_path)

  gsub_file controller_path,
    /^[ \t]*# TODO: Replace with real authentication.*?helper_method :current_user\r?\n/m,
    ""
end

#show_post_install_messageObject



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/generators/lcp_ruby/install_auth_generator.rb', line 226

def show_post_install_message
  say ""
  say "LCP Ruby authentication installed (#{auth_mode})!", :green
  say ""
  say "Generated:"
  say "  - db/migrate/*create_lcp_ruby_users.rb (or add_oidc_columns_… for OIDC re-run)"
  say "  - config/lcp_ruby/models/user.#{format_extension} (LCP metadata bound to LcpRuby::User)"
  say ""
  say "Next steps:"
  say "  1. Run migrations:  rails db:migrate"
  if auth_mode == "built_in"
    say "  2. Create admin:    rake lcp_ruby:create_admin EMAIL=admin@example.com PASSWORD=changeme123"
    say "  3. Start server:    rails s"
  else
    step = 2
    say "  #{step}. Set required environment variables (see comments in config/lcp_ruby/auth.yml)"
    show_provider_env_hints
    step += 1
    if options[:with_built_in]
      say "  #{step}. Create break-glass admin:  rake lcp_ruby:create_admin EMAIL=admin@example.com PASSWORD=changeme123"
      step += 1
    end
    say "  #{step}. Review config/lcp_ruby/auth.yml and config/initializers/lcp_ruby.rb"
    say "  #{step + 1}. Restart the app:  rails s"
  end
  
  say ""
end

#update_lcp_ruby_initializerObject



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/generators/lcp_ruby/install_auth_generator.rb', line 126

def update_lcp_ruby_initializer
  initializer_path = "config/initializers/lcp_ruby.rb"
  full_path = File.join(destination_root, initializer_path)

  unless File.exist?(full_path)
    create_file initializer_path, default_initializer_body
    return
  end

  gsub_file initializer_path, /^[ \t]*#[ \t]*config\.authentication\s*=.*\r?\n/, ""

  if File.read(full_path).match?(/^\s*config\.authentication\s*=/)
    gsub_file initializer_path,
              /^(\s*)config\.authentication\s*=\s*\S+/,
              "\\1config.authentication = :#{auth_mode}"
  else
    inject_into_file initializer_path, after: "LcpRuby.configure do |config|\n" do
      "  config.authentication = :#{auth_mode}\n"
    end
  end

  return unless auth_mode == "oidc"

  # Add a host_url placeholder if not already configured. Required for OIDC
  # to build the redirect_uri registered with the IdP.
  unless File.read(full_path).match?(/^\s*config\.host_url\s*=/)
    inject_into_file initializer_path, after: "LcpRuby.configure do |config|\n" do
      <<~RUBY
        # Required for OIDC: absolute base URL of this app, used to build
        # the redirect_uri registered with the identity provider.
          config.host_url = ENV.fetch("LCP_HOST_URL", "http://localhost:3000")
      RUBY
    end
  end

  # Add config.mount_path matching `mount LcpRuby::Engine => "..."` from
  # routes.rb when not already configured. This is the single source of
  # truth for both the OIDC redirect_uri and OmniAuth.config.path_prefix
  # — a mismatch would cause the IdP to reject the round-trip.
  return if File.read(full_path).match?(/^\s*config\.mount_path\s*=/)

  detected = detect_engine_mount_path
  return unless detected

  inject_into_file initializer_path, after: "LcpRuby.configure do |config|\n" do
    <<~RUBY
      # OIDC redirect_uri and OmniAuth path_prefix are derived from this.
      # Must match `mount LcpRuby::Engine => "..."` in config/routes.rb.
        config.mount_path = #{detected.inspect}
    RUBY
  end
end

#validate_optionsObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/generators/lcp_ruby/install_auth_generator.rb', line 35

def validate_options
  # Reject bad values up front. Defaults are applied lazily via the
  # `auth_mode` / `oidc_provider` accessors so per-task specs that drive
  # individual hooks in isolation get the same defaults as a full Thor run.
  validate_format
  unless VALID_MODES.include?(auth_mode)
    raise ArgumentError, "Invalid --mode: #{auth_mode.inspect}. Must be one of: #{VALID_MODES.join(', ')}"
  end

  return unless auth_mode == "oidc"

  unless VALID_PROVIDERS.include?(oidc_provider)
    raise ArgumentError,
          "Invalid --provider: #{oidc_provider.inspect}. Must be one of: #{VALID_PROVIDERS.join(', ')}"
  end
end

#write_auth_ymlObject



113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/generators/lcp_ruby/install_auth_generator.rb', line 113

def write_auth_yml
  return unless auth_mode == "oidc"

  target_path = "config/lcp_ruby/auth.yml"
  full_target = File.join(destination_root, target_path)

  if File.exist?(full_target)
    append_provider_to_existing_auth_yml(target_path)
  else
    template "install_auth/oidc/#{oidc_provider}.yml.erb", target_path
  end
end