class Grape::Knock::Authenticable

Public Class Methods

new(_, options = {}) click to toggle source
Calls superclass method
# File lib/grape/knock/authenticable.rb, line 10
 def initialize(_, options = {})
  super
  define_current_entity_getter entity_class, getter_name
end

Public Instance Methods

before() click to toggle source
# File lib/grape/knock/authenticable.rb, line 19
def before
  authenticate

  memoization_var_name = "@_#{getter_name}"
  context.send(:instance_variable_set, memoization_var_name, send(getter_name))
  context.class.send(:define_method, getter_name) { instance_variable_get memoization_var_name }
end
context() click to toggle source
# File lib/grape/knock/authenticable.rb, line 15
def context
  env['api.endpoint']
end

Private Instance Methods

authenticate() click to toggle source
# File lib/grape/knock/authenticable.rb, line 29
def authenticate
  fail ::Grape::Knock::ForbiddenError unless token
  fail ::Grape::Knock::ForbiddenError unless send(getter_name)
rescue ::JWT::DecodeError
  fail ::Grape::Knock::ForbiddenError
end
define_current_entity_getter(entity_class, getter_name) click to toggle source
# File lib/grape/knock/authenticable.rb, line 36
def define_current_entity_getter(entity_class, getter_name)
  unless self.respond_to?(getter_name)
    memoization_var_name = "@_#{getter_name}"
    self.class.send(:define_method, getter_name) do
      unless instance_variable_defined?(memoization_var_name)
        current =
          begin
            ::Knock::AuthToken.new(token: token).entity_for(entity_class)
          rescue ::Knock.not_found_exception_class, JWT::DecodeError
            nil
          end
        instance_variable_set(memoization_var_name, current)
      end
      instance_variable_get(memoization_var_name)
    end
  end
end
entity_class() click to toggle source
# File lib/grape/knock/authenticable.rb, line 54
def entity_class
  @options[:entity_class] || Object.const_get('User')
end
getter_name() click to toggle source
# File lib/grape/knock/authenticable.rb, line 58
def getter_name
  "current_#{entity_class.to_s.parameterize.underscore}".freeze
end
header_name() click to toggle source
# File lib/grape/knock/authenticable.rb, line 62
def header_name
  (@options[:header_name] || 'HTTP_AUTHORIZATION').freeze
end
token() click to toggle source
# File lib/grape/knock/authenticable.rb, line 66
def token
  env[header_name].to_s.split(' ').last
end