-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Use context provider to ensure 1 onauthstatechange listener exi…
…st for the whole app
- Loading branch information
1 parent
654c3b5
commit eb91ce2
Showing
14 changed files
with
143 additions
and
128 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,39 +1,43 @@ | ||
import { useEffect } from 'react' | ||
import { useSelector } from 'react-redux' | ||
import { useRouter } from 'next/router' | ||
import { useAuth } from '@/lib/hooks/useAuth' | ||
|
||
import LoadingCover from '@/common/layout/loadingcover' | ||
import WithAuth from '@/common/auth/withauth' | ||
|
||
/** | ||
* HOC that listens for the Firebase user auth info from the global "user" redux states set by the useAuth() hook. | ||
* Displays a loading cover page while waiting for the remote authentication info to settle in. | ||
* Displays and returns the contents (children) of a tree if there is a signed-in user from the remote auth. | ||
* Displays and returns the Component parameter if there is user data from the remote auth. | ||
* Redirect to the /login page if there is no user info after the remote auth settles in. | ||
* @param {Component} children | ||
* @returns {Component} | ||
* @param {Component} Component | ||
* @returns {Component} (Component parameter or a Loading placeholder component) | ||
* Usage: export default ProtectedPage(MyComponent) | ||
*/ | ||
function ProtectedPage ({ children }) { | ||
const router = useRouter() | ||
const { authLoading, authUser } = useSelector(state => state.user) | ||
function ProtectedPage (Component) { | ||
function AuthListener (props) { | ||
const router = useRouter() | ||
const { authLoading, authError, authUser } = useAuth() | ||
|
||
useEffect(() => { | ||
if (!authLoading && !authUser) { | ||
router.push('/login') | ||
} | ||
}, [authUser, authLoading, router]) | ||
useEffect(() => { | ||
if (!authLoading && !authUser) { | ||
router.push('/login') | ||
} | ||
}, [authUser, authLoading, router]) | ||
|
||
const ItemComponent = () => { | ||
if (authLoading) { | ||
return <LoadingCover /> | ||
} else if (authUser) { | ||
return <div> | ||
{children} | ||
</div> | ||
} else { | ||
return <LoadingCover /> | ||
const ItemComponent = () => { | ||
if (authLoading) { | ||
return <LoadingCover /> | ||
} else if (authUser) { | ||
return <Component {...props} /> | ||
} else { | ||
return <LoadingCover authError={authError} /> | ||
} | ||
} | ||
|
||
return (<ItemComponent />) | ||
} | ||
|
||
return (<ItemComponent />) | ||
return AuthListener | ||
} | ||
|
||
export default WithAuth(ProtectedPage) | ||
export default ProtectedPage |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
import { useEffect, createContext, useContext } from 'react' | ||
import { useDispatch, useSelector } from 'react-redux' | ||
import { authErrorReceived, authReceived } from '@/store/users/userSlice' | ||
import { authSignOut } from '@/lib/store/users/userThunk' | ||
import { auth, onAuthStateChanged } from '@/lib/utils/firebase/config' | ||
|
||
/** | ||
* Context provider that listens for the Firebase user auth info using the Firebase onAuthStateChanged() method. | ||
* Sets the global Firebase user auth details in the user { authUser, authLoading, authError, authStatus } redux store. | ||
* Also returns the user { authUser, authLoading, authError, authStatus } redux data for convenience. | ||
* @returns {Object} authUser - partial, relevant signed-in Firebase user data | ||
* @returns {Bool} authLoading - Firebase auth status is being fetched from Firebase (from intial page load or during sign-out) | ||
* @returns {String} authError - Firebase authentication error | ||
* @returns {String} authStatus - Descriptive Auth status info. One of USER_STATES | ||
* Usage: const { authUser, authLoading, authError, authStatus } = useAuth() | ||
*/ | ||
|
||
const AuthContext = createContext() | ||
|
||
export function AuthProvider ({ children }) { | ||
const authUser = useFirebaseAuth() | ||
return <AuthContext.Provider value={authUser}>{children}</AuthContext.Provider> | ||
} | ||
|
||
export const useAuth = () => { | ||
return useContext(AuthContext) | ||
} | ||
|
||
function useFirebaseAuth () { | ||
const { authUser, authLoading, authStatus, authError } = useSelector(state => state.user) | ||
const dispatch = useDispatch() | ||
|
||
useEffect(() => { | ||
const handleFirebaseUser = async (firebaseUser) => { | ||
if (firebaseUser) { | ||
// Check if user is emailVerified | ||
if (!firebaseUser?.emailVerified ?? false) { | ||
dispatch(authSignOut('Email not verified. Please verify your email first.')) | ||
return | ||
} | ||
|
||
try { | ||
// Retrieve the custom claims information | ||
const { claims } = await firebaseUser.getIdTokenResult() | ||
|
||
if (claims.account_level) { | ||
// Get the firebase auth items of interest | ||
dispatch(authReceived({ | ||
uid: firebaseUser.uid, | ||
email: firebaseUser.email, | ||
name: firebaseUser.displayName, | ||
accessToken: firebaseUser.accessToken, | ||
emailVerified: firebaseUser.emailVerified, | ||
account_level: claims.account_level | ||
})) | ||
} else { | ||
// User did not sign-up using the custom process | ||
dispatch(authSignOut('Missing custom claims')) | ||
} | ||
} catch (err) { | ||
dispatch(authErrorReceived(err?.response?.data ?? err.message)) | ||
dispatch(authReceived(null)) | ||
} | ||
} else { | ||
// No user is signed-in | ||
dispatch(authReceived(null)) | ||
} | ||
} | ||
|
||
const unsubscribe = onAuthStateChanged(auth, handleFirebaseUser) | ||
return () => unsubscribe() | ||
}, [dispatch]) | ||
|
||
return { | ||
authUser, | ||
authLoading, | ||
authStatus, | ||
authError, | ||
authSignOut | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.