diff --git a/.gitignore b/.gitignore index ae44b2c..275f0fe 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ .powenv tmp bin +example/app.log diff --git a/.travis.yml b/.travis.yml index 5c0f254..618030d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,4 +8,9 @@ - 1.9.2 - 1.9.3 - 2.0.0 + - 2.1 - jruby + - rbx +matrix: + allow_failures: + - rvm: rbx diff --git a/CHANGELOG.md b/CHANGELOG.md index 836f2e1..c9fcd38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## 2.0.0 (2014-08-07) + +Bugfixes: + + - bump omniauth-oauth2 dependency which addresses CVE-2012-6134 (#162, @linedotstar) + ## 1.6.0 (2014-01-13) Features: @@ -55,9 +61,6 @@ - have `raw_info` return an empty hash if the Facebook response returns false (#44, @brianjlandau) - prevent oauth2 from interpreting Facebook's expires field as `expires_in`, when it's really `expires_at` (#39, @watsonbox) - remove deprecated `offline_access` permission (@mkdynamic) - -Changes: - - tidy up the `callback_url` option (@mkdynamic) ## 1.2.0 (2012-01-06) diff --git a/Gemfile b/Gemfile index 08c3acf..2fc94e1 100644 --- a/Gemfile +++ b/Gemfile @@ -2,4 +2,6 @@ gemspec -gem 'jruby-openssl', :platform => :jruby +platforms :rbx do + gem 'rubysl', '~> 2.0' +end diff --git a/README.md b/README.md index 374d105..fad29e1 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,11 @@ -**NOTE: If you're running < 1.5.1, please upgrade to address 2 security vulnerabilities. -More details [here](https://github.com/mkdynamic/omniauth-facebook/wiki/CSRF-vulnerability:-CVE-2013-4562) and [here](https://github.com/mkdynamic/omniauth-facebook/wiki/Access-token-vulnerability:-CVE-2013-4593).** +**IMPORTANT: If you're running < 1.5.1, please upgrade to the latest version to address 3 security vulnerabilities. +More details [here](https://github.com/mkdynamic/omniauth-facebook/wiki/CSRF-vulnerability:-CVE-2013-4562), [here](https://github.com/mkdynamic/omniauth-facebook/wiki/Access-token-vulnerability:-CVE-2013-4593) and [here](http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2012-6134).** --- # OmniAuth Facebook  [![Build Status](https://secure.travis-ci.org/mkdynamic/omniauth-facebook.png?branch=master)](https://travis-ci.org/mkdynamic/omniauth-facebook) + +**These notes are based on master, please see tags for README pertaining to specific releases.** Facebook OAuth2 Strategy for OmniAuth. @@ -37,14 +39,16 @@ You can configure several options, which you pass in to the `provider` method via a `Hash`: -* `scope`: A comma-separated list of permissions you want to request from the user. See the Facebook docs for a full list of available permissions: http://developers.facebook.com/docs/reference/api/permissions. Default: `email` -* `display`: The display context to show the authentication page. Options are: `page`, `popup` and `touch`. Read the Facebook docs for more details: https://developers.facebook.com/docs/reference/dialogs/oauth/. Default: `page` -* `auth_type`: Optionally specifies the requested authentication features as a comma-separated list, as per https://developers.facebook.com/docs/authentication/reauthentication/. -Valid values are `https` (checks for the presence of the secure cookie and asks for re-authentication if it is not present), and `reauthenticate` (asks the user to re-authenticate unconditionally). Default is `nil`. -* `secure_image_url`: Set to `true` to use https for the avatar image url returned in the auth hash. Default is `false`. -* `image_size`: Set the size for the returned image url in the auth hash. Valid options include `square` (50x50), `small` (50 pixels wide, variable height), `normal` (100 pixels wide, variable height), or `large` (about 200 pixels wide, variable height). Additionally, you can request a picture of a specific size by setting this option to a hash with `:width` and `:height` as keys. This will return an available profile picture closest to the requested size and requested aspect ratio. If only `:width` or `:height` is specified, we will return a picture whose width or height is closest to the requested size, respectively. -* `info_fields`: Specify exactly which fields should be returned when getting the user's info. Value should be a comma-separated string as per https://developers.facebook.com/docs/reference/api/user/ (only /me endpoint). -* `locale`: Specify locale which should be used when getting the user's info. Value should be locale string as per https://developers.facebook.com/docs/reference/api/locale/. +Option name | Default | Explanation +--- | --- | --- +`scope` | `email` | A comma-separated list of permissions you want to request from the user. See the Facebook docs for a full list of available permissions: https://developers.facebook.com/docs/reference/login/ +`display` | `page` | The display context to show the authentication page. Options are: `page`, `popup` and `touch`. Read the Facebook docs for more details: https://developers.facebook.com/docs/reference/dialogs/oauth/ +`image_size` | `square` | Set the size for the returned image url in the auth hash. Valid options include `square` (50x50), `small` (50 pixels wide, variable height), `normal` (100 pixels wide, variable height), or `large` (about 200 pixels wide, variable height). Additionally, you can request a picture of a specific size by setting this option to a hash with `:width` and `:height` as keys. This will return an available profile picture closest to the requested size and requested aspect ratio. If only `:width` or `:height` is specified, we will return a picture whose width or height is closest to the requested size, respectively. +`info_fields` | | Specify exactly which fields should be returned when getting the user's info. Value should be a comma-separated string as per https://developers.facebook.com/docs/graph-api/reference/user/ (only `/me` endpoint). +`locale` | | Specify locale which should be used when getting the user's info. Value should be locale string as per https://developers.facebook.com/docs/reference/api/locale/. +`auth_type` | | Optionally specifies the requested authentication features as a comma-separated list, as per https://developers.facebook.com/docs/facebook-login/reauthentication/. Valid values are `https` (checks for the presence of the secure cookie and asks for re-authentication if it is not present), and `reauthenticate` (asks the user to re-authenticate unconditionally). Default is `nil`. +`secure_image_url` | `false` | Set to `true` to use https for the avatar image url returned in the auth hash. +`callback_url` / `callback_path` | | Specify a custom callback URL used during the server-side flow. Note this must be allowed by your app configuration on Facebook (see 'Valid OAuth redirect URIs' under the 'Advanced' settings section in the configuration for your Facebook app for more details). For example, to request `email`, `user_birthday` and `read_stream` permissions and display the authentication page in a popup window: @@ -58,10 +62,6 @@ ### Per-Request Options If you want to set the `display` format, `auth_type`, or `scope` on a per-request basis, you can just pass it to the OmniAuth request phase URL, for example: `/auth/facebook?display=popup` or `/auth/facebook?scope=email`. - -### Custom Callback URL/Path - -You can set a custom `callback_url` or `callback_path` option to override the default value. See [OmniAuth::Strategy#callback_url](https://github.com/intridea/omniauth/blob/master/lib/omniauth/strategy.rb#L411) for more details on the default. ## Auth Hash @@ -109,13 +109,13 @@ The precise information available may depend on the permissions which you request. -## Client-side Flow +## Client-side Flow with Facebook Javascript SDK You can use the Facebook Javascript SDK with `FB.login`, and just hit the callback endpoint (`/auth/facebook/callback` by default) once the user has authenticated in the success callback. -Note that you must enable cookies in the `FB.init` config for this process to work. +**Note that you must enable cookies in the `FB.init` config for this process to work.** -See the example Sinatra app under `example/` and read the [Facebook docs on Client-Side Authentication](https://developers.facebook.com/docs/authentication/client-side/) for more details. +See the example Sinatra app under `example/` and read the [Facebook docs on Login for JavaScript](https://developers.facebook.com/docs/facebook-login/login-flow-for-web/) for more details. ### How it Works @@ -127,53 +127,31 @@ 2. extract the authorization code contained in it 3. and hit Facebook and obtain an access token which will get placed in the `request.env['omniauth.auth']['credentials']` hash. -Note that this access token will be the same token obtained and available in the client through the hash [as detailed in the Facebook docs](https://developers.facebook.com/docs/authentication/client-side/). - -## Canvas Apps - -Canvas apps will send a signed request with the initial POST, therefore you *can* (if it makes sense for your app) pass this to the authorize endpoint (`/auth/facebook` by default) in the querystring. - -There are then 2 scenarios for what happens next: - -1. A user has already granted access to your app, this will contain an access token. In this case, omniauth-facebook will skip asking the user for authentication and immediately redirect to the callback endpoint (`/auth/facebook/callback` by default) with the access token present in the `request.env['omniauth.auth']['credentials']` hash. - -2. A user has not granted access to your app, and the signed request *will not* contain an access token. In this case omniauth-facebook will simply follow the standard auth flow. - -Take a look at [the example Sinatra app for one option of how you can integrate with a canvas page](https://github.com/mkdynamic/omniauth-facebook/blob/master/example/config.ru). - -Bear in mind you have several [options](https://developers.facebook.com/docs/opengraph/authentication). Read [the Facebook docs on canvas page authentication](https://developers.facebook.com/docs/authentication/canvas/) for more info. - ## Token Expiry -Since Facebook deprecated the `offline_access` permission, this has become more complex. The expiration time of the access token you obtain will depend on which flow you are using. See below for more details. +The expiration time of the access token you obtain will depend on which flow you are using. ### Client-Side Flow If you use the client-side flow, Facebook will give you back a short lived access token (~ 2 hours). -You can exchange this short lived access token for a longer lived version. Read the [Facebook docs about the offline_access deprecation](https://developers.facebook.com/roadmap/offline-access-removal/) for more information. +You can exchange this short lived access token for a longer lived version. Read the [Facebook docs](https://developers.facebook.com/docs/facebook-login/access-tokens/) for more information on exchanging a short lived token for a long lived token. ### Server-Side Flow If you use the server-side flow, Facebook will give you back a longer lived access token (~ 60 days). -If you're having issue getting a long lived token with the server-side flow, make sure to enable the 'deprecate offline_access setting' in you Facebook app config. Read the [Facebook docs about the offline_access deprecation](https://developers.facebook.com/roadmap/offline-access-removal/) for more information. - ## Supported Rubies Actively tested with the following Ruby versions: +- MRI 2.1.0 - MRI 2.0.0 - MRI 1.9.3 - MRI 1.9.2 - MRI 1.8.7 -- JRuby 1.7.4 - -*NB.* For JRuby < 1.7, you'll need to install the `jruby-openssl` gem. There's no way to automatically specify this in a Rubygem gemspec, so you need to manually add it your project's own Gemfile: - -```ruby -gem 'jruby-openssl', :platform => :jruby -``` +- JRuby 1.7.9 +- Rubinius (latest stable) ## License @@ -184,3 +162,7 @@ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/mkdynamic/omniauth-facebook/trend.png)](https://bitdeli.com/free "Bitdeli Badge") + diff --git a/checksums.yaml.gz b/checksums.yaml.gz index 63fad67..b2d7cd2 100644 Binary files a/checksums.yaml.gz and b/checksums.yaml.gz differ diff --git a/example/Gemfile b/example/Gemfile index 9962447..443d6a2 100644 --- a/example/Gemfile +++ b/example/Gemfile @@ -1,4 +1,5 @@ source 'https://rubygems.org' gem 'sinatra' +gem 'sinatra-reloader' gem 'omniauth-facebook', :path => '../' diff --git a/example/Gemfile.lock b/example/Gemfile.lock index 50f5617..2447291 100644 --- a/example/Gemfile.lock +++ b/example/Gemfile.lock @@ -1,39 +1,53 @@ PATH remote: ../ specs: - omniauth-facebook (1.6.0.rc1) + omniauth-facebook (2.0.0.pre1) omniauth-oauth2 (~> 1.1) GEM remote: https://rubygems.org/ specs: - faraday (0.8.8) - multipart-post (~> 1.2.0) - hashie (2.0.5) - httpauth (0.2.0) - jwt (0.1.8) + backports (3.3.5) + faraday (0.9.0) + multipart-post (>= 1.2, < 3) + hashie (2.1.1) + jwt (0.1.13) multi_json (>= 1.5) multi_json (1.8.2) - multipart-post (1.2.0) - oauth2 (0.8.1) - faraday (~> 0.8) - httpauth (~> 0.1) - jwt (~> 0.1.4) - multi_json (~> 1.0) + multi_xml (0.5.5) + multipart-post (2.0.0) + oauth2 (0.9.3) + faraday (>= 0.8, < 0.10) + jwt (~> 0.1.8) + multi_json (~> 1.3) + multi_xml (~> 0.5) rack (~> 1.2) - omniauth (1.1.4) + omniauth (1.2.1) hashie (>= 1.2, < 3) - rack - omniauth-oauth2 (1.1.1) - oauth2 (~> 0.8.0) - omniauth (~> 1.0) + rack (~> 1.0) + omniauth-oauth2 (1.1.2) + faraday (>= 0.8, < 0.10) + multi_json (~> 1.3) + oauth2 (~> 0.9.3) + omniauth (~> 1.2) rack (1.5.2) rack-protection (1.5.1) rack + rack-test (0.6.2) + rack (>= 1.0) sinatra (1.4.4) rack (~> 1.4) rack-protection (~> 1.4) tilt (~> 1.3, >= 1.3.4) + sinatra-contrib (1.4.2) + backports (>= 2.0) + multi_json + rack-protection + rack-test + sinatra (~> 1.4.0) + tilt (~> 1.3) + sinatra-reloader (1.0) + sinatra-contrib tilt (1.4.1) PLATFORMS @@ -42,3 +56,4 @@ DEPENDENCIES omniauth-facebook! sinatra + sinatra-reloader diff --git a/example/app.rb b/example/app.rb new file mode 100644 index 0000000..a078746 --- /dev/null +++ b/example/app.rb @@ -0,0 +1,93 @@ +require 'sinatra' +require "sinatra/reloader" +require 'yaml' + +# configure sinatra +set :run, false +set :raise_errors, true + +# setup logging to file +log = File.new("app.log", "a+") +$stdout.reopen(log) +$stderr.reopen(log) +$stderr.sync = true +$stdout.sync = true + +# server-side flow +get '/server-side' do + # NOTE: You would just hit this endpoint directly from the browser in a real app. The redirect is just here to + # explicit declare this server-side flow. + redirect '/auth/facebook' +end + +# client-side flow +get '/client-side' do + content_type 'text/html' + # NOTE: When you enable cookie below in the FB.init call the GET request in the FB.login callback will send a signed + # request in a cookie back the OmniAuth callback which will parse out the authorization code and obtain an + # access_token with it. + <<-END + + + Client-side Flow Example + + + +
+ + + +

+ Connect to FB! +

+ +

+ + + END +end + +get '/auth/:provider/callback' do + content_type 'application/json' + MultiJson.encode(request.env) +end + +get '/auth/failure' do + content_type 'application/json' + MultiJson.encode(request.env) +end diff --git a/example/config.ru b/example/config.ru index 267f392..17f0760 100644 --- a/example/config.ru +++ b/example/config.ru @@ -1,110 +1,11 @@ require 'bundler/setup' -require 'sinatra/base' require 'omniauth-facebook' +require './app.rb' -SCOPE = 'email,read_stream' +use Rack::Session::Cookie, :secret => 'abc123' -class App < Sinatra::Base - # turn off sinatra default X-Frame-Options for FB canvas - set :protection, :except => :frame_options - - # server-side flow - get '/' do - # NOTE: you would just hit this endpoint directly from the browser - # in a real app. the redirect is just here to setup the root - # path in this example sinatra app. - redirect '/auth/facebook' - end - - # client-side flow - get '/client-side' do - content_type 'text/html' - # NOTE: when you enable cookie below in the FB.init call - # the GET request in the FB.login callback will send - # a signed request in a cookie back the OmniAuth callback - # which will parse out the authorization code and obtain - # the access_token. This will be the exact same access_token - # returned to the client in response.authResponse.accessToken. - <<-END - - - Client-side Flow Example - - - -

