Skip to content

Instantly share code, notes, and snippets.

@Agowan
Last active April 21, 2016 09:00
Show Gist options
  • Save Agowan/db1e33549195ca097933ee380bb784dc to your computer and use it in GitHub Desktop.
Save Agowan/db1e33549195ca097933ee380bb784dc to your computer and use it in GitHub Desktop.
class ApiController < ActionController::Metal
include ActionController::HttpAuthentication::Token::ControllerMethods
include AbstractController::Rendering
include ActionController::Rendering
include ActionController::Renderers::All
include ActionController::ForceSSL
include ActionController::StrongParameters
include ActionController::Serialization
include ActiveSupport::Rescuable
include ActionController::Head
include AbstractController::Callbacks
include Authority::Controller
include ActionController::Helpers
before_action :authenticate_user_from_token!
helper_method :current_user
if Rails.env.development? || Rails.env.test?
include ActionController::Instrumentation
ActiveSupport.run_load_hooks(:action_controller, self)
end
def current_user
@current_user
end
private
# constant-time comparison algorithm to prevent timing attacks
def secure_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
def authenticate_user_from_token!
authenticate_or_request_with_http_token do |token, options|
user_email = options[:user_email].presence
user = user_email && User.find_by_email(user_email)
if user && secure_compare(user.authentication_token, token.gsub(/^token=\"/, ''))
@current_user = user
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment