Class: Rack::OAuth

Inherits:
Object
  • Object
show all
Defined in:
lib/rack-oauth.rb

Overview

Rack Middleware for integrating OAuth into your application

Note: this requires that a Rack::Session middleware be enabled

Defined Under Namespace

Modules: Methods

Constant Summary collapse

DEFAULT_OPTIONS =
{
  :login_path    => '/oauth_login',
  :callback_path => '/oauth_callback',
  :redirect_to   => '/oauth_complete',
  :rack_session  => 'rack.session'
}

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, *args) ⇒ OAuth

Returns a new instance of OAuth.



158
159
160
161
162
163
164
165
166
167
168
# File 'lib/rack-oauth.rb', line 158

def initialize app, *args
  @app = app

  options = args.pop
  @name   = args.first || Rack::OAuth.default_instance_name
  
  DEFAULT_OPTIONS.each {|name, value| send "#{name}=", value }
  options.each         {|name, value| send "#{name}=", value } if options

  raise_validation_exception unless valid?
end

Class Attribute Details

.default_instance_nameObject

The name we use for Rack::OAuth instances when a name is not given.

This is ‘default’ by default



84
85
86
# File 'lib/rack-oauth.rb', line 84

def default_instance_name
  @default_instance_name
end

.test_mode_enabledObject

Set this equal to true to enable ‘test mode’



87
88
89
# File 'lib/rack-oauth.rb', line 87

def test_mode_enabled
  @test_mode_enabled
end

Instance Attribute Details

#callback_pathObject Also known as: callback

the URL that the OAuth provider should callback to after OAuth login is complete



122
123
124
# File 'lib/rack-oauth.rb', line 122

def callback_path
  ::File.join *[@callback_path.to_s, name_unless_default].compact
end

#consumer_keyObject Also known as: key

required

Your OAuth consumer key



138
139
140
# File 'lib/rack-oauth.rb', line 138

def consumer_key
  @consumer_key
end

#consumer_secretObject Also known as: secret

required

Your OAuth consumer secret



143
144
145
# File 'lib/rack-oauth.rb', line 143

def consumer_secret
  @consumer_secret
end

#consumer_siteObject Also known as: site

required

The site you want to request OAuth for, eg. ‘twitter.com



148
149
150
# File 'lib/rack-oauth.rb', line 148

def consumer_site
  @consumer_site
end

#login_pathObject Also known as: login

the URL that should initiate OAuth and redirect to the OAuth provider’s login page



114
115
116
# File 'lib/rack-oauth.rb', line 114

def 
  ::File.join *[@login_path.to_s, name_unless_default].compact
end

#nameObject

an arbitrary name for this instance of Rack::OAuth



153
154
155
# File 'lib/rack-oauth.rb', line 153

def name
  @name.to_s
end

#rack_sessionObject

the name of the Rack env variable used for the session



135
136
137
# File 'lib/rack-oauth.rb', line 135

def rack_session
  @rack_session
end

#redirect_toObject Also known as: redirect

the URL that Rack::OAuth should redirect to after the OAuth has been completed (part of your app)



130
131
132
# File 'lib/rack-oauth.rb', line 130

def redirect_to
  @redirect_to
end

Class Method Details

.all(env) ⇒ Object

Returns all of the Rack::OAuth instances found in this Rack ‘env’ Hash



96
97
98
# File 'lib/rack-oauth.rb', line 96

def self.all env
  env['rack.oauth']
end

.disable_test_modeObject



89
# File 'lib/rack-oauth.rb', line 89

def disable_test_mode() self.test_mode_enabled =  false end

.enable_test_modeObject



88
# File 'lib/rack-oauth.rb', line 88

def enable_test_mode()  self.test_mode_enabled =  true  end

.get(env, name = nil) ⇒ Object

Simple helper to get an instance of Rack::OAuth by name found in this Rack ‘env’ Hash



101
102
103
104
# File 'lib/rack-oauth.rb', line 101

def self.get env, name = nil
  name = Rack::OAuth.default_instance_name if name.nil?
  all(env)[name.to_s]
end

.mock_request(method, path, response = nil) ⇒ Object

Set the response that should be returned when a particular method and path are called.

This is used when Rack::OAuth::test_mode? is true



272
273
274
275
276
277
278
279
280
281
282
# File 'lib/rack-oauth.rb', line 272

def self.mock_request method, path, response = nil
  if method.to_s.start_with?('/')
    response = path
    path     = method
    method   = :get
  end

  @mock_responses ||= {}
  @mock_responses[path] ||= {}
  @mock_responses[path][method] = response
end

.mock_response_for(method, path) ⇒ Object

Returns the mock response, if one has been set via #mock_request, for a method and path.

Raises an exception if the response doesn’t exist because we never want the test environment to actually make real requests!



261
262
263
264
265
266
267
# File 'lib/rack-oauth.rb', line 261

def self.mock_response_for method, path
  unless @mock_responses and @mock_responses[path] and @mock_responses[path][method]
    raise "No mock response created for #{ method.inspect } #{ path.inspect }"
  else
    return @mock_responses[path][method]
  end
end

.test_mode?Boolean

Returns:

  • (Boolean)


90
# File 'lib/rack-oauth.rb', line 90

def test_mode?()             test_mode_enabled == true  end

Instance Method Details

#call(env) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/rack-oauth.rb', line 170

