I’m noticing a behavior that I think should be classified as a bug:
After a successful logIn() on a page useAuth() returns isAuthenticated, but with null for currentUser and userMetadata.
This results in additional unnecessary authentication(s) when code assumes !currentUser means not authenticated. I believe there are places in the AuthProvider code that makes this assumption and trigger additional authentications.
After some debugging I noticed that this is what is happening:
- The initial call to useAuth() on a page calls getToken() which tries to fetch the token from the server.
- The server response is a null token because the user is not yet logged in (no session cookie).
- dbAuth caches the null token
- The page calls logIn() which succeeds. The server sends a set-cookie for the session.
- logIn() next calls reauthenticate() internally, which kicks off another getToken()
- That call to getToken() never goes to the server because dbAuth finds the previously cached null token and returns it instead of fetching from from the server and getting the actual token
- The page re-renders with isAuthenticated: true, currentUser: null, userMetadata: null
- Calling navigate() to another route at this point triggers another authentication because calls to useAuth() have currentUser: null
It seems to me that if the cached token is null, getToken should fetch from the server. I don’t know the code very well but I was thinking the code below could be a fix.
Can someone who knows the code better determine the most appropriate fix and include it in the next release?
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/packages/auth-providers/dbAuth/web/src/dbAuth.ts b/packages/auth-providers/dbAuth/web/src/dbAuth.ts
--- a/packages/auth-providers/dbAuth/web/src/dbAuth.ts (revision 1075258d60cc0d0fdda0257576f999b26ac5a07d)
+++ b/packages/auth-providers/dbAuth/web/src/dbAuth.ts (date 1704231152678)
@@ -86,7 +86,7 @@
return getTokenPromise
}
- if (isTokenCacheExpired()) {
+ if (isTokenCacheExpired() || cachedToken === null) {
getTokenPromise = fetch(`${getApiDbAuthUrl()}?method=getToken`, {
credentials,
})