Skip to content

Commit a135a63

Browse files
committed
Guard safeguarding flag request cache
1 parent 09a9473 commit a135a63

3 files changed

Lines changed: 18 additions & 0 deletions

File tree

app/controllers/concerns/identifiable.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ def load_current_user
1313
return unless token
1414

1515
@current_user = User.from_token(token:)
16+
return unless RequestStore.respond_to?(:active?) && RequestStore.active?
17+
1618
RequestStore.store[:safeguarding_flag_users_by_token] ||= {}
1719
RequestStore.store[:safeguarding_flag_users_by_token][token] = @current_user
1820
end

app/services/safeguarding_flag_service.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,16 @@ def create_for_roles(token:, email:, school:, roles:)
3737
private
3838

3939
def user_for_token(token)
40+
return User.from_token(token:) unless request_store_active?
41+
4042
cache = RequestStore.store[:safeguarding_flag_users_by_token] ||= {}
4143
return cache[token] if cache.key?(token)
4244

4345
cache[token] = User.from_token(token:)
4446
end
47+
48+
def request_store_active?
49+
RequestStore.respond_to?(:active?) && RequestStore.active?
50+
end
4551
end
4652
end

spec/services/safeguarding_flag_service_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858

5959
before do
6060
allow(User).to receive(:from_token).with(token:).and_return(user)
61+
allow(described_class).to receive(:request_store_active?).and_return(false)
6162
end
6263

6364
it 'creates flags for the user identified by the token' do
@@ -72,6 +73,7 @@
7273
end
7374

7475
it 'uses a user cached for the token' do
76+
allow(described_class).to receive(:request_store_active?).and_return(true)
7577
RequestStore.store[:safeguarding_flag_users_by_token][token] = user
7678

7779
described_class.create_for_token(token:, school:)
@@ -86,11 +88,19 @@
8688
end
8789

8890
it 'caches the user after looking it up' do
91+
allow(described_class).to receive(:request_store_active?).and_return(true)
92+
8993
2.times { described_class.create_for_token(token:, school:) }
9094

9195
expect(User).to have_received(:from_token).once
9296
end
9397

98+
it 'does not cache token lookups outside an active request store' do
99+
2.times { described_class.create_for_token(token:, school:) }
100+
101+
expect(User).to have_received(:from_token).twice
102+
end
103+
94104
it 'does not look up a user without a token' do
95105
described_class.create_for_token(token: nil, school:)
96106

0 commit comments

Comments
 (0)