diff --git a/app/models/france_connect_information.rb b/app/models/france_connect_information.rb index c4deb17a2..bdc6d5d5b 100644 --- a/app/models/france_connect_information.rb +++ b/app/models/france_connect_information.rb @@ -18,6 +18,8 @@ # user_id :integer # class FranceConnectInformation < ApplicationRecord + MERGE_VALIDITY = 15.minutes + belongs_to :user, optional: true validates :france_connect_particulier_id, presence: true, allow_blank: false, allow_nil: false @@ -39,4 +41,8 @@ class FranceConnectInformation < ApplicationRecord update_attribute('user_id', user.id) touch # needed to update updated_at column end + + def valid_for_merge? + (MERGE_VALIDITY.ago < merge_token_created_at) && user_id.nil? + end end diff --git a/spec/models/france_connect_information_spec.rb b/spec/models/france_connect_information_spec.rb index 150b92fc3..ab321cec5 100644 --- a/spec/models/france_connect_information_spec.rb +++ b/spec/models/france_connect_information_spec.rb @@ -19,4 +19,28 @@ describe FranceConnectInformation, type: :model do end end end + + describe '#valid_for_merge?' do + let(:fci) { create(:france_connect_information) } + + subject { fci.valid_for_merge? } + + context 'when the merge token is young enough' do + before { fci.merge_token_created_at = 1.minute.ago } + + it { is_expected.to be(true) } + + context 'but the fci is already linked to an user' do + before { fci.update(user: create(:user)) } + + it { is_expected.to be(false) } + end + end + + context 'when the merge token is too old' do + before { fci.merge_token_created_at = (FranceConnectInformation::MERGE_VALIDITY + 1.minute).ago } + + it { is_expected.to be(false) } + end + end end