Skip to content

Commit a936104

Browse files
committed
Don't try to validate an invalidate token multiple times
I noticed that if a token is invalid because it has expired, we might call `from_token` multiple times. This is because `@current_user` is set to `nil` so won't be cached. `from_token` calls `HydraPublicApiClient.fetch_oauth_user` which does an API request. Since we might call current_user many times in a controller, we shouldn't be doing a API request from each one. Since we're currently recording unauthorized errors in Sentry, this often resulted in 3-5 errors being recorded for the same request. Instead, load the current user once. This might mean in some API calls we're loading the user when we don't need to, but since almost all API actions should validate the current user I don't see this as a problem. The identifible by cookie file doesn't have this problem, but I've updated it for consistency.
1 parent 9d9d042 commit a936104

2 files changed

Lines changed: 12 additions & 10 deletions

File tree

app/controllers/concerns/identifiable.rb

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@
33
module Identifiable
44
extend ActiveSupport::Concern
55

6-
def identify_user
7-
token = request.headers['Authorization']
8-
User.from_token(token:) if token
6+
included do
7+
before_action :load_current_user
8+
attr_reader :current_user
99
end
1010

11-
def current_user
12-
@current_user ||= identify_user
11+
def load_current_user
12+
token = request.headers['Authorization']
13+
@current_user = User.from_token(token:) if token
1314
end
1415
end

app/controllers/concerns/identifiable_by_cookie.rb

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@ module IdentifiableByCookie
44
extend ActiveSupport::Concern
55
include ActionController::Cookies
66

7-
def identify_user
8-
token = cookies[:scratch_auth]
9-
User.from_token(token:) if token
7+
included do
8+
before_action :load_current_user
9+
attr_reader :current_user
1010
end
1111

12-
def current_user
13-
@current_user ||= identify_user
12+
def load_current_user
13+
token = cookies[:scratch_auth]
14+
@current_user = User.from_token(token:) if token
1415
end
1516
end

0 commit comments

Comments
 (0)