Skip to content

Instantly share code, notes, and snippets.

@mrrooijen
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrrooijen/38695127b594592868af to your computer and use it in GitHub Desktop.
Save mrrooijen/38695127b594592868af to your computer and use it in GitHub Desktop.
Ember.js + Rails API setup with header-based API key and API version configuration.
class Api::BaseController < ActionController::Base
protect_from_forgery with: :null_session
before_action :unauthorized_if_signed_out
layout false
def current_user
@current_user ||= (
authenticate_or_request_with_http_token do |token, options|
User.find_by(api_key: token)
end
)
rescue
end
private
def unauthorized_if_signed_out
return if !!current_user
render nothing: true, status: :unauthorized
end
end
<!DOCTYPE html>
<html data-api-key="<%= current_user.api_key %>">
<head>
<title>App</title>
<%= stylesheet_link_tag "application", media: "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
</body>
</html>
module Constraints
class Api
ACTIVE_API_VERSIONS = %w[v1]
attr_reader :default, :version
def initialize(options)
@version = "v#{options[:version]}"
@default = options[:default]
end
def matches?(req)
if match = req.headers["Accept"].match(/application\/vnd.myapp.(v[0-9]+)\+json/)
ACTIVE_API_VERSIONS.include?(version) ? version == match[1] : default
else
default
end
end
end
end
App.ApplicationStore = DS.Store.extend()
App.ApplicationAdapter = DS.ActiveModelAdapter.extend
headers:
"Authorization" : "Token token=#{$("html").data("api-key")}"
"Accept" : "application/vnd.myapp.v1+json"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment