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.



153
154
155
156
157
158
159
160
161
162
163
# File 'lib/rack-oauth.rb', line 153

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



79
80
81
# File 'lib/rack-oauth.rb', line 79

def default_instance_name
  @default_instance_name
end

.test_mode_enabledObject

Set this equal to true to enable ‘test mode’



82
83
84
# File 'lib/rack-oauth.rb', line 82

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



117
118
119
# File 'lib/rack-oauth.rb', line 117

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



133
134
135
# File 'lib/rack-oauth.rb', line 133

def consumer_key
  @consumer_key
end

#consumer_secretObject Also known as: secret

required

Your OAuth consumer secret



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

def consumer_secret
  @consumer_secret
end

#consumer_siteObject Also known as: site

required

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



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

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



109
110
111
# File 'lib/rack-oauth.rb', line 109

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

#nameObject

an arbitrary name for this instance of Rack::OAuth



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

def name
  @name.to_s
end

#rack_sessionObject

the name of the Rack env variable used for the session



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

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)



125
126
127
# File 'lib/rack-oauth.rb', line 125

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



91
92
93
# File 'lib/rack-oauth.rb', line 91

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

.disable_test_modeObject



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

def disable_test_mode() self.test_mode_enabled =  false end

.enable_test_modeObject



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

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



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

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



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

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!



250
251
252
253
254
255
256
# File 'lib/rack-oauth.rb', line 250

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)


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

def test_mode?()             test_mode_enabled == true  end

Instance Method Details

#call(env) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/rack-oauth.rb', line 165

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



277
278
279
# File 'lib/rack-oauth.rb', line 277

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

#do_callback(env) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/rack-oauth.rb', line 205

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



190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/rack-oauth.rb', line 190

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



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

def get_access_token env
  params = session(env)[: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



311
312
313
# File 'lib/rack-oauth.rb', line 311

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

#raise_validation_exceptionObject



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

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]


235
236
237
238
239
240
241
242
243
244
# File 'lib/rack-oauth.rb', line 235

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.



303
304
305
306
307
308
# File 'lib/rack-oauth.rb', line 303

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)



219
220
221
# File 'lib/rack-oauth.rb', line 219

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

#valid?Boolean

Returns:

  • (Boolean)


281
282
283
284
285
286
287
# File 'lib/rack-oauth.rb', line 281

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)


273
274
275
# File 'lib/rack-oauth.rb', line 273

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