module Toll::Controllers::Authenticable

Protected Instance Methods

authenticate!() click to toggle source
# File lib/toll/controllers/authenticable.rb, line 7
def authenticate!
  authenticate_with_token || render_unauthorized
end
authenticate_with_token() click to toggle source
# File lib/toll/controllers/authenticable.rb, line 17
def authenticate_with_token
  authenticate_with_http_token do |token, options|

    user = User.find_by(authentication_keys(options))

    if user && secure_token_compare(user.send(Toll.authentication_token_attribute_name), token)
      @current_user = user
    end
  end
end
authenticated?() click to toggle source
# File lib/toll/controllers/authenticable.rb, line 32
def authenticated?
  current_user.present?
end
current_user() click to toggle source
# File lib/toll/controllers/authenticable.rb, line 28
def current_user
  @current_user
end
render_unauthorized() click to toggle source
# File lib/toll/controllers/authenticable.rb, line 11
def render_unauthorized
  self.headers['WWW-Authenticate'] = 'Token realm="Application"'
  render json: { errors: "Invalid session data" },
    status: :unauthorized
end

Private Instance Methods

authentication_keys(options = {}) click to toggle source
# File lib/toll/controllers/authenticable.rb, line 49
def authentication_keys(options = {})
  {}.tap do |authentication_keys|
    Toll.authentication_keys.each do |key|
      authentication_keys[key] = options[key]
    end
  end
end
secure_token_compare(a, b) click to toggle source

constant-time comparison algorithm to prevent timing attacks Thanks Devise

# File lib/toll/controllers/authenticable.rb, line 40
def secure_token_compare(a, b)
  return false if a.blank? || b.blank? || a.bytesize != b.bytesize
  l = a.unpack "C#{a.bytesize}"

  res = 0
  b.each_byte { |byte| res |= byte ^ l.shift }
  res == 0
end