public
Created — forked from ahawkins/api_controller.rb

Basic API style controller for Rails

  • Download Gist
api_controller.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
# A Basic API Controller for Rails
# Handles authentication via Headers, params, and HTTP Auth
# Automatically makes all requests JSON format
#
# Written for production code
# Made public for: http://broadcastingadam.com/2012/03/state_of_rails_apis
#
# Enjoy!
 
class ApiController < ApplicationController
class InvalidAppToken < RuntimeError ; end
class InvalidUserToken < RuntimeError ; end
 
USER_ID_HEADER = 'HTTP_X_USER_ID'
APP_ID_HEADER = 'HTTP_X_APP_ID'
 
respond_to :json
 
rescue_from InvalidUserToken, InvalidAppToken do
render :text => "Could not authenticate user or app", :status => :unauthorized
end
 
rescue_from ::CanCan::AccessDenied do
render :text => "You do not have access to this service", :status => :forbidden
end
 
before_filter :set_default_format
 
def current_user
begin
@current_user ||= User.find(user_id)
rescue Mongoid::Errors::DocumentNotFound
raise InvalidAppToken
end
end
 
def current_app
begin
@current_app ||= current_user.apps.find(app_id)
rescue Mongoid::Errors::DocumentNotFound
raise InvalidUserToken
end
end
 
def current_ability
@current_ability ||= Ability.new current_app
end
 
private
def user_id
if params[:user_id]
params[:user_id]
elsif request.headers[USER_ID_HEADER]
request.headers[USER_ID_HEADER]
else
authenticate_with_http_basic do |user, pass|
user
end
end
end
 
def app_id
if params[:app_id]
params[:app_id]
elsif request.headers[APP_ID_HEADER]
request.headers[APP_ID_HEADER]
else
authenticate_with_http_basic do |user, pass|
pass
end
end
end
 
def set_default_format
request.format = 'json'
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.