- - - -

- Connect to FB -

- -

- - - END - end - - # auth via FB canvas and signed request param - post '/canvas/' do - # we just redirect to /auth/facebook here which will parse the - # signed_request FB sends us, asking for auth if the user has - # not already granted access, or simply moving straight to the - # callback where they have already granted access. - redirect "/auth/facebook?signed_request=#{request.params['signed_request']}" - end - - get '/auth/:provider/callback' do - content_type 'application/json' - MultiJson.encode(request.env) - end - - get '/auth/failure' do - content_type 'application/json' - MultiJson.encode(request.env) - end +use OmniAuth::Builder do + provider :facebook, ENV['APP_ID'], ENV['APP_SECRET'], :scope => 'email,read_stream' end -use Rack::Session::Cookie - -use OmniAuth::Builder do - provider :facebook, ENV['APP_ID'], ENV['APP_SECRET'], :scope => SCOPE -end - -run App.new +run Sinatra::Application diff --git a/lib/omniauth/facebook/version.rb b/lib/omniauth/facebook/version.rb index bf5e6ac..1b44e54 100644 --- a/lib/omniauth/facebook/version.rb +++ b/lib/omniauth/facebook/version.rb @@ -1,5 +1,5 @@ module OmniAuth module Facebook - VERSION = "1.6.0" + VERSION = "2.0.0" end end diff --git a/lib/omniauth/strategies/facebook.rb b/lib/omniauth/strategies/facebook.rb index 1bd257e..268322f 100644 --- a/lib/omniauth/strategies/facebook.rb +++ b/lib/omniauth/strategies/facebook.rb @@ -68,35 +68,20 @@ end def callback_phase - super + with_authorization_code! do + super + end rescue NoAuthorizationCodeError => e fail!(:no_authorization_code, e) rescue UnknownSignatureAlgorithmError => e fail!(:unknown_signature_algoruthm, e) end - def request_phase - if signed_request_contains_access_token? - # If we already have an access token, we can just hit the callback URL directly and pass the signed request. - params = { :signed_request => raw_signed_request } - query = Rack::Utils.build_query(params) - - url = callback_url - url << "?" unless url.match(/\?/) - url << "&" unless url.match(/[\&\?]$/) - url << query - - redirect url - else - super - end - end - # NOTE If we're using code from the signed request then FB sets the redirect_uri to '' during the authorize # phase and it must match during the access_token phase: - # https://github.com/facebook/php-sdk/blob/master/src/base_facebook.php#L348 + # https://github.com/facebook/facebook-php-sdk/blob/master/src/base_facebook.php#L477 def callback_url - if @authorization_code_from_signed_request + if @authorization_code_from_signed_request_in_cookie '' else options[:callback_url] || super @@ -110,7 +95,7 @@ # You can pass +display+, +scope+, or +auth_type+ params to the auth request, if you need to set them dynamically. # You can also set these options in the OmniAuth config :authorize_params option. # - # /auth/facebook?display=popup + # For example: /auth/facebook?display=popup def authorize_params super.tap do |params| %w[display scope auth_type].each do |v| @@ -123,63 +108,47 @@ end end - # Parse signed request in order, from: - # - # 1. The request 'signed_request' param (server-side flow from canvas pages) or - # 2. A cookie (client-side flow via JS SDK) - def signed_request - @signed_request ||= raw_signed_request && parse_signed_request(raw_signed_request) - end - protected def build_access_token - if signed_request_contains_access_token? - hash = signed_request.clone - ::OAuth2::AccessToken.new( - client, - hash.delete('oauth_token'), - hash.merge!(access_token_options.merge(:expires_at => hash.delete('expires'))) - ) - else - with_authorization_code! { super }.tap do |token| - token.options.merge!(access_token_options) - end + super.tap do |token| + token.options.merge!(access_token_options) end end private - def raw_signed_request - request.params['signed_request'] || request.cookies["fbsr_#{client.id}"] - end - - # If the signed_request comes from a FB canvas page and the user has already authorized your application, the JSON - # object will be contain the access token. - # - # https://developers.facebook.com/docs/authentication/canvas/ - def signed_request_contains_access_token? - signed_request && signed_request['oauth_token'] + def signed_request_from_cookie + @signed_request_from_cookie ||= raw_signed_request_from_cookie && parse_signed_request(raw_signed_request_from_cookie) + end + + def raw_signed_request_from_cookie + request.cookies["fbsr_#{client.id}"] end # Picks the authorization code in order, from: # # 1. The request 'code' param (manual callback from standard server-side flow) - # 2. A signed request (see #signed_request for more) + # 2. A signed request from cookie (passed from the client during the client-side flow) def with_authorization_code! if request.params.key?('code') yield - elsif code_from_signed_request = signed_request && signed_request['code'] + elsif code_from_signed_request = signed_request_from_cookie && signed_request_from_cookie['code'] request.params['code'] = code_from_signed_request - @authorization_code_from_signed_request = true + @authorization_code_from_signed_request_in_cookie = true + # NOTE The code from the signed fbsr_XXX cookie is set by the FB JS SDK will confirm that the identity of the + # user contained in the signed request matches the user loading the app. + original_provider_ignores_state = options.provider_ignores_state + options.provider_ignores_state = true begin yield ensure request.params.delete('code') - @authorization_code_from_signed_request = false + @authorization_code_from_signed_request_in_cookie = false + options.provider_ignores_state = original_provider_ignores_state end else - raise NoAuthorizationCodeError, 'must pass either a `code` parameter or a signed request (via `signed_request` parameter or a `fbsr_XXX` cookie)' + raise NoAuthorizationCodeError, 'must pass either a `code` (via URL or by an `fbsr_XXX` signed request cookie)' end end diff --git a/metadata.yml b/metadata.yml index 9a62135..5a9f71f 100644 --- a/metadata.yml +++ b/metadata.yml @@ -1,7 +1,7 @@ --- !ruby/object:Gem::Specification name: omniauth-facebook version: !ruby/object:Gem::Version - version: 1.6.0 + version: 2.0.0 platform: ruby authors: - Mark Dodwell @@ -9,7 +9,7 @@ autorequire: bindir: bin cert_chain: [] -date: 2014-01-11 00:00:00.000000000 Z +date: 2014-08-07 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: omniauth-oauth2 @@ -17,14 +17,14 @@ requirements: - - ~> - !ruby/object:Gem::Version - version: '1.1' + version: '1.2' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ~> - !ruby/object:Gem::Version - version: '1.1' + version: '1.2' - !ruby/object:Gem::Dependency name: minitest requirement: !ruby/object:Gem::Requirement @@ -83,6 +83,7 @@ - Rakefile - example/Gemfile - example/Gemfile.lock +- example/app.rb - example/config.ru - lib/omniauth-facebook.rb - lib/omniauth/facebook.rb @@ -112,7 +113,7 @@ version: '0' requirements: [] rubyforge_project: -rubygems_version: 2.0.2 +rubygems_version: 2.2.2 signing_key: specification_version: 4 summary: Facebook OAuth2 Strategy for OmniAuth diff --git a/omniauth-facebook.gemspec b/omniauth-facebook.gemspec index d82cea6..39bbbce 100644 --- a/omniauth-facebook.gemspec +++ b/omniauth-facebook.gemspec @@ -16,7 +16,7 @@ s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) } s.require_paths = ['lib'] - s.add_runtime_dependency 'omniauth-oauth2', '~> 1.1' + s.add_runtime_dependency 'omniauth-oauth2', '~> 1.2' s.add_development_dependency 'minitest' s.add_development_dependency 'mocha' diff --git a/test/helper.rb b/test/helper.rb index e0b1f26..bd1b82b 100644 --- a/test/helper.rb +++ b/test/helper.rb @@ -36,6 +36,7 @@ @request.stubs(:params).returns({}) @request.stubs(:cookies).returns({}) @request.stubs(:env).returns({}) + @request.stubs(:scheme).returns({}) @request.stubs(:ssl?).returns(false) @client_id = '123' diff --git a/test/test.rb b/test/test.rb index 65f0565..35be2e3 100644 --- a/test/test.rb +++ b/test/test.rb @@ -115,13 +115,9 @@ @options = { :image_size => { :width => 123, :height => 987 } } raw_info = { 'name' => 'Fred Smith', 'id' => '321' } strategy.stubs(:raw_info).returns(raw_info) - image_url = strategy.info['image'] - path, query = image_url.split("?") - query_params = Hash[*query.split("&").map {|pair| pair.split("=") }.flatten] - - assert_equal 'http://graph.facebook.com/321/picture', path - assert_equal '123', query_params['width'] - assert_equal '987', query_params['height'] + assert_match 'width=123', strategy.info['image'] + assert_match 'height=987', strategy.info['image'] + assert_match 'http://graph.facebook.com/321/picture?', strategy.info['image'] end end @@ -398,12 +394,11 @@ class CookieAndParamNotPresentTest < TestCase test 'is nil' do - assert_nil strategy.send(:signed_request) + assert_nil strategy.send(:signed_request_from_cookie) end test 'throws an error on calling build_access_token' do - assert_equal 'must pass either a `code` parameter or a signed request (via `signed_request` parameter or a `fbsr_XXX` cookie)', - assert_raises(OmniAuth::Strategies::Facebook::NoAuthorizationCodeError) { strategy.send(:build_access_token) }.message + assert_raises(OmniAuth::Strategies::Facebook::NoAuthorizationCodeError) { strategy.send(:with_authorization_code!) {} } end end @@ -421,125 +416,54 @@ end test 'parses the access code out from the cookie' do - assert_equal @payload, strategy.send(:signed_request) + assert_equal @payload, strategy.send(:signed_request_from_cookie) end test 'throws an error if the algorithm is unknown' do setup('UNKNOWN-ALGO') - assert_equal "unknown algorithm: UNKNOWN-ALGO", assert_raises(OmniAuth::Strategies::Facebook::UnknownSignatureAlgorithmError) { strategy.send(:signed_request) }.message - end - end - - class ParamPresentTest < TestCase + assert_equal "unknown algorithm: UNKNOWN-ALGO", assert_raises(OmniAuth::Strategies::Facebook::UnknownSignatureAlgorithmError) { strategy.send(:signed_request_from_cookie) }.message + end + end + + class EmptySignedRequestTest < TestCase + def setup + super + @request.stubs(:params).returns({'signed_request' => ''}) + end + + test 'empty param' do + assert_equal nil, strategy.send(:signed_request_from_cookie) + end + end + + class MissingCodeInParamsRequestTest < TestCase + def setup + super + @request.stubs(:params).returns({}) + end + + test 'calls fail! when a code is not included in the params' do + strategy.expects(:fail!).times(1).with(:no_authorization_code, kind_of(Exception)) + strategy.callback_phase + end + end + + class MissingCodeInCookieRequestTest < TestCase def setup(algo = nil) super() @payload = { 'algorithm' => algo || 'HMAC-SHA256', - 'oauth_token' => 'XXX', + 'code' => nil, 'issued_at' => Time.now.to_i, 'user_id' => '123456' } - @request.stubs(:params).returns({'signed_request' => signed_request(@payload, @client_secret)}) - end - - test 'parses the access code out from the param' do - assert_equal @payload, strategy.send(:signed_request) - end - - test 'throws an error if the algorithm is unknown' do - setup('UNKNOWN-ALGO') - assert_equal "unknown algorithm: UNKNOWN-ALGO", assert_raises(OmniAuth::Strategies::Facebook::UnknownSignatureAlgorithmError) { strategy.send(:signed_request) }.message - end - end - - class CookieAndParamPresentTest < TestCase - def setup - super - @payload_from_cookie = { - 'algorithm' => 'HMAC-SHA256', - 'from' => 'cookie' - } - - @request.stubs(:cookies).returns({"fbsr_#{@client_id}" => signed_request(@payload_from_cookie, @client_secret)}) - - @payload_from_param = { - 'algorithm' => 'HMAC-SHA256', - 'from' => 'param' - } - - @request.stubs(:params).returns({'signed_request' => signed_request(@payload_from_param, @client_secret)}) - end - - test 'picks param over cookie' do - assert_equal @payload_from_param, strategy.send(:signed_request) - end - end - - class EmptySignedRequestTest < TestCase - def setup - super - @request.stubs(:params).returns({'signed_request' => ''}) - end - - test 'empty param' do - assert_equal nil, strategy.send(:signed_request) - end - end - -end - -class RequestPhaseWithSignedRequestTest < StrategyTestCase - include SignedRequestHelpers - - def setup - super - - payload = { - 'algorithm' => 'HMAC-SHA256', - 'oauth_token' => 'm4c0d3z' - } - @raw_signed_request = signed_request(payload, @client_secret) - @request.stubs(:params).returns("signed_request" => @raw_signed_request) - - strategy.stubs(:callback_url).returns('/') - end - - test 'redirects to callback passing along signed request' do - strategy.expects(:redirect).with("/?signed_request=#{Rack::Utils.escape(@raw_signed_request)}").once - strategy.request_phase - end -end - -module BuildAccessTokenTests - class TestCase < StrategyTestCase - include SignedRequestHelpers - end - - class ParamsContainSignedRequestWithAccessTokenTest < TestCase - def setup - super - - @payload = { - 'algorithm' => 'HMAC-SHA256', - 'oauth_token' => 'm4c0d3z', - 'expires' => Time.now.to_i - } - @raw_signed_request = signed_request(@payload, @client_secret) - @request.stubs(:params).returns({"signed_request" => @raw_signed_request}) - - strategy.stubs(:callback_url).returns('/') - end - - test 'returns a new access token from the signed request' do - result = strategy.send(:build_access_token) - assert_kind_of ::OAuth2::AccessToken, result - assert_equal @payload['oauth_token'], result.token - end - - test 'returns an access token with the correct expiry time' do - result = strategy.send(:build_access_token) - assert_equal @payload['expires'], result.expires_at - end - end -end + @request.stubs(:cookies).returns({"fbsr_#{@client_id}" => signed_request(@payload, @client_secret)}) + end + + test 'calls fail! when a code is not included in the cookie' do + strategy.expects(:fail!).times(1).with(:no_authorization_code, kind_of(Exception)) + strategy.callback_phase + end + end +end