OAuthPlug: use user cache instead of joining

As this plug is called on every request, this should reduce load on the
database by not requiring to select on the users table every single
time, and to instead use the by-ID user cache whenever possible.
This commit is contained in:
Hélène 2022-08-23 17:15:06 +02:00
parent a022b9d733
commit 439c1baf25
Signed by untrusted user: helene
GPG key ID: A215F2E9F1589D62

View file

@ -47,15 +47,17 @@ def call(conn, _) do
# #
@spec fetch_user_and_token(String.t()) :: {:ok, User.t(), Token.t()} | nil @spec fetch_user_and_token(String.t()) :: {:ok, User.t(), Token.t()} | nil
defp fetch_user_and_token(token) do defp fetch_user_and_token(token) do
query = token_query =
from(t in Token, from(t in Token,
where: t.token == ^token, where: t.token == ^token
join: user in assoc(t, :user),
preload: [user: user]
) )
with %Token{user: user} = token_record <- Repo.one(query) do with %Token{user_id: user_id} = token_record <- Repo.one(token_query),
false <- is_nil(user_id),
%User{} = user <- User.get_cached_by_id(user_id) do
{:ok, user, token_record} {:ok, user, token_record}
else
_ -> nil
end end
end end