From b1c6d4b8f398525c86c1ac26c52f3297f08bb24f Mon Sep 17 00:00:00 2001 From: Richard Hatherall Date: Tue, 3 Mar 2026 21:41:49 +0000 Subject: [PATCH] feat: Add Token#expired? convenience method Returns true when the current time is at or past expires_at, false when the token has no expiry information. --- lib/cognito_idp/token.rb | 6 +++++ spec/cognito_idp/token_spec.rb | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) 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