refactor: create a generic auth cookie provider

Signed-off-by: Camila Belo <camilaibs@gmail.com>
This commit is contained in:
Camila Belo
2024-03-12 13:56:35 +01:00
parent 8a74a14754
commit 81793abc0c
14 changed files with 346 additions and 1 deletions
@@ -0,0 +1,51 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { ReactNode } from 'react';
import { ErrorPanel } from '@backstage/core-components';
import { ApiRef, useApp } from '@backstage/core-plugin-api';
import { Button } from '@material-ui/core';
import { useCookieAuthRefresh } from '../../hooks';
import { AuthApi } from '../../types';
export function CookieAuthRefreshProvider<T extends AuthApi>({
apiRef,
children,
}: {
apiRef: ApiRef<T>;
children: ReactNode;
}) {
const app = useApp();
const { Progress } = app.getComponents();
const { state, actions } = useCookieAuthRefresh({ apiRef });
if (state.status === 'error' && state.error) {
return (
<ErrorPanel error={state.error}>
<Button variant="outlined" onClick={actions.execute}>
Retry
</Button>
</ErrorPanel>
);
}
if (state.status === 'loading') {
return <Progress />;
}
return children;
}
@@ -0,0 +1,17 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { CookieAuthRefreshProvider } from './CookieAuthRefreshProvider';
@@ -0,0 +1,20 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// The index file in ./components/ is typically responsible for selecting
// which components are public API and should be exported from the package.
export * from './CookieAuthRefreshProvider';
+20
View File
@@ -0,0 +1,20 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// The index file in ./hooks/ is typically responsible for selecting
// which hooks are public API and should be exported from the package.
export * from './useCookieAuthRefresh';
@@ -0,0 +1,17 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { useCookieAuthRefresh } from './useCookieAuthRefresh';
@@ -0,0 +1,82 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useEffect, useState, useCallback } from 'react';
import { ApiRef, useApi } from '@backstage/core-plugin-api';
import { useAsync, useMountEffect } from '@react-hookz/web';
import { AuthApi } from '../../types';
type CookieAuthRefreshMessage = MessageEvent<{
action: string;
payload: {
expiresAt: string;
};
}>;
export function useCookieAuthRefresh<T extends AuthApi>({
apiRef,
}: {
apiRef: ApiRef<T>;
}) {
const api = useApi(apiRef);
const [channel] = useState(
() => new BroadcastChannel(`${apiRef.id}.auth.cookie.channel`),
);
const [state, actions] = useAsync(async () => await api.getCookie());
useMountEffect(actions.execute);
const refresh = useCallback(
(options: { expiresAt: string }) => {
// Randomize the refreshing margin to avoid all tabs refreshing at the same time
const margin = (1 + 3 * Math.random()) * 60000;
const delay = Date.parse(options.expiresAt) - Date.now() - margin;
const timeout = setTimeout(actions.execute, delay);
return () => clearTimeout(timeout);
},
[actions],
);
useEffect(() => {
if (!state.result) return () => {};
channel.postMessage({
action: 'COOKIE_REFRESHED',
payload: state.result,
});
let cancel = refresh(state.result);
const handleMessage = (event: CookieAuthRefreshMessage): void => {
const { action, payload } = event.data;
if (action === 'COOKIE_REFRESHED') {
cancel();
cancel = refresh(payload);
}
};
channel.addEventListener('message', handleMessage);
return () => {
cancel();
channel.removeEventListener('message', handleMessage);
};
}, [state, refresh, channel]);
return { state, actions };
}
+27
View File
@@ -0,0 +1,27 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Web library for the auth plugin.
*
* @packageDocumentation
*/
// In this package you might for example export components or hooks
// that are useful to other plugins or modules.
export * from './components';
export * from './hooks';
+16
View File
@@ -0,0 +1,16 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import '@testing-library/jest-dom';
+17
View File
@@ -0,0 +1,17 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export type AuthApi = { getCookie(): Promise<{ expiresAt: string }> };