Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove unecessary renders after auth refresh. #2943

Merged
merged 1 commit into from
Sep 25, 2024
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
10 changes: 7 additions & 3 deletions cypress/component/AllServicesPage/AllServicesPage.cy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,13 @@ describe('<AllServices />', () => {
},
}));
cy.mount(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
<ChromeAuthContext.Provider value={{}}>
<ChromeAuthContext.Provider
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
value={{
user: userFixture as unknown as ChromeUser,
}}
>
<ScalprumProvider
config={{}}
api={{
Expand Down
4 changes: 2 additions & 2 deletions cypress/component/ContextSwitcher/ContextSwitcher.cy.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ describe('<ContextSwithcer />', () => {
const elem = cy
.mount(
<Wrapper store={store}>
<ContextSwitcher user={testUser} />
<ContextSwitcher accountNumber={testUser.identity.account_number} isInternal={testUser.identity.user.is_internal} />
</Wrapper>
)
.get('html');
Expand All @@ -76,7 +76,7 @@ describe('<ContextSwithcer />', () => {
const elem = cy
.mount(
<Wrapper store={store}>
<ContextSwitcher user={testUser} />
<ContextSwitcher accountNumber={testUser.identity.account_number} isInternal={testUser.identity.user.is_internal} />
</Wrapper>
)
.get('html');
Expand Down
11 changes: 7 additions & 4 deletions cypress/component/OIDCConnector/OIDCSecured.cy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ describe('ODIC Secured', () => {
const authContextValue: AuthContextProps = {
clearStaleState: () => Promise.resolve(),
settings: authContextSettings,
events: {} as AuthContextProps['events'],
removeUser: () => Promise.resolve(),
signinRedirect: () => Promise.resolve(),
isAuthenticated: true,
Expand All @@ -94,6 +93,10 @@ describe('ODIC Secured', () => {
startSilentRenew: () => Promise.resolve(),
stopSilentRenew: () => Promise.resolve(),
user: testUser,
events: {
addSilentRenewError: () => {},
removeSilentRenewError: () => {},
} as unknown as AuthContextProps['events'],
};
beforeEach(() => {
store = createStore((state = { chrome: {} }) => {
Expand All @@ -105,7 +108,7 @@ describe('ODIC Secured', () => {
cy.mount(
<AuthContext.Provider value={authContextValue}>
<Wrapper store={store}>
<OIDCSecured microFrontendConfig={{}} cookieElement={null} setCookieElement={() => undefined}>
<OIDCSecured ssoUrl="" microFrontendConfig={{}}>
<ChildComponent />
</OIDCSecured>
</Wrapper>
Expand All @@ -119,7 +122,7 @@ describe('ODIC Secured', () => {
cy.mount(
<AuthContext.Provider value={authContextValue}>
<Wrapper store={store}>
<OIDCSecured microFrontendConfig={{}} cookieElement={null} setCookieElement={() => undefined}>
<OIDCSecured ssoUrl="" microFrontendConfig={{}}>
<ChildComponent />
</OIDCSecured>
</Wrapper>
Expand All @@ -133,7 +136,7 @@ describe('ODIC Secured', () => {
cy.mount(
<AuthContext.Provider value={authContextValue}>
<Wrapper store={store}>
<OIDCSecured microFrontendConfig={{}} cookieElement={null} setCookieElement={() => undefined}>
<OIDCSecured ssoUrl="" microFrontendConfig={{}}>
<ChildComponent />
</OIDCSecured>
</Wrapper>
Expand Down
20 changes: 5 additions & 15 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@
"@rhds/elements": "^2.0.1",
"@rhds/icons": "^1.1.1",
"@scalprum/core": "^0.8.1",
"@scalprum/react-core": "^0.9.1",
"@scalprum/react-core": "^0.9.3",
"@segment/analytics-next": "^1.70.0",
"@sentry/react": "^7.118.0",
"@sentry/tracing": "^7.118.0",
Expand Down
4 changes: 3 additions & 1 deletion src/auth/ChromeAuthContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { AxiosResponse } from 'axios';
import { createContext } from 'react';
import { OfflineTokenResponse } from './offline';

export type ChromeLogin<LoginResponse = void> = (requiredScopes?: string[]) => Promise<LoginResponse>;

export type ChromeAuthContextValue<LoginResponse = void> = {
ssoUrl: string;
ready: boolean;
Expand All @@ -12,7 +14,7 @@ export type ChromeAuthContextValue<LoginResponse = void> = {
logoutAllTabs: (bounce?: boolean) => void;
loginAllTabs: () => void;
logout: () => void;
login: (requiredScopes?: string[]) => Promise<LoginResponse>;
login: ChromeLogin<LoginResponse>;
tokenExpires: number;
getToken: () => Promise<string>;
getRefreshToken: () => Promise<string>;
Expand Down
13 changes: 12 additions & 1 deletion src/auth/OIDCConnector/OIDCSecured.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
children,
microFrontendConfig,
ssoUrl,
}: React.PropsWithChildren<{ microFrontendConfig: Record<string, any>; ssoUrl: string }>) {

Check warning on line 79 in src/auth/OIDCConnector/OIDCSecured.tsx

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
const auth = useAuth();
const authRef = useRef(auth);
const setScalprumConfigAtom = useSetAtom(writeInitialScalprumConfigAtom);
Expand Down Expand Up @@ -184,7 +184,18 @@
if (!auth.error) {
startChrome();
}
}, [auth]);
function onRenewError(error: Error) {
console.error('Silent renew error', error);
state.login();
}
auth.events.addSilentRenewError(onRenewError);

return () => {
auth.events.removeSilentRenewError(onRenewError);
};
// to ensure we are not re-initializing the chrome on every auth change
// only on the important events
}, [auth.error, auth.isLoading, auth.isAuthenticated, state.token, state.user?.identity?.account_number]);

useEffect(() => {
authRef.current = auth;
Expand Down
16 changes: 12 additions & 4 deletions src/components/Activation/Activation.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import React, { useContext, useEffect, useState } from 'react';
import { ChromeUser } from '@redhat-cloud-services/types';
import { DeepRequired } from 'utility-types';
import { useNavigate } from 'react-router-dom';
import { Modal, ModalVariant } from '@patternfly/react-core/dist/dynamic/components/Modal';
import { Text, TextContent } from '@patternfly/react-core/dist/dynamic/components/Text';
Expand All @@ -9,7 +7,17 @@ import { useIntl } from 'react-intl';
import messages from '../../locales/Messages';
import InternalChromeContext from '../../utils/internalChromeContext';

const Activation = ({ user, request }: { user: DeepRequired<ChromeUser>; request: string }) => {
const Activation = ({
user,
request,
}: {
user: {
username: string;
accountNumber: string;
email: string;
};
request: string;
}) => {
const intl = useIntl();
const [isModalOpen, setIsModalOpen] = useState(true);
const navigate = useNavigate();
Expand All @@ -29,7 +37,7 @@ const Activation = ({ user, request }: { user: DeepRequired<ChromeUser>; request
'Content-Type': 'application/json',
},
body: JSON.stringify({
description: `Username: ${user.identity.user.username}, Account ID: ${user.identity.account_number}, Email: ${user.identity.user.email}`, //eslint-disable-line
description: `Username: ${user.username}, Account ID: ${user.accountNumber}, Email: ${user.email}`, //eslint-disable-line
summary: `Activation Request - for cloud-marketplace-enablement team`,
labels: [request],
}),
Expand Down
17 changes: 0 additions & 17 deletions src/components/ChromeRoute/ChromeRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,9 @@ import LoadingFallback from '../../utils/loading-fallback';
import { batch, useDispatch } from 'react-redux';
import { toggleGlobalFilter } from '../../redux/actions';
import ErrorComponent from '../ErrorComponents/DefaultErrorComponent';
import { getPendoConf } from '../../analytics';
import classNames from 'classnames';
import { HelpTopicContext } from '@patternfly/quickstarts';
import GatewayErrorComponent from '../ErrorComponents/GatewayErrorComponent';
import { DeepRequired } from 'utility-types';
import { ChromeUser } from '@redhat-cloud-services/types';
import ChromeAuthContext from '../../auth/ChromeAuthContext';
import { useAtomValue, useSetAtom } from 'jotai';
import { activeModuleAtom } from '../../state/atoms/activeModuleAtom';
import { gatewayErrorAtom } from '../../state/atoms/gatewayErrorAtom';
Expand All @@ -35,7 +31,6 @@ const ChromeRoute = memo(
const isPreview = useAtomValue(isPreviewAtom);
const dispatch = useDispatch();
const { setActiveHelpTopicByName } = useContext(HelpTopicContext);
const { user } = useContext(ChromeAuthContext);
const gatewayError = useAtomValue(gatewayErrorAtom);
const [isHidden, setIsHidden] = useState<boolean | null>(null);

Expand Down Expand Up @@ -65,18 +60,6 @@ const ChromeRoute = memo(
// should be triggered only once per session
setActiveModule(scope);
});
/**
* update pendo metadata on application change
*/
if (window.pendo) {
try {
window.pendo.updateOptions(getPendoConf(user as DeepRequired<ChromeUser>, isPreview));
} catch (error) {
console.error('Unable to update pendo options');
console.error(error);
}
}

/**
* TODO: Discuss default close feature of topics
* Topics drawer has no close button, therefore there might be an issue with opened topics after user changes route and does not clear the active topic trough the now non existing elements.
Expand Down
22 changes: 11 additions & 11 deletions src/components/ContextSwitcher/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ import {
REQUESTS_COUNT,
REQUESTS_DATA,
} from '../../utils/consts';
import { ChromeUser } from '@redhat-cloud-services/types';
import { useAtom } from 'jotai';
import { contextSwitcherOpenAtom } from '../../state/atoms/contextSwitcher';

export type ContextSwitcherProps = {
user: ChromeUser;
className?: string;
accountNumber?: string;
isInternal?: boolean;
};

// These attributes are present in the response based on the open API spec.
Expand All @@ -41,12 +41,12 @@ type CrossAccountRequestInternal = CrossAccountRequest & {
email: string;
};

const ContextSwitcher = ({ user, className }: ContextSwitcherProps) => {
const ContextSwitcher = ({ accountNumber, className, isInternal }: ContextSwitcherProps) => {
const intl = useIntl();
const [isOpen, setIsOpen] = useAtom(contextSwitcherOpenAtom);
const [data, setData] = useState<CrossAccountRequestInternal[]>([]);
const [searchValue, setSearchValue] = useState('');
const [selectedAccountNumber, setSelectedAccountNumber] = useState(user.identity.account_number);
const [selectedAccountNumber, setSelectedAccountNumber] = useState(accountNumber);
const onSelect = () => {
setIsOpen((prev) => !prev);
};
Expand Down Expand Up @@ -80,10 +80,10 @@ const ContextSwitcher = ({ user, className }: ContextSwitcherProps) => {
};

const resetAccountRequest = () => {
if (user?.identity?.account_number === selectedAccountNumber) {
if (accountNumber === selectedAccountNumber) {
return;
}
setSelectedAccountNumber(user?.identity?.account_number);
setSelectedAccountNumber(accountNumber);
Cookies.remove(CROSS_ACCESS_ACCOUNT_NUMBER);
Cookies.remove(CROSS_ACCESS_ORG_ID);
localStorage.removeItem(ACTIVE_REMOTE_REQUEST);
Expand All @@ -93,7 +93,7 @@ const ContextSwitcher = ({ user, className }: ContextSwitcherProps) => {
useEffect(() => {
let mounted = true;
// only inernal users have the TAM features enabled
if (user?.identity?.user?.is_internal) {
if (isInternal) {
const initialAccount = localStorage.getItem(ACTIVE_REMOTE_REQUEST);
if (initialAccount) {
try {
Expand Down Expand Up @@ -121,7 +121,7 @@ const ContextSwitcher = ({ user, className }: ContextSwitcherProps) => {
}
return [...acc, curr];
}, [])
.filter(({ target_account }) => target_account !== user.identity.account_number)
.filter(({ target_account }) => target_account !== accountNumber)
);
}
});
Expand Down Expand Up @@ -151,12 +151,12 @@ const ContextSwitcher = ({ user, className }: ContextSwitcherProps) => {
searchInputPlaceholder={intl.formatMessage(messages.searchAccount)}
isFullHeight
>
{user && user?.identity?.account_number?.includes(searchValue) ? (
{accountNumber?.includes(searchValue) ? (
<ContextSelectorItem onClick={resetAccountRequest}>
<TextContent className="chr-c-content-account">
<Text className="account-label pf-v5-u-mb-0 sentry-mask data-hj-suppress">
<span>{user?.identity?.account_number}</span>
{user?.identity?.account_number === `${selectedAccountNumber}` && (
<span>{accountNumber}</span>
{accountNumber === `${selectedAccountNumber}` && (
<Icon size="sm" className="pf-v5-u-ml-auto">
<CheckIcon color="var(--pf-v5-global--primary-color--100)" />
</Icon>
Expand Down
Loading
Loading