Class: ApiKeys::Generators::AddRestrictionsGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Includes:
ActiveRecord::Generators::Migration
Defined in:
lib/generators/api_keys/add_restrictions_generator.rb

Overview

Rails generator for adding the restrictions column to the api_keys table. This generator is for existing installations that want to lock keys to specific web origins or IP addresses. New installs get the column from the install generator, so they never need to run this.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.next_migration_number(dirname) ⇒ Object

Implement the required interface for Rails::Generators::Migration.



18
19
20
21
# File 'lib/generators/api_keys/add_restrictions_generator.rb', line 18

def self.next_migration_number(dirname)
  next_migration_number = current_migration_number(dirname) + 1
  ActiveRecord::Migration.next_migration_number(next_migration_number)
end

Instance Method Details

#create_migration_fileObject

Creates the migration file using the template.



24
25
26
27
# File 'lib/generators/api_keys/add_restrictions_generator.rb', line 24

def create_migration_file
  migration_template "add_restrictions_to_api_keys.rb.erb",
                     File.join(db_migrate_path, "add_restrictions_to_api_keys.rb")
end

#display_post_install_messageObject

Displays helpful information to the user after installation.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/generators/api_keys/add_restrictions_generator.rb', line 30

def display_post_install_message
  say "\n🌐 Request restrictions migration created!", :green
  say "\nNext steps:"
  say "  1. Run `rails db:migrate` to add the restrictions column."
  say "\n  2. Lock a key to the places it may be used from:"
  say "       user.create_api_key!(name: 'Widget key', allowed_origins: 'example.com, *.example.com')"
  say "       key.allowed_ips = '203.0.113.7, 10.0.0.0/8'"
  say "\n     Keys without restrictions keep working from anywhere; presence is the toggle."
  say "\n  3. Optionally cap which restriction kinds each key type may carry:"
  say "       config.key_types = {"
  say "         publishable: { prefix: 'pk', permissions: %w[read], public: true,"
  say "                        restrictions: [:origins] },"
  say "         secret:      { prefix: 'sk', permissions: :all, restrictions: [:ips] }"
  say "       }"
  say "\n  4. Behind a CDN or proxy, make sure the client IP is truthful:"
  say "       config.action_dispatch.trusted_proxies = ..."
  say "       # Trust a vendor header only when ingress blocks requests that bypass that vendor."
  say "\nSee the api_keys README for detailed usage and examples.", :cyan
end