Skip to content

Instantly share code, notes, and snippets.

@izelnakri
Created February 19, 2016 12:59
Show Gist options
  • Select an option

  • Save izelnakri/656bcab95a5526e48da7 to your computer and use it in GitHub Desktop.

Select an option

Save izelnakri/656bcab95a5526e48da7 to your computer and use it in GitHub Desktop.
class APIController < ActionController::API
include ActionController::HttpAuthentication::Token
include ActiveSupport::SecurityUtils
rescue_from ActiveRecord::RecordNotFound, with: :not_found
def not_found
api_error(status: 404, errors: 'Not found')
end
def api_error(status: 500, errors: [])
return render status: :unprocessable_entity if errors.empty?
unless Rails.env.production?
logger.info errors
logger.warn errors.full_messages if errors.respond_to? :full_messages
end
render json: { errors: errors.as_json }, status: status
end
protected
def authenticate
authenticate_user! || render_unauthorized
end
def authenticate_user!
token, options = token_and_options(request)
return false unless token || options
@user = User.find_by(email: options[:email])
if @user && secure_compare(@user.authentication_token, token)
@current_user = @user
else
render_unauthorized
end
end
def render_unauthorized
headers['WWW-Authenticate'] = 'Token realm="Application"'
api_error(status: 401, errors: 'Unauthorized Access Request')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment