Class: TinyAuth::Controller

Inherits:
Module
  • Object
show all
Defined in:
lib/tiny_auth/controller.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model:, name: model.model_name.singular) ⇒ Controller

Defines a before action that will authenticate the resource. It also defines methods for accessing the currently authenticated resource.

Examples:

class ApplicationController < ActionController::Base
  include TinyAuth::Controller.new(model: User)

  before_action :authenticate_user

  def index
    if user_signed_in?
      render json: current_user
    else
      head :unauthorized
    end
  end
end

Parameters:

  • model (ActiveRecord::Base)
  • name (Symbol) (defaults to: model.model_name.singular)

    Used to define methods like ‘current_user`



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/tiny_auth/controller.rb', line 33

def initialize(model:, name: model.model_name.singular)
  authenticate = :"authenticate_#{name}"
  current = :"current_#{name}"
  current_ivar = :"@current_#{name}"
  signed_in = :"#{name}_signed_in?"

  attr_reader current

  define_method(signed_in) do
    !send(current).nil?
  end

  define_method(authenticate) do
    token = TinyAuth::Controller.token(request)

    if token
      resource = model.find_by_token(token)
      instance_variable_set(current_ivar, resource)
    end
  end
end

Class Method Details

.token(request) ⇒ String?

Extract a token from a request

Parameters:

  • request (ActionDispatch::HTTP::Request)

Returns:

  • (String, nil)


8
9
10
11
# File 'lib/tiny_auth/controller.rb', line 8

def self.token(request)
  header = request.authorization.to_s
  header[/^Bearer (.*)$/, 1].presence
end