Skip to content

Authorization

alpaca-tc edited this page Jan 7, 2017 · 1 revision

Authorization

Authorization examples

Devise

Allow authenticated administrator.

# config/routes.rb
authenticate :user, ->(user) { user.administrator? } do
  mount AdminScript::Engine => '/admin_scripts'
end

Constraints

# config/routes.rb
constraints PrivateIpConstraint.new do
  mount AdminScript::Engine, at: '/admin_scripts'
end
# lib/private_ip_constraint.rb
class PrivateIpConstraint
  ALLOWED_IP_ADDRESSES = %w(12.34.56.78).freeze # Your private ip address

  def matches?(request)
    ALLOWED_IP_ADDRESSES.include?(request.remote_ip)
  end
end

Controller Filter

Define before_action to authenticate access.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  ALLOWED_IP_ADDRESSES = %w(12.34.56.78).freeze # Your private ip address

  before_action :authenticate_ip_address, unless: -> { Rails.env.development? }

  private

  # Block unknown ip addresses.
  def authenticate_ip_address
    head :forbidden unless ALLOWED_IP_ADDRESSES.include?(request.remote_ip)
  end
end

# config/initializers/admin_script.rb
AdminScript.configure do |config|
  config.parent_controller = 'ApplicationController'
end
Clone this wiki locally