diff --git a/compass/app/admin/layout.tsx b/compass/app/admin/layout.tsx new file mode 100644 index 0000000..40f057b --- /dev/null +++ b/compass/app/admin/layout.tsx @@ -0,0 +1,9 @@ +import { withAuth } from '@/utils/hooks'; +import { User } from '@/utils/constants'; + +const adminLayout = () => { + return <div>Admin Page Content</div>; +}; + + +export default withAuth(adminLayout, [User.ADMIN]); diff --git a/compass/app/auth/layout.tsx b/compass/app/auth/layout.tsx new file mode 100644 index 0000000..7cc969a --- /dev/null +++ b/compass/app/auth/layout.tsx @@ -0,0 +1,9 @@ +import { withAuth } from '@/utils/hooks'; +import { User } from '@/utils/constants'; + +const authLayout = () => { + return <div>Auth Page Content</div>; +}; + + +export default authLayout; diff --git a/compass/app/layout.tsx b/compass/app/layout.tsx index 120a901..d1526bc 100644 --- a/compass/app/layout.tsx +++ b/compass/app/layout.tsx @@ -7,6 +7,10 @@ export default function RootLayout({ children: React.ReactNode }) { return ( - <StoreProvider>{children}</StoreProvider> + <html> + <body> + <StoreProvider>{children}</StoreProvider> + </body> + </html> ) } \ No newline at end of file diff --git a/compass/app/resource/layout.tsx b/compass/app/resource/layout.tsx new file mode 100644 index 0000000..0e5c63f --- /dev/null +++ b/compass/app/resource/layout.tsx @@ -0,0 +1,9 @@ +import { withAuth } from '@/utils/hooks'; +import { User } from '@/utils/constants'; + +const resourceLayout = () => { + return <div>Resource Page Content</div>; +}; + + +export default withAuth(resourceLayout, [User.EMPLOYEE, User.VOLUNTEER]); diff --git a/compass/utils/hooks.ts b/compass/utils/hooks.ts index da466c5..6f4b279 100644 --- a/compass/utils/hooks.ts +++ b/compass/utils/hooks.ts @@ -1,8 +1,28 @@ import { useDispatch, useSelector, useStore } from 'react-redux' import type { TypedUseSelectorHook } from 'react-redux' import type { RootState, AppStore, AppDispatch } from './store' - +import React from 'react'; +import { useRouter } from 'next/router'; +import { User } from './constants'; export const useAppDispatch: () => AppDispatch = useDispatch export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector -export const useAppStore: () => AppStore = useStore \ No newline at end of file +export const useAppStore: () => AppStore = useStore + +// TODO - debug this auth hook +export const withAuth = (WrappedComponent: React.ComponentType<any>, allowedUserTypes: User[] = []) => { + return (props: any) => { + const router = useRouter(); + const { isLoggedIn, userType } = useAppSelector((state: RootState) => state.user); + + React.useEffect(() => { + if (!isLoggedIn) { + router.push('/auth'); + } else if (userType && !allowedUserTypes.includes(userType)) { + router.push(userType === User.ADMIN ? '/admin' : '/resource'); + } + }, [isLoggedIn, userType, router, allowedUserTypes]); + + return isLoggedIn ? <WrappedComponent {...props} /> : (null); + }; + }; \ No newline at end of file