Created
January 24, 2014 12:56
-
-
Save th3hunt/8596719 to your computer and use it in GitHub Desktop.
Rails API Controller Boilerplate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json_responder' | |
class Api::V1::ApiController < ActionController::Base | |
respond_to :json | |
before_filter :authenticate_user | |
self.responder = JsonResponder | |
rescue_from ActiveRecord::RecordNotFound, with: :not_found | |
rescue_from ActiveModel::MassAssignmentSecurity::Error, with: :bad_request | |
rescue_from AccessForbidden, with: :access_forbidden | |
rescue_from InvalidTransition, with: :invalid_transition | |
def current_user | |
@current_user ||= User.find_by_access_key(access_key) if access_key | |
end | |
private | |
def not_found(exception) | |
render_exception 'missing', exception, status: :not_found | |
end | |
def bad_request(exception) | |
render_exception 'bad_request', exception, status: :bad_request | |
end | |
def access_forbidden(exception) | |
render_exception 'access_forbidden', exception, status: :forbidden | |
end | |
def invalid_transition(exception) | |
render_exception 'invalid_transition', exception, status: :unprocessable_entity | |
end | |
def render_exception(name, exception, opts = {}) | |
render partial: "api/v1/shared/#{name}", status: opts[:status], locals: { exception: exception } | |
end | |
def access_key | |
params[:access_key] || access_key_from_token | |
end | |
# Retrieve the token from the request headers. The authorization headers should | |
# look like Authorization: Token token="a_token" | |
def access_key_from_token | |
ActionController::HttpAuthentication::Token.token_and_options(request).try(:first) | |
end | |
# Respond with the appropriate error if the user is not authorized to access the api | |
def authenticate_user | |
unless current_user | |
headers["WWW-Authenticate"] = 'Token realm="FooBar"' | |
render partial: "api/v1/shared/unauthorized", status: :unauthorized, locals: { token: access_key } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment