Class: Grape::Middleware::Auth::OAuth2

Inherits:
Base
  • Object
show all
Defined in:
lib/grape/middleware/auth/oauth2.rb

Instance Attribute Summary

Attributes inherited from Base

#app, #env, #options

Instance Method Summary collapse

Methods inherited from Base

#after, #call, #call!, #initialize, #request, #response

Constructor Details

This class inherits a constructor from Grape::Middleware::Base

Instance Method Details

#beforeObject



10
11
12
13
14
15
16
# File 'lib/grape/middleware/auth/oauth2.rb', line 10

def before
  if request['oauth_token']
    verify_token(request['oauth_token'])
  elsif env['Authorization'] && t = parse_authorization_header
    verify_token(t)
  end
end

#default_optionsObject



3
4
5
6
7
8
# File 'lib/grape/middleware/auth/oauth2.rb', line 3

def default_options
  {
    :token_class => 'AccessToken',
    :realm => 'OAuth API'
  }
end

#error_out(status, error) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/grape/middleware/auth/oauth2.rb', line 44

def error_out(status, error)
  throw :error, {
    :message => 'The token provided has expired.',
    :status => status,
    :headers => {
      'WWW-Authenticate' => "OAuth realm='#{options[:realm]}', error='#{error}'"
    }
  }
end

#parse_authorization_headerObject



38
39
40
41
42
# File 'lib/grape/middleware/auth/oauth2.rb', line 38

def parse_authorization_header
  if env['Authorization'] =~ /oauth (.*)/i
    $1
  end
end

#token_classObject



18
19
20
# File 'lib/grape/middleware/auth/oauth2.rb', line 18

def token_class
  @klass ||= eval(options[:token_class])
end

#verify_token(token) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/grape/middleware/auth/oauth2.rb', line 22

def verify_token(token)
  if token = token_class.verify(token)
    if token.expired?
      error_out(401, 'expired_token')
    else
      if token.permission_for?(env)
        env['api.token'] = token
      else
        error_out(403, 'insufficient_scope')
      end
    end
  else
    error_out(401, 'invalid_token')
  end
end