Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

check if token is expired

  • Loading branch information...
commit 5d4d120669319db4dc5f4c7154046432cc732a56 1 parent 802ad11
LupineDev authored
View
10 lib/microsoft_translator/azure_authentication.rb
@@ -14,17 +14,19 @@ def initialize(client_id, client_secret)
renew_token
end
- def latest_token
- # check if current token is still good
- # get new_token if not
+ def current_token
+ if @token_expires_at < Time.now
+ renew_token
+ end
+ @token
end
def renew_token
auth_response = RestClient.post(AUTH_URL, auth_params)
parsed_json = JSON.parse(auth_response.body)
- @token = parsed_json['access_token']
@token_expires_at = Time.now + parsed_json['expires_in'].to_i
+ @token = parsed_json['access_token']
end
private
View
26 spec/lib/microsoft_translator/azure_authentication_spec.rb
@@ -39,4 +39,30 @@
end
end
+ describe "#latest_token" do
+ before :each do
+ stub_auth_request('first_token')
+ @auth = MicrosoftTranslator::AzureAuthentication.new('id','secret')
+ end
+
+ after :each do
+ Timecop.return
+ end
+
+ it "should return the current_token if it has not expired yet" do
+ @auth.should_not_receive(:renew_token)
+ Timecop.travel(@auth.token_expires_at - 100)
+ @auth.current_token.should eq('first_token')
+ end
+
+ it "should get a new token if it has not expired yet" do
+ pending "having trouble testing"
+ @auth.should_receive(:renew_token)
+ Timecop.travel(@auth.token_expires_at + 1000)
+ stub_auth_request('new_token')
+ token = @auth.current_token
+ token.should eq('new_token')
+ end
+ end
+
end
View
4 spec/support/requests_helper.rb
@@ -6,8 +6,8 @@ def auth_params(id, secret)
"grant_type" => MicrosoftTranslator::AzureAuthentication::GRANT_TYPE
}
end
-def stub_auth_request
- response = stub("response", :body => {"access_token"=>"stubbed_token", "token_type"=>"http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0", "expires_in"=>"599", "scope"=>"http://api.microsofttranslator.com"}.to_json)
+def stub_auth_request(returned_token=nil)
+ response = stub("response", :body => {"access_token"=>"#{returned_token || 'stubbed_token'}", "token_type"=>"http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0", "expires_in"=>"599", "scope"=>"http://api.microsofttranslator.com"}.to_json)
RestClient.stub(:post).and_return(response)
end
Please sign in to comment.
Something went wrong with that request. Please try again.