Class: GrapeSimpleAuth::Oauth2

Inherits:
Grape::Middleware::Base
  • Object
show all
Defined in:
lib/grape_simple_auth/oauth2.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#auth_strategyObject (readonly)

Returns the value of attribute auth_strategy.



5
6
7
# File 'lib/grape_simple_auth/oauth2.rb', line 5

def auth_strategy
  @auth_strategy
end

Instance Method Details

#auth_scopesObject



36
37
38
39
# File 'lib/grape_simple_auth/oauth2.rb', line 36

def auth_scopes
  return *nil unless auth_strategy.has_auth_scopes?
  auth_strategy.auth_scopes
end

#authorize!(*scopes) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/grape_simple_auth/oauth2.rb', line 41

def authorize!(*scopes)
  response = HTTParty.get(GrapeSimpleAuth.verify_url, {query: {access_token: token}})
  if response.code == 200
    scopes = response.parsed_response["data"]["credential"]["scopes"]
    unless auth_strategy.auth_scopes & scopes == auth_strategy.auth_scopes
      raise GrapeSimpleAuth::Errors::InvalidScope
    end
    return response
  end
  raise GrapeSimpleAuth::Errors::InvalidToken
end

#beforeObject

Grape middleware methods



57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/grape_simple_auth/oauth2.rb', line 57

def before
  set_auth_strategy(GrapeSimpleAuth.auth_strategy)
  auth_strategy.api_context = context
  context.extend(GrapeSimpleAuth::AuthMethods)

  context.protected_endpoint = endpoint_protected?
  return unless context.protected_endpoint?

  self.the_request = env
  resp = authorize!(*auth_scopes)
  context.the_access_token = token
  context.current_user = resp.parsed_response["data"]["info"] rescue nil
  context.credentials = resp.parsed_response["data"]["credential"] rescue nil
end

#contextObject



7
8
9
# File 'lib/grape_simple_auth/oauth2.rb', line 7

def context
  env['api.endpoint']
end

#endpoint_protected?Boolean

Authorization control.

Returns:

  • (Boolean)


32
33
34
# File 'lib/grape_simple_auth/oauth2.rb', line 32

def endpoint_protected?
  auth_strategy.endpoint_protected?
end

#requestObject



15
16
17
# File 'lib/grape_simple_auth/oauth2.rb', line 15

def request
  @_the_request
end

#the_request=(env) ⇒ Object



11
12
13
# File 'lib/grape_simple_auth/oauth2.rb', line 11

def the_request=(env)
  @_the_request = ActionDispatch::Request.new(env)
end

#tokenObject



19
20
21
22
23
24
25
# File 'lib/grape_simple_auth/oauth2.rb', line 19

def token
  token = if request.headers["Authorization"].present?
    request.headers["Authorization"].include?("bearer") ? request.headers["Authorization"].try("split", "bearer").try(:last).try(:strip) : request.headers["Authorization"]
  else
    request.parameters["access_token"]
  end
end