def call env
  # put this instance of Rack::OAuth in the env 
  # so it's accessible from the application
  env['rack.oauth'] ||= {}
  env['rack.oauth'][name] = self

  case env['PATH_INFO']
  
  # find out where to redirect to authorize for this oauth provider 
  # and redirect there.  when the authorization is finished, 
  # the provider will redirect back to our application's callback path
  when 
    (env)

  # the oauth provider has redirected back to us!  we should have a 
  # verifier now that we can use, in combination with out token and 
  # secret, to get an access token for this user
  when callback_path
    do_callback(env)

  else
    @app.call(env)
  end
end

#consumerObject



288
289
290
# File 'lib/rack-oauth.rb', line 288

def consumer
  @consumer ||= ::OAuth::Consumer.new consumer_key, consumer_secret, :site => consumer_site
end

#do_callback(env) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/rack-oauth.rb', line 210

def do_callback env
  # get access token and persist it in the session in a way that we can get it back out later
  request = ::OAuth::RequestToken.new consumer, session(env)[:token], session(env)[:secret]
  set_access_token env, request.get_access_token(:oauth_verifier => Rack::Request.new(env).params['oauth_verifier'])

  # clear out the session variables (won't need these anymore)
  session(env).delete(:token)
  session(env).delete(:secret)

  # we have an access token now ... redirect back to the user's application
  [ 302, { 'Content-Type' => 'text/html', 'Location' => redirect_to }, [] ]
end

#do_login(env) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/rack-oauth.rb', line 195

def  env
  if Rack::OAuth.test_mode?
    set_access_token env, OpenStruct.new(:params => { 'I am a' => 'fake token' })
    return [ 302, { 'Content-Type' => 'text/html', 'Location' => redirect_to }, [] ]
  end

  # get request token and hold onto the token/secret (which we need later to get the access token)
  request = consumer.get_request_token :oauth_callback => ::File.join("http://#{ env['HTTP_HOST'] }", callback_path)
  session(env)[:token]  = request.token
  session(env)[:secret] = request.secret

  # redirect to the oauth provider's authorize url to authorize the user
  [ 302, { 'Content-Type' => 'text/html', 'Location' => request.authorize_url }, [] ]
end

#get_access_token(env) ⇒ Object

See #set_access_token



229
230
231
232
# File 'lib/rack-oauth.rb', line 229

def get_access_token env
  params = session(env)[:access_token_params]
  ::OAuth::AccessToken.from_hash consumer, params if params
end

#get_access_token!(env) ⇒ Object

Same as #get_access_token but it clears the access token info out of the session



235
236
237
238
# File 'lib/rack-oauth.rb', line 235

def get_access_token! env
  params = session(env).delete(:access_token_params)
  ::OAuth::AccessToken.from_hash consumer, params if params
end

#name_unless_defaultObject

Returns the #name of this Rack::OAuth unless the name is ‘default’, in which case it returns nil



322
323
324
# File 'lib/rack-oauth.rb', line 322

def name_unless_default
  name == Rack::OAuth.default_instance_name ? nil : name
end

#raise_validation_exceptionObject



300
301
302
# File 'lib/rack-oauth.rb', line 300

def raise_validation_exception
  raise @errors.join(', ')
end

#request(token, method, path = nil, *args) ⇒ Object

Usage:

request @token, '/account/verify_credentials.json'
request @token, 'GET', '/account/verify_credentials.json'
request @token, :post, '/statuses/update.json', :status => params[:tweet]


246
247
248
249
250
251
252
253
254
255
# File 'lib/rack-oauth.rb', line 246

def request token, method, path = nil, *args
  if method.to_s.start_with?('/')
    path   = method
    method = :get
  end

  return Rack::OAuth.mock_response_for(method, path) if Rack::OAuth.test_mode?

  consumer.request method.to_s.downcase.to_sym, path, token, *args
end

#session(env) ⇒ Object

Returns a hash of session variables, specific to this instance of Rack::OAuth and the end-user

All user-specific variables are stored in the session.

The variables we currently keep track of are:

  • token

  • secret

  • verifier

With all three of these, we can make arbitrary requests to our OAuth provider for this user.



314
315
316
317
318
319
# File 'lib/rack-oauth.rb', line 314

def session env
  raise "Rack env['rack.session'] is nil ... has a Rack::Session middleware be enabled?  " + 
        "use :rack_session for custom key" if env[rack_session].nil?      
  env[rack_session]['rack.oauth']       ||= {}
  env[rack_session]['rack.oauth'][name] ||= {}
end

#set_access_token(env, token) ⇒ Object

Stores the access token in this env’s session in a way that we can get it back out via #get_access_token(env)



224
225
226
# File 'lib/rack-oauth.rb', line 224

def set_access_token env, token
  session(env)[:access_token_params] = token.params
end

#valid?Boolean

Returns:

  • (Boolean)


292
293
294
295
296
297
298
# File 'lib/rack-oauth.rb', line 292

def valid?
  @errors = []
  @errors << ":consumer_key option is required"    unless consumer_key
  @errors << ":consumer_secret option is required" unless consumer_secret
  @errors << ":consumer_site option is required"   unless consumer_site
  @errors.empty?
end

#verified?(env) ⇒ Boolean

Returns:

  • (Boolean)


284
285
286
# File 'lib/rack-oauth.rb', line 284

def verified? env
  [ :token, :secret, :verifier ].all? { |required_session_key| session(env)[required_session_key] }
end