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
21 changes: 21 additions & 0 deletions src/core/utils/deepEqual.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export function deepEqual<T>(x: T, y: T): boolean {
if (x === y) {
return true;
} else if (
typeof x == 'object' &&
x != null &&
typeof y == 'object' &&
y != null
) {
if (Object.keys(x).length != Object.keys(y).length) return false;

for (const prop in x) {
if (Object.prototype.hasOwnProperty.call(y, prop)) {
if (!deepEqual(x[prop], y[prop])) return false;
} else return false;
}
return true;
} else {
return false;
}
}
24 changes: 17 additions & 7 deletions src/hooks/Auth0Provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -146,21 +146,31 @@ export const Auth0Provider = ({
);

const getCredentials = useCallback(
(
async (
scope?: string,
minTtl?: number,
parameters?: Record<string, unknown>,
forceRefresh?: boolean
) =>
loginFlow(
client.credentialsManager.getCredentials(
) => {
try {
const credentials = await client.credentialsManager.getCredentials(
scope,
minTtl,
parameters,
forceRefresh
)
),
[client, loginFlow]
);
if (credentials.idToken) {
const user = Auth0User.fromIdToken(credentials.idToken);
dispatch({ type: 'SET_USER', user });
}
return credentials;
} catch (e) {
const error = e as AuthError;
dispatch({ type: 'ERROR', error });
throw error;
}
},
[client]
);

const hasValidCredentials = useCallback(
Expand Down
9 changes: 8 additions & 1 deletion src/hooks/reducer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { User } from '../types';
import type { AuthError } from '../core/models';
import { deepEqual } from '../core/utils/deepEqual';

/**
* The shape of the authentication state managed by the Auth0Provider.
Expand All @@ -18,7 +19,8 @@ export type AuthAction =
| { type: 'LOGIN_COMPLETE'; user: User }
| { type: 'LOGOUT_COMPLETE' }
| { type: 'ERROR'; error: AuthError }
| { type: 'INITIALIZED'; user: User | null };
| { type: 'INITIALIZED'; user: User | null }
| { type: 'SET_USER'; user: User | null };

/**
* A pure function that calculates the new state based on the previous state and a dispatched action.
Expand All @@ -34,5 +36,10 @@ export const reducer = (state: AuthState, action: AuthAction): AuthState => {
return { ...state, isLoading: false, error: action.error };
case 'INITIALIZED':
return { ...state, isLoading: false, user: action.user };
case 'SET_USER':
if (deepEqual(state.user, action.user)) {
return state;
}
return { ...state, user: action.user };
}
};