diff --git a/lib/cognito_idp/token.rb b/lib/cognito_idp/token.rb index 203e373..e7f0317 100644 --- a/lib/cognito_idp/token.rb +++ b/lib/cognito_idp/token.rb @@ -15,6 +15,12 @@ def initialize(token_hash) @expires_at = Time.now + expires_in unless expires_in.nil? end + def expired? + return false if expires_at.nil? + + Time.now >= expires_at + end + def inspect "#<#{self.class}:0x#{object_id.to_s(16)} " \ "@access_token=#{access_token.nil? ? "nil" : "[REDACTED]"}, " \ diff --git a/spec/cognito_idp/token_spec.rb b/spec/cognito_idp/token_spec.rb index 0a5e7a3..323842d 100644 --- a/spec/cognito_idp/token_spec.rb +++ b/spec/cognito_idp/token_spec.rb @@ -16,6 +16,46 @@ it { expect(token.expires_at).to be_nil } it { expect(token.refresh_token).to be_nil } + describe "#expired?" do + context "when expires_in is nil" do + it { expect(token.expired?).to be false } + end + + context "when token has not expired" do + let(:token_hash) { {"expires_in" => 3600} } + + it { expect(token.expired?).to be false } + end + + context "when token has expired" do + let(:token_hash) { {"expires_in" => 3600} } + + before do + Timecop.freeze + token # force creation at frozen time + Timecop.freeze(Time.now + 3601) + end + + after { Timecop.return } + + it { expect(token.expired?).to be true } + end + + context "when token is at the exact expiry time" do + let(:token_hash) { {"expires_in" => 3600} } + + before do + Timecop.freeze + token # force creation at frozen time + Timecop.freeze(Time.now + 3600) + end + + after { Timecop.return } + + it { expect(token.expired?).to be true } + end + end + describe "#inspect" do context "when token values are set" do let(:token_hash) do