Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.