Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/reference/use-auth/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Further, the `useAuth` exports defined as a TypeScript type look like this:
```ts
type UseAuth = {
/**
* A way to determine if a user is authenticated or not. The value is `null` by default, and then changes to a boolean once the state is determined.
* A way to determine if a user is authenticated or not. The value is `null` by default, and then changes to a boolean once the state is determined. It updates without a page reload when the user logs in with `useLogin` or their session ends.
*/
isAuthenticated: boolean | null;

Expand Down
28 changes: 28 additions & 0 deletions packages/faustwp-core/src/auth/client/accessToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,28 @@ export function setRefreshTimer(timer: RefreshTimer): void {
*/
let accessToken: AccessToken | undefined;

/**
* Functions to call when this tab logs in or out.
*/
const authChangeListeners = new Set<() => void>();

/**
* Call a function whenever this tab logs in or out, that is, when an access
* token is stored where there was none, or cleared. Refreshing an existing
* token doesn't count.
*
* @param {Function} listener Function to call.
*
* @returns {Function} Function that stops calling the listener.
*/
export function onAuthChange(listener: () => void): () => void {
authChangeListeners.add(listener);

return () => {
authChangeListeners.delete(listener);
};
}

/**
* Get an access token from memory if one exists
*
Expand Down Expand Up @@ -83,10 +105,16 @@ export function setAccessToken(
return;
}

const wasAuthenticated = Boolean(accessToken?.token);

accessToken = {
token,
expiration,
};

if (Boolean(token) !== wasAuthenticated) {
authChangeListeners.forEach((listener) => listener());
}
}

/**
Expand Down
65 changes: 62 additions & 3 deletions packages/faustwp-core/src/hooks/useAuth.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import trim from 'lodash/trim.js';
import defaults from 'lodash/defaults.js';
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { gql } from '@apollo/client';
import {
ensureAuthorization,
EnsureAuthorizationOptions,
getAccessToken,
onAuthChange,
} from '../auth/index.js';
import { getApolloAuthClient } from '../client.js';
import { getWpUrl } from '../lib/getWpUrl.js';

type RedirectStrategyConfig = {
strategy: 'redirect';
Expand Down Expand Up @@ -46,6 +49,17 @@ type ViewerType = {

export type UseAuthConfig = RedirectStrategyConfig | LocalStrategyConfig;

/**
* The URL to log in at for the given strategy, returning to the current page.
*/
function getLoginUrl(config: UseAuthConfig): string {
const redirectUri = encodeURIComponent(window.location.href);

return config.strategy === 'local'
? `/${trim(config.loginPageUrl, '/')}?redirect_uri=${redirectUri}`
: `${getWpUrl()}/generate?redirect_uri=${redirectUri}`;
}

export function useAuth(_config?: UseAuthConfig) {
const config = defaults(_config, {
strategy: 'redirect',
Expand All @@ -64,6 +78,13 @@ export function useAuth(_config?: UseAuthConfig) {
const [loginUrl, setLoginUrl] = useState<string | null>(null);
const [called, setCalled] = useState<boolean>(false);
const [viewer, setViewer] = useState<ViewerType | null>(null);
// Counts logins and logouts in this tab, so a viewer request started before
// one is ignored.
const [session, setSession] = useState<number>(0);
const sessionRef = useRef<number>(0);
const initialCheckDone = useRef<boolean>(false);
const configRef = useRef<UseAuthConfig>(config);
configRef.current = config;

useEffect(() => {
if (config.skip === true) {
Expand Down Expand Up @@ -110,9 +131,38 @@ export function useAuth(_config?: UseAuthConfig) {
}

setIsReady(true);
initialCheckDone.current = true;
})();
}, [called, config]);

/**
* Update when this tab logs in or out after the first check, for example
* after a login with useLogin() or when the session ends.
*/
useEffect(() => {
if (config.skip === true) {
return undefined;
}

function syncWithAccessToken() {
const authenticated = Boolean(getAccessToken());

sessionRef.current += 1;
setSession(sessionRef.current);
setIsAuthenticated(authenticated);
setIsReady(true);
setViewer(null);
setLoginUrl(authenticated ? null : getLoginUrl(configRef.current));
}

// The user may have logged in or out while skip was true.
if (initialCheckDone.current) {
syncWithAccessToken();
}

return onAuthChange(syncWithAccessToken);
}, [config.skip]);

/**
* Automatically redirect the user to the login page if the
* shouldRedirect option is set to true.
Expand Down Expand Up @@ -152,10 +202,16 @@ export function useAuth(_config?: UseAuthConfig) {
return;
}

const requestSession = sessionRef.current;

(async () => {
const client = getApolloAuthClient();

const { data } = await client.query({
// Always ask WordPress, and never share a request with an earlier
// session's, since a different user may have logged in since.
fetchPolicy: 'network-only',
context: { queryDeduplication: false },
query: gql`
query GetFaustViewer {
viewer {
Expand Down Expand Up @@ -183,9 +239,12 @@ export function useAuth(_config?: UseAuthConfig) {
}
`,
});
setViewer(data.viewer as ViewerType | null);
// Ignore the result if the user logged in or out while it was loading.
if (sessionRef.current === requestSession) {
setViewer(data.viewer as ViewerType | null);
}
})();
}, [isAuthenticated, config.skip]);
}, [isAuthenticated, session, config.skip]);

return {
isAuthenticated,
Expand Down
16 changes: 16 additions & 0 deletions packages/faustwp-core/tests/auth/client/accessToken.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,20 @@ describe('auth/client/accessToken', () => {

expect(setTimeoutSpy).toHaveBeenCalledTimes(1);
});

test('onAuthChange() calls listeners on login and logout, not on refresh', () => {
const listener = jest.fn();
const stop = accessToken.onAuthChange(listener);

accessToken.setAccessToken('at', 100);
accessToken.setAccessToken('refreshed', 200);
expect(listener).toHaveBeenCalledTimes(1);

accessToken.setAccessToken(undefined, undefined);
expect(listener).toHaveBeenCalledTimes(2);

stop();
accessToken.setAccessToken('at', 100);
expect(listener).toHaveBeenCalledTimes(2);
});
});
Loading
Loading