Last active
August 29, 2015 14:05
-
-
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.
This file contains 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
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 |
This file contains 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
<!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> |
This file contains 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
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 | |
This file contains 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
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