Module: APIGuard::HelperMethods

Defined in:
app/api/concerns/api_guard.rb

Instance Method Summary collapse

Instance Method Details

#all_scopesObject


86
87
88
89
90
91
92
93
# File 'app/api/concerns/api_guard.rb', line 86

def all_scopes
  if @all_scopes
    @all_scopes
  else
    @all_scopes = Doorkeeper.configuration.default_scopes.instance_variable_get('@scopes') + Doorkeeper.configuration.optional_scopes.instance_variable_get('@scopes')
    @all_scopes = @all_scopes.map(&:to_sym)
  end
end

#current_access_tokenObject


58
59
60
61
62
63
64
65
66
# File 'app/api/concerns/api_guard.rb', line 58

def current_access_token
  return @access_token if @access_token
  token_string = request.env[Rack::OAuth2::Server::Resource::ACCESS_TOKEN]
  if token_string.blank?
    @access_token = nil
  else
    @access_token = find_access_token(token_string)
  end
end

#current_applicationObject Also known as: current_app


72
73
74
# File 'app/api/concerns/api_guard.rb', line 72

def current_application
  current_access_token.try(:application)
end

#current_resource_ownerObject


68
69
70
# File 'app/api/concerns/api_guard.rb', line 68

def current_resource_owner
  @current_resource_owner ||= User.find(current_access_token.try(:resource_owner_id))
end

#current_userObject


82
83
84
# File 'app/api/concerns/api_guard.rb', line 82

def current_user
  @current_user ||= current_resource_owner
end

#guard!(scopes: []) ⇒ Object

Invokes the doorkeeper guard.

If token string is blank, then it raises MissingTokenError.

If token is presented and valid, then it sets @current_user.

If the token does not have sufficient scopes to cover the requred scopes, then it raises InsufficientTokenScopeError.

If the token is expired, then it raises ExpiredTokenError.

If the token is revoked, then it raises RevokedTokenError.

If the token is not found (nil), then it raises TokenNotFoundError.

Arguments:

scopes: (optional) scopes required for this guard.
        Defaults to empty array.

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/api/concerns/api_guard.rb', line 42

def guard!(scopes: [])
  token_string = request.env[Rack::OAuth2::Server::Resource::ACCESS_TOKEN]
  fail OAuth::MissingTokenError if token_string.blank?
  fail OAuth::TokenNotFoundError if (@access_token ||= find_access_token(token_string)).nil?

  if current_application.present? && current_application.core_app?
    @access_token.scopes = all_scopes.join(' ')
    @scopes = all_scopes
  end

  OAuth::AccessTokenValidationService.validate!(@access_token, scopes: scopes)

  @current_resource_owner = User.find(@access_token.resource_owner_id)
  @current_user = @current_resource_owner
end

#scopesObject


78
79
80
# File 'app/api/concerns/api_guard.rb', line 78

def scopes
  @scopes ||= @access_token.scopes.map(&:to_sym)
end