Sha256: eff2d764873ab02c987b817e74ce14b8cd8b241a9be0b3cb13486252b6f4c987

Contents?: true

Size: 1.24 KB

Versions: 6

Compression:

Stored size: 1.24 KB

Contents

module Grape::Middleware::Auth
  class OAuth2 < Grape::Middleware::Base
    def default_options
      {
        :token_class => 'AccessToken',
        :realm => 'OAuth API'
      }
    end
    
    def before
      if request['oauth_token']
        verify_token(request['oauth_token'])
      elsif env['Authorization'] && t = parse_authorization_header
        verify_token(t)
      end
    end
    
    def token_class
      @klass ||= eval(options[:token_class])
    end
    
    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
    
    def parse_authorization_header
      if env['Authorization'] =~ /oauth (.*)/i
        $1
      end
    end
    
    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
  end
end
    

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
grape-0.1.4 lib/grape/middleware/auth/oauth2.rb
grape-0.1.3 lib/grape/middleware/auth/oauth2.rb
grape-0.1.1 lib/grape/middleware/auth/oauth2.rb
grape-0.1.0 lib/grape/middleware/auth/oauth2.rb
grape-0.0.0.alpha.2 lib/grape/middleware/auth/oauth2.rb
grape-0.0.0.alpha.1 lib/grape/middleware/auth/oauth2.rb