1
1
import { useEffect , useCallback } from 'react' ;
2
2
import { getOAuthLogoutUrl , getOAuthOrigin } from '../constants/' ;
3
+ import { useIsOAuth2Enabled } from './useIsOAuth2Enabled' ;
3
4
4
5
type MessageEvent = {
5
6
data : 'logout_complete' | 'logout_error' ;
6
7
origin : string ;
7
8
} ;
8
9
10
+ type hydraBEApps = {
11
+ enabled_for : number [ ] ;
12
+ } ;
13
+
14
+ type OAuth2Config = {
15
+ OAuth2EnabledApps : hydraBEApps [ ] ;
16
+ OAuth2EnabledAppsInitialised : boolean ;
17
+ } ;
18
+
9
19
/**
10
20
* Custom hook to handle OAuth2 logout and redirection.
11
21
*
22
+ * @param {OAuth2Config } config - Configuration object containing OAuth2 enabled apps and initialisation flag.
12
23
* @param {(oauthUrl: string) => Promise<void> } WSLogoutAndRedirect - Function to handle logout and redirection.
13
24
* @returns {{ OAuth2Logout: () => Promise<void> } } - Object containing the OAuth2Logout function.
14
25
*/
15
- export const useOAuth2 = ( WSLogoutAndRedirect : ( ) => Promise < void > ) => {
26
+ export const useOAuth2 = ( OAuth2GrowthBookConfig : OAuth2Config , WSLogoutAndRedirect : ( ) => Promise < void > ) => {
27
+ const { OAuth2EnabledApps, OAuth2EnabledAppsInitialised } = OAuth2GrowthBookConfig ;
28
+ const isOAuth2Enabled = useIsOAuth2Enabled ( OAuth2EnabledApps , OAuth2EnabledAppsInitialised ) ;
29
+
16
30
useEffect ( ( ) => {
31
+ if ( ! isOAuth2Enabled ) return ;
32
+
17
33
const onMessage = async ( event : MessageEvent ) => {
18
34
const allowedOrigin = getOAuthOrigin ( ) ;
19
35
if ( allowedOrigin === event . origin ) {
@@ -29,9 +45,14 @@ export const useOAuth2 = (WSLogoutAndRedirect: () => Promise<void>) => {
29
45
30
46
window . addEventListener ( 'message' , onMessage ) ;
31
47
return ( ) => window . removeEventListener ( 'message' , onMessage ) ;
32
- } , [ WSLogoutAndRedirect ] ) ;
48
+ } , [ isOAuth2Enabled , WSLogoutAndRedirect ] ) ;
33
49
34
50
const OAuth2Logout = useCallback ( async ( ) => {
51
+ if ( ! isOAuth2Enabled ) {
52
+ WSLogoutAndRedirect ( ) ;
53
+ return ;
54
+ }
55
+
35
56
let iframe : HTMLIFrameElement | null = document . getElementById ( 'logout-iframe' ) as HTMLIFrameElement ;
36
57
if ( ! iframe ) {
37
58
iframe = document . createElement ( 'iframe' ) ;
@@ -49,7 +70,7 @@ export const useOAuth2 = (WSLogoutAndRedirect: () => Promise<void>) => {
49
70
iframe . onerror = error => {
50
71
console . error ( 'There has been a problem with the logout: ' , error ) ;
51
72
} ;
52
- } , [ WSLogoutAndRedirect ] ) ;
73
+ } , [ isOAuth2Enabled , WSLogoutAndRedirect ] ) ;
53
74
54
75
return { OAuth2Logout } ;
55
76
} ;
0 commit comments