### Install Dependencies
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Run this command after checking out the repository to install necessary dependencies for development.
```bash
bin/setup
```
--------------------------------
### Install Gem Locally
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Install the gem onto your local machine after development or testing.
```bash
bundle exec rake install
```
--------------------------------
### Example Custom Owner and Authentication Methods
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Provide example implementations for `current_organization` and `authenticate_organization!` methods in `ApplicationController` when using a custom owner model.
```ruby
class ApplicationController < ActionController::Base
def current_organization
# Your logic to return the current organization
@current_organization ||= Organization.find(session[:organization_id])
end
def authenticate_organization!
redirect_to login_path unless current_organization
end
end
```
--------------------------------
### Add api_keys Gem to Gemfile
Source: https://github.com/rameerez/api_keys/blob/main/README.md
To install the gem, add the following line to your application's Gemfile and run `bundle install`.
```ruby
gem "api_keys"
```
--------------------------------
### Run API Keys Generator and Migration
Source: https://github.com/rameerez/api_keys/blob/main/README.md
After installing the gem, run the generator and database migration to set up the necessary tables and configurations.
```bash
rails g api_keys:install
rails db:migrate
```
--------------------------------
### API Keys Configuration for Multi-tenant Applications
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Example configuration for multi-tenant applications where each tenant or account owns the API keys.
```ruby
config.current_owner_method = :current_account
config.authenticate_owner_method = :authenticate_account!
```
--------------------------------
### Interactive Console
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Start an interactive console session to experiment with the gem's functionality.
```bash
bin/console
```
--------------------------------
### Key Types Mode Configuration Example
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Illustrates how different key types and environments receive distinct prefixes when key types are configured. This follows a Stripe-like convention.
```ruby
# With key_types configured, prefixes come from the type configuration:
# publishable + test → pk_test_abc123...
# secret + live → sk_live_xyz789...
```
--------------------------------
### API Keys Configuration for Organization Ownership
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Example configuration for scenarios where organizations own keys but users manage them.
```ruby
config.current_owner_method = :current_organization
config.authenticate_owner_method = :require_organization_member!
```
--------------------------------
### API Keys Configuration for Team-based Ownership
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Example configuration for scenarios where teams own the API keys.
```ruby
config.current_owner_method = :current_team
config.authenticate_owner_method = :ensure_team_access!
```
--------------------------------
### Manage Key Limits
Source: https://github.com/rameerez/api_keys/blob/main/README.md
The `limit` option restricts the number of keys of a specific type that can exist per owner per environment. This example shows a limit of 1 for publishable keys.
```ruby
# With limit: 1 for publishable keys
user.create_api_key!(key_type: :publishable, environment: :test) # Works
user.create_api_key!(key_type: :publishable, environment: :test) # Raises validation error
# But can have one per environment
user.create_api_key!(key_type: :publishable, environment: :live) # Works
```
--------------------------------
### Get API Key Token Immediately After Creation
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Access the plaintext token of an API key. This is only available directly after the key has been successfully created and can only be shown once.
```ruby
@api_key.token # => "sk_live_abc123..." (plaintext, once only)
```
--------------------------------
### API Key Type and Environment Label Helpers
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Get human-readable labels for API key types (Publishable, Secret) and environments (Test, Live, Default). Also includes boolean checks for key types.
```erb
<%= api_key_type_label(@key) %>
```
```erb
<%= api_key_environment_label(@key) %>
```
```erb
<%= api_key_publishable?(@key) %>
<%= api_key_secret?(@key) %>
```
--------------------------------
### Display Viewable API Key Token
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Get the full API key token if it is a public key type. Returns nil otherwise.
```ruby
@api_key.viewable_token # => full token if public key type, nil otherwise
```
--------------------------------
### Add Key Types Migration
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Generate and run a Rails migration to add new key types to an existing installation. This ensures backwards compatibility for existing keys.
```bash
rails g api_keys:add_key_types
rails db:migrate
```
--------------------------------
### Get Available Scopes for Forms
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Retrieve the list of available scopes for an organization, which can be used to populate forms for API key creation. Falls back to global configuration if not owner-specific.
```ruby
@available_scopes = current_org.available_api_key_scopes
```
--------------------------------
### Get Structured Data for API Key Token Display
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Returns structured data including masked and full token values, viewability status, type, and environment. Useful for building token display UIs.
```erb
<% data = form.api_key_token_data %>
<%= data[:masked] %>
<% if data[:viewable] %>
<% end %>
```
--------------------------------
### API Key Status Helpers
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Get the API key status as a symbol (:active, :expired, :revoked), a human-readable label, or detailed info including color coding for styling.
```erb
<%= api_key_status(@key) %>
```
```erb
<%= api_key_status_label(@key) %>
```
```erb
<% info = api_key_status_info(@key) %>
<%= info[:label] %>
```
--------------------------------
### Configure Authentication Callbacks
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Set up callbacks to execute logic before and after API key authentication. These callbacks are enqueued as asynchronous jobs.
```ruby
config.before_authentication = ->(request) { Rails.logger.info "Authenticating request: #{request.uuid}" }
config.after_authentication = ->(result) { MyAnalytics.track_auth(result) }
```
--------------------------------
### Create API Key with Custom Parameters
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Demonstrates how to programmatically create a new API key for a user, specifying name, scopes, and expiration. The plaintext token is available immediately after creation.
```ruby
@api_key = @user.create_api_key!(
name: "my-key",
scopes: "['read', 'write']",
expires_at: 42.days.from_now
)
# Get the plaintext token only available upon creation
plaintext_token = @api_key.token
# => ak_123abc...
```
--------------------------------
### Create API Key with Options
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Create a new API key for an organization with various configuration options including name, type, scopes, expiration, environment, and metadata. Presets for expiration take precedence over explicit dates.
```ruby
@api_key = current_org.create_api_key!(
name: "My Key",
key_type: :secret, # or :publishable
scopes: ["read", "write"], # Blank values auto-removed
expires_at: 30.days.from_now, # Explicit date
expires_at_preset: "30_days", # OR use preset (takes precedence)
environment: :live, # Defaults to current_environment
metadata: { team: "backend" } # Optional JSON metadata
)
```
--------------------------------
### Configure Sandbox/Live Environment Names
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Customize environment names and their corresponding prefix segments, similar to Stripe's 'test' and 'live' conventions.
```ruby
config.environments = {
sandbox: { prefix_segment: "test" }, # → pk_test_
live: { prefix_segment: "live" } # → pk_live_
}
```
--------------------------------
### Access Public and Secret Keys
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Demonstrates how to create and inspect API keys, checking if they are of a public key type and accessing their viewable token.
```ruby
pk = user.create_api_key!(key_type: :publishable)
pk.public_key_type? # => true
pk.viewable_token # => "pk_test_abc123..." (the full token)
sk = user.create_api_key!(key_type: :secret)
sk.public_key_type? # => false
sk.viewable_token # => nil (not stored)
```
--------------------------------
### Configure Key Types and Environments
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Define different API key types (publishable, secret) with specific prefixes, permissions, and revocability. Configure environments (test, live) and strict isolation.
```ruby
# config/initializers/api_keys.rb
ApiKeys.configure do |config|
config.key_types = {
publishable: {
prefix: "pk", # Token prefix → pk_test_, pk_live_
permissions: %w[read validate],
revocable: false,
limit: 1
},
secret: {
prefix: "sk",
permissions: :all
}
}
config.environments = {
test: { prefix_segment: "test" },
live: { prefix_segment: "live" }
}
config.current_environment = -> { Rails.env.production? ? :live : :test }
config.strict_environment_isolation = true
end
```
--------------------------------
### Make HTTP Request with API Key
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Shows how to include an API key in the 'Authorization' header for making authenticated requests to an API endpoint.
```bash
curl -X GET -H "Authorization: Bearer ak_123abc..." "http://example.com/api/endpoint"
```
--------------------------------
### API Key Environment Helpers from Token
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Extract and display the environment (Test, Live, Default) from a token string. Useful for displaying status on a success page.
```erb
<%= api_key_environment_from_token(@token) %>
```
```erb
<%= api_key_environment_label_from_token(@token) %>
```
--------------------------------
### Run Tests
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Execute the test suite to ensure the gem is functioning correctly. This can be done using Rake commands.
```bash
bundle exec rake test
```
```bash
rake spec
```
--------------------------------
### API Keys Gem Initializer Configuration
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Configure the API Keys gem and include form builder extensions for cleaner forms. Set methods for identifying the current owner and authentication.
```ruby
# Include form builder extensions for cleaner forms
Rails.application.config.to_prepare do
ActionView::Helpers::FormBuilder.include(ApiKeys::FormBuilderExtensions)
end
ApiKeys.configure do |config|
config.current_owner_method = :current_organization
config.authenticate_owner_method = :authenticate_organization!
# ... other config
end
```
--------------------------------
### List All API Keys for a User
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Retrieves all API keys associated with a user record.
```ruby
@user.api_keys
```
--------------------------------
### API Key Type and Environment Checks
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Check the type, environment, and revocability of an API key. Also access metadata like name, creation, expiration, and request counts.
```ruby
@api_key.public_key_type?
@api_key.key_type
@api_key.environment
```
```ruby
@api_key.revoke!
```
```ruby
@api_key.scopes
@api_key.allows_scope?("read")
```
```ruby
@api_key.name
@api_key.created_at
@api_key.expires_at
@api_key.last_used_at
@api_key.requests_count
```
--------------------------------
### Configure Default Token Prefix
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Sets a default prefix for all API keys when key types are not configured. This helps in identifying keys at a glance.
```ruby
config.token_prefix = -> { "myapp_" } # → myapp_abc123...
```
--------------------------------
### Define Global API Key Scopes
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Set default available permissions that will be visible in the API Keys dashboard. This is configured in the gem's initializer file.
```ruby
config.default_scopes = ["read", "write"]
```
--------------------------------
### Configure API Keys Dashboard for Custom Owner Models
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Configure the API keys dashboard in an initializer if API keys belong to a model other than `User`, such as `Organization`.
```ruby
# config/initializers/api_keys.rb
ApiKeys.configure do |config|
# Tell the dashboard how to find the current API key owner
config.current_owner_method = :current_organization
# Tell the dashboard how to ensure the owner is authenticated
config.authenticate_owner_method = :authenticate_organization!
end
```
--------------------------------
### Enable API Key in Query Parameters
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Allows API keys to be passed as a URL query parameter instead of only in the Authorization header. This is not recommended for security reasons.
```ruby
config.query_param = "api_key"
```
--------------------------------
### Customize `has_api_keys` with Options
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Customize the behavior of `has_api_keys` by passing a block to configure options like `max_keys` and `require_name`.
```ruby
class User < ApplicationRecord
has_api_keys do
max_keys 10 # only 10 active API keys per user allowed
require_name true # always require users to set a name for each API key
end
end
```
--------------------------------
### Increase Cache TTL for Performance
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Increases the cache TTL to 2 minutes to boost performance by reducing database hits, at the cost of slower key revocation.
```ruby
config.cache_ttl = 2.minutes # boosts performance at cost of slower revocation
```
--------------------------------
### API Keys Gem Routes Configuration
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Define RESTful routes for API key management within a 'settings' namespace. Includes actions for indexing, creating, editing, revoking, and success callbacks.
```ruby
namespace :settings do
resources :api_keys, only: [:index, :new, :create, :edit, :update] do
post :revoke, on: :member
get :success, on: :collection
post :create_publishable, on: :collection # If using key types
end
end
```
--------------------------------
### Opt-in Form Builder Extensions for API Keys
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Include ApiKeys::FormBuilderExtensions in your initializer to enable custom form builder methods for API keys.
```ruby
Rails.application.config.to_prepare do
ActionView::Helpers::FormBuilder.include(ApiKeys::FormBuilderExtensions)
end
```
--------------------------------
### Include API Keys View Helpers in Application Helper
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Include the API Keys gem's view helpers in your ApplicationHelper to make them available throughout your application. This is a single-line inclusion.
```ruby
module ApplicationHelper
include ApiKeys::ViewHelpers
end
```
--------------------------------
### API Key Expiration Options for Select Dropdowns
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Generate options for expiration dropdowns and parse preset values to dates. Includes options for 'no expiration' and custom presets.
```ruby
ApiKeys::ExpirationOptions.for_select
```
```ruby
ApiKeys::ExpirationOptions.default_value
```
```ruby
ApiKeys::ExpirationOptions.parse("30_days")
ApiKeys::ExpirationOptions.parse("no_expiration")
```
```ruby
ApiKeys::ExpirationOptions.for_select(include_no_expiration: false)
```
--------------------------------
### Mount API Keys Dashboard Engine
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Mount the `ApiKeys::Engine` in your `routes.rb` to provide a self-serve dashboard for users to manage their API keys.
```ruby
mount ApiKeys::Engine => '/settings/api-keys'
```
--------------------------------
### Create Typed API Keys
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Generate API keys of specific types (publishable or secret) for different use cases. Publishable keys are for embedding and have limited permissions.
```ruby
# Create a publishable key (limited permissions, cannot be revoked)
pk = user.create_api_key!(
name: "Production App",
key_type: :publishable,
environment: :live # Optional, defaults to current_environment
)
pk.token # => "pk_live_abc123..."
# Create a secret key (full access)
sk = user.create_api_key!(
name: "Admin Dashboard",
key_type: :secret
)
sk.token # => "sk_test_xyz789..."
```
--------------------------------
### Check if Owner Can Create API Key
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Verify if an organization is allowed to create a new API key, respecting any defined limits. Returns false if the limit for the specified key type has been reached.
```ruby
current_org.can_create_api_key?(key_type: :publishable)
# => false if limit reached
```
--------------------------------
### Include ApiKeys::Controller Concern
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Integrate API key authentication and owner retrieval methods into your controllers. This concern provides `authenticate_api_key!` and `current_api_key_owner`.
```ruby
class ApiController < ApplicationController
include ApiKeys::Controller # provides authenticate_api_key! and current_api_key_owner
end
```
--------------------------------
### Enforce Scope Ceiling for Key Types
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Demonstrates how limited permissions on key types filter requested scopes. Publishable keys only retain allowed scopes.
```ruby
# Publishable keys can only have read/validate permissions
pk = user.create_api_key!(
key_type: :publishable,
scopes: %w[read validate issue_license admin] # Tries to request all
)
pk.scopes # => ["read", "validate"] # Only allowed scopes kept
# Secret keys with permissions: :all keep everything
sk = user.create_api_key!(
key_type: :secret,
scopes: %w[read validate issue_license admin]
)
sk.scopes # => ["read", "validate", "issue_license", "admin"]
```
--------------------------------
### Display Publishable and Secret Keys on Index Page
Source: https://github.com/rameerez/api_keys/blob/main/README.md
Renders the publishable key or a button to create one. Lists secret keys in a table, showing name, masked token, status, and actions like edit and revoke.
```erb
<%# Publishable key section %>
<% if @publishable_key %>
<%= @publishable_key.viewable_token || @publishable_key.masked_token %>
<%= api_key_environment_label(@publishable_key) %> mode
<% else %>
<%= button_to create_publishable_settings_api_keys_path, method: :post do %>
Create Publishable Key
<% end %>
<% end %>
<%# Secret keys table %>
<% @secret_keys.each do |key| %>
<%= key.masked_token %>This key will only be shown once. Copy it now!
<% else %>Token already shown. Create a new key if needed.
<%= link_to "Create New Key", new_settings_api_key_path %> <% end %> ``` -------------------------------- ### Render API Key Expiration Select Dropdown Source: https://github.com/rameerez/api_keys/blob/main/README.md Renders a select dropdown for API key expiration presets. Supports custom CSS classes and default selections. ```erb <%= form.api_key_expiration_select %> ``` ```erb <%= form.api_key_expiration_select(class: "w-full px-4 py-3 border rounded-lg") %> ``` ```erb <%= form.api_key_expiration_select(selected: "30_days") %> ``` -------------------------------- ### Define Per-Model API Key Scopes Source: https://github.com/rameerez/api_keys/blob/main/README.md Override global scope defaults for a specific model. This allows for more granular permissions defined within the `has_api_keys` block. ```ruby class User < ApplicationRecord has_api_keys do max_keys 10 default_scopes %w[read write admin] end end ``` -------------------------------- ### Require API Key Authentication for an Endpoint Source: https://github.com/rameerez/api_keys/blob/main/README.md Enforce that a valid API key must be present to access an endpoint. Returns a 401 Unauthenticated status if no valid key is provided. ```ruby before_action :authenticate_api_key! ``` -------------------------------- ### Change Hashing Strategy to Bcrypt Source: https://github.com/rameerez/api_keys/blob/main/README.md Switches the token hashing algorithm from the default SHA256 to bcrypt for password-grade security. Note that bcrypt is significantly slower than SHA256. ```ruby config.hash_strategy = :bcrypt ``` -------------------------------- ### Render API Key Scopes Checkboxes Source: https://github.com/rameerez/api_keys/blob/main/README.md Renders checkboxes for API key scopes, allowing custom HTML markup within a block. Handles default checked states for new and existing records. ```erb <%= form.api_key_scopes_checkboxes(@available_scopes) do |scope, checked| <% end %> ``` ```erb <%= form.api_key_scopes_checkboxes(@scopes, checked: :none) do |scope, checked| ... <% end %> ``` -------------------------------- ### Rate Limit API Endpoint by API Key ID (Rails 8+) Source: https://github.com/rameerez/api_keys/blob/main/README.md Implement rate limiting for an API endpoint, restricting requests per API key. Requires Rails 8+ and a configured cache store like `solid_cache`. ```ruby before_action -> { authenticate_api_key! }, only: [:rate_limited_action] rate_limit to: 2, within: 10.seconds, by: -> { current_api_key&.id }, # Limit per API key ID with: -> { render json: { error: "rate_limited", message: "Too many requests (max 2 per 10 seconds per key). Please wait." }, status: :too_many_requests }, only: [:rate_limited_action] def rate_limited_action render json: { # Success JSON }, status: :ok end ``` -------------------------------- ### New/Edit API Key Form Source: https://github.com/rameerez/api_keys/blob/main/README.md A form for creating or editing API keys, including fields for name, expiration, and scopes. Uses Rails' form_with helper for form generation. ```erb <%= form_with(model: @api_key, url: settings_api_keys_path) do |form| %> <%# Name %> <%= form.text_field :name, placeholder: "e.g., Production Server" %> <%# Expiration (new keys only) %> <%= form.api_key_expiration_select(class: "form-select") %> <%# Scopes %> <%= form.api_key_scopes_checkboxes(@available_scopes) do |scope, checked| %> <% end %> <%= form.submit %> <% end %> ``` -------------------------------- ### Filter API Keys by Type and Status Source: https://github.com/rameerez/api_keys/blob/main/README.md Use chained methods on the organization's API keys to filter by key type (publishable, secret) and status (active, inactive, expired, revoked). ```ruby @org.api_keys.publishable @org.api_keys.secret @org.api_keys.active @org.api_keys.inactive @org.api_keys.expired @org.api_keys.revoked @org.api_keys.publishable.active @org.api_keys.secret.inactive.order(created_at: :desc) ``` -------------------------------- ### Integrate `has_api_keys` into a Model Source: https://github.com/rameerez/api_keys/blob/main/README.md Add `has_api_keys` to your desired model (e.g., `User`) to enable API key functionality for its records. ```ruby class User < ApplicationRecord has_api_keys end ``` -------------------------------- ### Check API Key Scope Allowance Source: https://github.com/rameerez/api_keys/blob/main/README.md Verify if a given API key has permission to perform a specific action by checking its assigned scopes. Returns a boolean. ```ruby @api_key.allows_scope?("read") # => true ``` -------------------------------- ### Check API Key Status Source: https://github.com/rameerez/api_keys/blob/main/README.md Methods to check if an API key is currently active, expired, or revoked. ```ruby @api_key.active? # => true ``` ```ruby @api_key.expired? # => false ``` ```ruby @api_key.revoked? # => true ``` -------------------------------- ### Display Masked API Key Token Source: https://github.com/rameerez/api_keys/blob/main/README.md Obtain a masked version of the API key token, suitable for display in user interfaces where the full token should not be revealed. ```ruby @api_key.masked_token # => "sk_live_••••abc1" (safe for UI) ``` -------------------------------- ### Access API Key Request Count Source: https://github.com/rameerez/api_keys/blob/main/README.md Retrieve the number of requests made by an API key when the `track_requests_count` option is enabled. Requires a configured Active Job backend. ```ruby @api_key.requests_count # => 4567 ``` -------------------------------- ### Filter API Keys by Status Source: https://github.com/rameerez/api_keys/blob/main/README.md Provides methods to filter API keys based on their status: active, expired, revoked, or inactive (expired or revoked). ```ruby @user.api_keys.active @user.api_keys.expired @user.api_keys.revoked @user.api_keys.inactive # expired or revoked ``` -------------------------------- ### Enforce Environment Isolation Source: https://github.com/rameerez/api_keys/blob/main/README.md When `strict_environment_isolation` is enabled, API keys can only authenticate in their matching environment, preventing accidental cross-environment usage. ```ruby # In production (current_environment returns :live) # A test key will fail authentication with error_code: :environment_mismatch ``` -------------------------------- ### Require Specific Scope for an Endpoint Source: https://github.com/rameerez/api_keys/blob/main/README.md Enforce that an API key must possess a specific scope to access an endpoint. This can be configured directly or using a Proc for `before_action`. ```ruby authenticate_api_key!(scope: "write") ``` ```ruby before_action -> { authenticate_api_key!(scope: "write") }, only: [:write_action] def write_action # We'll only get here if the API key is active AND it has the right scope, so execute the actual logic of the endpoint and return success: render json: { # Your success JSON... }, status: :ok end ``` -------------------------------- ### Access Current API Key Expiration Source: https://github.com/rameerez/api_keys/blob/main/README.md Retrieve the expiration timestamp of the currently authenticated API key. This is useful for displaying key validity information. ```ruby current_api_key.expires_at # => 2025-05-25 05:25:05.250525000 UTC +00:00 ``` -------------------------------- ### Display Masked API Key Source: https://github.com/rameerez/api_keys/blob/main/README.md Generates a masked version of an API key for display purposes in user interfaces, obscuring sensitive parts of the token. ```ruby @api_key.masked_token # => "ak_demo_••••yZn9" ``` -------------------------------- ### Allow Unauthenticated Endpoints Source: https://github.com/rameerez/api_keys/blob/main/README.md Specify endpoints that do not require API key authentication, while still enforcing it on other endpoints within the controller. ```ruby before_action :authenticate_api_key!, except: [:unauthenticated_endpoint] ``` -------------------------------- ### Disable Token Lookup Caching Source: https://github.com/rameerez/api_keys/blob/main/README.md Disables caching of token lookups by setting the cache TTL to 0 seconds. This ensures immediate revocation of keys but impacts performance. ```ruby config.cache_ttl = 0.seconds # disables caching ``` -------------------------------- ### Check if API Key has Expired Source: https://github.com/rameerez/api_keys/blob/main/README.md Check if the expiration date of an API key has passed. ```ruby @api_key.expired? # => true if past expires_at ``` -------------------------------- ### Check if API Key has been Revoked Source: https://github.com/rameerez/api_keys/blob/main/README.md Determine if an API key has been manually revoked. ```ruby @api_key.revoked? # => true if manually revoked ``` -------------------------------- ### Check if API Key is Active Source: https://github.com/rameerez/api_keys/blob/main/README.md Determine if an API key is currently active, meaning it has not been revoked and has not expired. ```ruby @api_key.active? # => true if not revoked and not expired ``` -------------------------------- ### Access Current API Key Owner Source: https://github.com/rameerez/api_keys/blob/main/README.md Retrieve the owner object associated with the current API key. This can be accessed directly via `current_api_key.owner` or the helper method `current_api_key_owner`. ```ruby current_api_key_owner.email # => john.doe@example.com ``` -------------------------------- ### Revoke an API Key Source: https://github.com/rameerez/api_keys/blob/main/README.md Disables an API key, making it inactive and preventing it from performing further actions. ```ruby @api_key.revoke! ``` -------------------------------- ### Override CSS Variables for Dashboard Customization Source: https://github.com/rameerez/api_keys/blob/main/README.md Tweak the appearance of the API keys dashboard by overriding default CSS variables in your application's stylesheet. This allows for easy color and spacing adjustments. ```css :root { --api-keys-primary-color: #your-brand-color; --api-keys-danger-color: #dc3545; --api-keys-success-color: #28a745; --api-keys-badge-secret-bg: #e7f1ff; --api-keys-badge-publishable-bg: #fef3cd; /* See layout file for all available variables */ } ``` -------------------------------- ### Check if API Key is Revocable Source: https://github.com/rameerez/api_keys/blob/main/README.md Check if an API key can be revoked. Returns false for certain non-revocable key types. ```ruby @api_key.revocable? # => false for non-revocable key types ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.