Skip to content

Commit

Permalink
added grape helper
Browse files Browse the repository at this point in the history
  • Loading branch information
hobofan committed Feb 20, 2015
1 parent db9c00f commit 839cc5f
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 2 deletions.
59 changes: 59 additions & 0 deletions lib/doorkeeper/grape/helpers.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
module Doorkeeper
module Grape
module Helpers
extend ActiveSupport::Concern

included do
helpers do
def doorkeeper_token
@_doorkeeper_token ||= OAuth::Token.authenticate request, *Doorkeeper.configuration.access_token_methods
end

def valid_doorkeeper_token?(*scopes)
doorkeeper_token && doorkeeper_token.acceptable?(scopes)
end

# endpoint specific scopes > parameter scopes > default scopes
def doorkeeper_authorize!(*scopes)
endpoint_scopes = env['api.endpoint'].options[:route_options][:scopes]
scope_string = Doorkeeper::OAuth::Scopes.from_array(scopes).all.inspect if scopes && !scopes.empty?
scope_string = Doorkeeper::OAuth::Scopes.from_array(endpoint_scopes).all.inspect if endpoint_scopes
scopes = Array.wrap(scope_string) if scope_string
scopes = Doorkeeper.configuration.default_scopes if scopes.empty?

unless valid_doorkeeper_token?(*scopes)
if !doorkeeper_token || !doorkeeper_token.accessible?
error = OAuth::InvalidTokenResponse.from_access_token(doorkeeper_token)
options = doorkeeper_unauthorized_render_options
else
error = OAuth::ForbiddenTokenResponse.from_scopes(scopes)
options = doorkeeper_forbidden_render_options
end
headers.merge!(error.headers.reject { |k| ['Content-Type'].include? k })
doorkeeper_error_renderer(error, options)
end
end

def doorkeeper_unauthorized_render_options
nil
end

def doorkeeper_forbidden_render_options
nil
end

def doorkeeper_error_renderer(error, options = {})
status_code = case error.status
when :unauthorized
401
when :forbidden
403
end

error!({ error: error.description }, status_code)
end
end
end
end
end
end
12 changes: 10 additions & 2 deletions lib/doorkeeper/oauth/token.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,19 @@ module OAuth
class Token
module Methods
def from_access_token_param(request)
request.parameters[:access_token]
if request.respond_to?(:parameters)
request.parameters[:access_token]
elsif request.respond_to?(:params)
request.params[:access_token]
end
end

def from_bearer_param(request)
request.parameters[:bearer_token]
if request.respond_to?(:parameters)
request.parameters[:bearer_token]
elsif request.respond_to?(:params)
request.params[:bearer_token]
end
end

def from_bearer_authorization(request)
Expand Down

0 comments on commit 839cc5f

Please sign in to comment.