11import { Loader } from '@openfun/cunningham-react' ;
22import { useRouter } from 'next/router' ;
3- import { PropsWithChildren } from 'react' ;
3+ import { PropsWithChildren , useEffect , useState } from 'react' ;
44
55import { Box } from '@/components' ;
66import { useConfig } from '@/core' ;
@@ -15,51 +15,63 @@ export const Auth = ({ children }: PropsWithChildren) => {
1515 const { replace, pathname } = useRouter ( ) ;
1616 const { data : config } = useConfig ( ) ;
1717
18- if ( isLoading && ! isFetchedAfterMount ) {
19- return (
20- < Box $height = "100vh" $width = "100vw" $align = "center" $justify = "center" >
21- < Loader />
22- </ Box >
23- ) ;
24- }
18+ const [ isRedirectingToLogin , setIsRedirectingToLogin ] = useState ( false ) ;
2519
2620 /**
27- * If the user is authenticated and wanted initially to access a document,
28- * we redirect to the document page.
21+ * If the user is authenticated and initially wanted to access a specific page, redirect them to that page now.
2922 */
30- if ( authenticated ) {
23+ useEffect ( ( ) => {
24+ if ( ! authenticated ) {
25+ return ;
26+ }
27+
3128 const authUrl = getAuthUrl ( ) ;
3229 if ( authUrl ) {
3330 void replace ( authUrl ) ;
34- return (
35- < Box $height = "100vh" $width = "100vw" $align = "center" $justify = "center" >
36- < Loader />
37- </ Box >
38- ) ;
31+ return ;
3932 }
40- }
33+
34+ if ( pathname === HOME_URL ) {
35+ void replace ( '/' ) ;
36+ }
37+ } , [ authenticated , pathname , replace ] ) ;
4138
4239 /**
4340 * If the user is not authenticated and the path is not allowed, we redirect to the login page.
4441 */
45- if ( ! authenticated && ! pathAllowed ) {
46- if ( config ?. FRONTEND_HOMEPAGE_FEATURE_ENABLED ) {
47- void replace ( HOME_URL ) ;
48- } else {
49- gotoLogin ( ) ;
42+ useEffect ( ( ) => {
43+ if ( isLoading || authenticated ) {
44+ return ;
5045 }
51- return (
52- < Box $height = "100vh" $width = "100vw" $align = "center" $justify = "center" >
53- < Loader />
54- </ Box >
55- ) ;
56- }
5746
58- /**
59- * If the user is authenticated and the path is the home page, we redirect to the index.
60- */
61- if ( pathname === HOME_URL && authenticated ) {
62- void replace ( '/' ) ;
47+ if ( ! authenticated && ! pathAllowed ) {
48+ if ( config ?. FRONTEND_HOMEPAGE_FEATURE_ENABLED ) {
49+ if ( pathname !== HOME_URL ) {
50+ void replace ( HOME_URL ) ;
51+ }
52+ } else {
53+ if ( ! isRedirectingToLogin ) {
54+ setIsRedirectingToLogin ( true ) ;
55+ gotoLogin ( ) ;
56+ }
57+ }
58+ }
59+ } , [
60+ authenticated ,
61+ pathAllowed ,
62+ config ?. FRONTEND_HOMEPAGE_FEATURE_ENABLED ,
63+ replace ,
64+ isLoading ,
65+ isRedirectingToLogin ,
66+ pathname ,
67+ ] ) ;
68+
69+ const shouldShowLoader =
70+ ( isLoading && ! isFetchedAfterMount ) ||
71+ isRedirectingToLogin ||
72+ ( ! authenticated && ! pathAllowed ) ;
73+
74+ if ( shouldShowLoader ) {
6375 return (
6476 < Box $height = "100vh" $width = "100vw" $align = "center" $justify = "center" >
6577 < Loader />
0 commit comments