Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Created December 22, 2020 09:33
Show Gist options
  • Save inopinatus/a5fa39f9b70dcd4fb14c5db238c170a6 to your computer and use it in GitHub Desktop.
Save inopinatus/a5fa39f9b70dcd4fb14c5db238c170a6 to your computer and use it in GitHub Desktop.
Injecting route-specific dependencies to avoid controller duplication.
# config/routes.rb
defaults authenticator: UserAuthenticator do
resources :todos
end
scope :api, defaults: { authenticator: APIAuthenticator, format: :json } do
resources :todos
end
# app/lib/user_authenticator.rb
class UserAuthenticator
def initialize(context)
@context = context
end
def let_me_in?
principal.exists?
end
def principal
User.where(id: @context.session[:user_id]).limit(1)
end
end
# app/lib/api_authenticator.rb
class APIAuthenticator
def initialize(context)
@context = context
end
# <your token verification here>
def let_me_in?
bearer_token == 'mAg!cKnUmB3R'
end
def bearer_token
@context.request.headers['Authorization'].dup&.delete_prefix!('Bearer ')
end
end
# app/controllers/concerns/authenticators.rb
module Authenticators
extend ActiveSupport::Concern
included do
before_action :authenticator
end
def authenticator
@_authenticator ||= params.delete(:authenticator).new(self)
end
end
# app/controllers/todos.rb
class TodosController < ActionController::Base
include Authenticators
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment