Skip to content

Commit d4d7924

Browse files
add auth feature to support admin page
1 parent fc23e02 commit d4d7924

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/layouts/Auth.tsx

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import React, { useCallback, useEffect, useState } from 'react';
2+
import { useDispatch } from 'react-redux';
3+
import { setAuthenticated, setCurrentUser } from '@/store/slices/authSlice';
4+
import { getCurrentUser } from '@/apis/auth';
5+
6+
import { getToken } from '@/helpers/local-storage';
7+
import { goURL } from '@/helpers/router';
8+
9+
interface IProps {
10+
children: React.ReactElement;
11+
}
12+
13+
const Auth: React.FC<IProps> = ({ children }) => {
14+
const [renderRoute, setRenderRoute] = useState(false);
15+
const dispatch = useDispatch();
16+
17+
const fetchCurrentUser = useCallback(async () => {
18+
try {
19+
const response = await getCurrentUser();
20+
if (response && response.data) {
21+
dispatch(setAuthenticated(true));
22+
dispatch(setCurrentUser(response.data));
23+
}
24+
} catch (error) {
25+
goURL('/login');
26+
}
27+
setRenderRoute(true);
28+
}, [dispatch]);
29+
30+
useEffect(() => {
31+
if (!getToken()) {
32+
goURL('/login');
33+
setRenderRoute(true);
34+
} else {
35+
fetchCurrentUser();
36+
}
37+
// eslint-disable-next-line react-hooks/exhaustive-deps
38+
}, []);
39+
40+
return renderRoute ? children : null;
41+
};
42+
43+
export default Auth;

src/layouts/main/index.tsx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ const Main: React.FC = () => {
4444
path={path}
4545
render={props => {
4646
updateDisplayLayout(currentLayout, layout);
47+
/**
48+
* Use this for authentication like admin page
49+
*/
50+
// return (
51+
// <Auth>
52+
// <Component {...props} />
53+
// </Auth>
54+
// );
4755
return <Component {...props} />;
4856
}}
4957
{...rest}

0 commit comments

Comments
 (0)