diff --git a/lib/fog/brightbox/oauth2.rb b/lib/fog/brightbox/oauth2.rb index 713b5abb7..45886e08b 100644 --- a/lib/fog/brightbox/oauth2.rb +++ b/lib/fog/brightbox/oauth2.rb @@ -81,7 +81,9 @@ module Fog::Brightbox::OAuth2 # @todo Add a means to dictate which should or shouldn't be used # def best_grant_strategy - if user_details? + if refresh_token? + RefreshTokenStrategy.new(self) + elsif user_details? UserCredentialsStrategy.new(self) else ClientCredentialsStrategy.new(self) @@ -135,6 +137,19 @@ module Fog::Brightbox::OAuth2 end end + # This strategy attempts to use a refresh_token gained during an earlier + # request to reuse the credentials given originally + # + class RefreshTokenStrategy < GrantTypeStrategy + def authorization_body_data + { + "grant_type" => "refresh_token", + "client_id" => @credentials.client_id, + "refresh_token" => @credentials.refresh_token + } + end + end + private # This updates the current credentials if passed a valid response diff --git a/tests/brightbox/oauth2_tests.rb b/tests/brightbox/oauth2_tests.rb index fd0c77ede..137cc147d 100644 --- a/tests/brightbox/oauth2_tests.rb +++ b/tests/brightbox/oauth2_tests.rb @@ -28,6 +28,17 @@ Shindo.tests("Fog::Brightbox::OAuth2", ["brightbox"]) do credentials.best_grant_strategy.is_a?(Fog::Brightbox::OAuth2::UserCredentialsStrategy) end end + + tests("with existing tokens") do + options = {:username => @username, :access_token => @access_token, :refresh_token => @refresh_token} + credentials = Fog::Brightbox::OAuth2::CredentialSet.new(@client_id, @client_secret, options) + tests("#user_details?").returns(false) { credentials.user_details? } + tests("#access_token?").returns(true) { credentials.access_token? } + tests("#refresh_token?").returns(true) { credentials.refresh_token? } + tests("#best_grant_strategy").returns(true) do + credentials.best_grant_strategy.is_a?(Fog::Brightbox::OAuth2::RefreshTokenStrategy) + end + end end tests("GrantTypeStrategy") do @@ -71,4 +82,22 @@ Shindo.tests("Fog::Brightbox::OAuth2", ["brightbox"]) do test("password == #{@password}") { authorization_body_data["password"] == @password } end end + + tests("RefreshTokenStrategy") do + refresh_token = "ab4b39dddf909" + options = {:refresh_token => refresh_token} + credentials = Fog::Brightbox::OAuth2::CredentialSet.new(@client_id, @client_secret, options) + strategy = Fog::Brightbox::OAuth2::RefreshTokenStrategy.new(credentials) + + tests("#respond_to? :authorization_body_data").returns(true) do + strategy.respond_to?(:authorization_body_data) + end + + tests("#authorization_body_data") do + authorization_body_data = strategy.authorization_body_data + test("grant_type == refresh_token") { authorization_body_data["grant_type"] == "refresh_token" } + test("client_id == #{@client_id}") { authorization_body_data["client_id"] == @client_id } + test("refresh_token == #{refresh_token}") { authorization_body_data["refresh_token"] == refresh_token } + end + end end