Created user store and added auth hooks across all pages

This commit is contained in:
Meliora Ho 2024-03-02 18:28:36 +00:00
parent 597b5ede58
commit c940acfde7
5 changed files with 54 additions and 3 deletions

View File

@ -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]);

View File

@ -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;

View File

@ -7,6 +7,10 @@ export default function RootLayout({
children: React.ReactNode
}) {
return (
<StoreProvider>{children}</StoreProvider>
<html>
<body>
<StoreProvider>{children}</StoreProvider>
</body>
</html>
)
}

View File

@ -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]);

View File

@ -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
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);
};
};