Skip to content

Commit

Permalink
broadcast-channel-fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
nidhi-bhanushali committed Sep 10, 2024
1 parent f5892f6 commit d208ac9
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 10 deletions.
27 changes: 24 additions & 3 deletions src/components/OAuthPopup.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect } from 'react';
import { OAUTH_RESPONSE } from './constants';
import { OAUTH_RESPONSE, OAUTH_RESPONSE_ACK } from './constants';
import { channelPostMessage, checkState, isBroadcastChannel, queryToObject } from './tools';
import { TMessageData } from './types';

type Props = {
Component?: React.ReactElement;
Expand All @@ -15,9 +16,9 @@ export const OAuthPopup = ({
</div>
),
}: Props) => {
const channel = new BroadcastChannel('oauth_channel');
const channel = new BroadcastChannel('refrens_oauth_channel');
useEffect(() => {
if (didInit) return;
if (didInit) return () => {};
didInit = true;

const payload = {
Expand All @@ -32,6 +33,7 @@ export const OAuthPopup = ({

if (!error && stateOk) {
channelPostMessage(channel, { type: OAUTH_RESPONSE, payload });
console.log('message sent', payload);
} else {
const errorMessage = error
? decodeURI(error)
Expand All @@ -41,10 +43,29 @@ export const OAuthPopup = ({
: 'OAuth error: State mismatch.'
}`;
channelPostMessage(channel, { type: OAUTH_RESPONSE, error: errorMessage });

console.error('message sent', errorMessage);
}
} else {
throw new Error('No BroadcastChannel support');
}

const handleListener = (message: MessageEvent<TMessageData>) => {
console.log('message received', message);
const type = message?.data?.type;
if (type !== OAUTH_RESPONSE_ACK) {
return;
}
console.log('message received', message, window, 'after');
window.close();
};

// eslint-disable-next-line unicorn/prefer-add-event-listener
channel.addEventListener('message', handleListener);

return () => {
channel.removeEventListener('message', handleListener);
};
}, []);

return Component;
Expand Down
1 change: 1 addition & 0 deletions src/components/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export const OAUTH_STATE_KEY = 'react-use-oauth2-state-key';
export const OAUTH_RESPONSE = 'react-use-oauth2-response';
export const EXCHANGE_CODE_FOR_TOKEN_METHODS = ['GET', 'POST', 'PUT', 'PATCH'] as const;
export const DEFAULT_EXCHANGE_CODE_FOR_TOKEN_METHOD = 'POST';
export const OAUTH_RESPONSE_ACK = 'react-use-oauth2-response-ack';
2 changes: 1 addition & 1 deletion src/components/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export const cleanupChannel = (
channel: BroadcastChannel
) => {
clearInterval(intervalRef.current);
console.log('channel', channel, popupRef.current, popupRef.current?.close);
console.log('channel clean up called', channel, popupRef.current, popupRef.current?.close);
if (popupRef.current && typeof popupRef.current.close === 'function') closePopup(popupRef);
channel.close();
};
Expand Down
6 changes: 5 additions & 1 deletion src/components/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { OAUTH_RESPONSE, EXCHANGE_CODE_FOR_TOKEN_METHODS } from './constants';
import { OAUTH_RESPONSE, EXCHANGE_CODE_FOR_TOKEN_METHODS, OAUTH_RESPONSE_ACK } from './constants';

export type TAuthTokenPayload = {
token_type: string;
Expand Down Expand Up @@ -52,6 +52,10 @@ export type TMessageData =
| {
type: typeof OAUTH_RESPONSE;
payload: any;
}
| {
type: typeof OAUTH_RESPONSE_ACK;
payload: any;
};

type RequireOnlyOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyof T, Keys>> &
Expand Down
20 changes: 15 additions & 5 deletions src/components/use-oauth2.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { useCallback, useRef, useState } from 'react';
import useLocalStorageState from 'use-local-storage-state';
import { DEFAULT_EXCHANGE_CODE_FOR_TOKEN_METHOD, OAUTH_RESPONSE } from './constants';
import {
DEFAULT_EXCHANGE_CODE_FOR_TOKEN_METHOD,
OAUTH_RESPONSE,
OAUTH_RESPONSE_ACK,
} from './constants';
import {
channelPostMessage,
cleanupChannel,
formatAuthorizeUrl,
formatExchangeCodeForTokenServerURL,
Expand All @@ -24,6 +29,8 @@ export const useOAuth2 = <TData = TAuthTokenPayload>(props: TOauth2Props<TData>)
onError,
} = props;

const [isAcknowledged, setIsAcknowledged] = useState(false);

useCheckProps<TData>(props);
const extraQueryParametersRef = useRef(extraQueryParameters);
const popupRef = useRef<Window | null>();
Expand All @@ -46,7 +53,7 @@ export const useOAuth2 = <TData = TAuthTokenPayload>(props: TOauth2Props<TData>)
);

const getAuth = useCallback(() => {
const channel = new BroadcastChannel('oauth_channel');
const channel = new BroadcastChannel('refrens_oauth_channel');
// 1. Init
setUI({
loading: true,
Expand Down Expand Up @@ -137,6 +144,9 @@ export const useOAuth2 = <TData = TAuthTokenPayload>(props: TOauth2Props<TData>)
if (onError) await onError(genericError.toString());
} finally {
// Clear stuff ...
channelPostMessage(channel, { type: OAUTH_RESPONSE_ACK, payload: 'ack' });
setIsAcknowledged(true);
console.log('messsage sent', 'ack');
console.log(
'channel',
channel,
Expand All @@ -150,8 +160,6 @@ export const useOAuth2 = <TData = TAuthTokenPayload>(props: TOauth2Props<TData>)
// eslint-disable-next-line unicorn/prefer-add-event-listener
channel.onmessage = handleBroadcastChannelMessage;

console.log('channel', channel, popupRef.current, popupRef.current?.close, 'outside');

// 4. Begin interval to check if popup was closed forcefully by the user
intervalRef.current = setInterval(() => {
const popupClosed = !popupRef.current?.window || popupRef.current?.window?.closed;
Expand All @@ -161,7 +169,9 @@ export const useOAuth2 = <TData = TAuthTokenPayload>(props: TOauth2Props<TData>)
...ui,
loading: false,
}));
console.warn('Warning: Popup was closed before completing authentication.');
if (!isAcknowledged) {
console.warn('Warning: Popup was closed before completing authentication.');
}
cleanupChannel(intervalRef, popupRef, channel);
}
}, 250);
Expand Down

0 comments on commit d208ac9

Please sign in to comment.