Skip to content

Instantly share code, notes, and snippets.

@jCrip
Last active August 29, 2015 14:17
Show Gist options
  • Save jCrip/f51a9be3af51297ba2ee to your computer and use it in GitHub Desktop.
Save jCrip/f51a9be3af51297ba2ee to your computer and use it in GitHub Desktop.
# This one goes to the API file.
before do
next if @resource
@req = ::AuthenticatedRequest.new(
uid: request.headers['Uid'],
token: request.headers['Access-Token'],
client: request.headers['Client'],
resource: @resource
)
@resource = @req.begin
if @resource
env['warden'].set_user(@resource, scope: :user)
else
h = {'Access-Control-Allow-Origin' => "*", 'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")}
error!('Login to use the application', 401, h)
end
end
after do
headers = @req.finish
next if headers.nil?
env['warden'].authenticate(scope: :user)
headers.each{|k,v| header(k,v)}
header 'Access-Control-Allow-Origin', '*'
header 'Access-Control-Request-Method', %w{GET POST OPTIONS}.join(",")
end
# This one goes to lib (and setting up config/application.rb to read lib files)
# or, easier (but not right), to app/lib.
class AuthenticatedRequest
include Devise::Controllers::SignInOut
attr_accessor :resource
def initialize(opts={})
@uid = opts[:uid]
@token = opts[:token]
@client_id = opts[:client] || 'default'
resource = opts[:resource]
end
def begin
return resource if resource
return nil if @token.nil? || @uid.nil?
user = User.find_by_uid(@uid)
@resource = nil
@resource = user if user && user.valid_token?(@token, @client_id)
return resource
end
def finish
return nil unless resource && resource.valid? && @client_id
@resource.with_lock do
auth_headers = {}
if @is_batch_request
auth_headers = resource.extend_batch_buffer(@token, @client_id)
else
auth_headers = resource.create_new_auth_token(@client_id)
end
return auth_headers
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment