Skip to content

Commit bc39a53

Browse files
committed
fix(auth.provider): validate token when page changed
1 parent 20220cf commit bc39a53

File tree

2 files changed

+21
-20
lines changed

2 files changed

+21
-20
lines changed

react-app/src/components/AuthProvider.jsx

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,25 @@ export const useAuth = () => {
1616

1717
export const AuthProvider = ({ afterLogin, children }) => {
1818
const navigate = useNavigate();
19+
const [isAuthenticated, setAuthenticated] = useState(false);
20+
const location = useLocation();
1921

20-
const TOKEN_NAME = 'access_token';
22+
const getAuthenticated = async () => {
23+
const result = await customAxios()
24+
.get('auth/authenticated-route')
25+
.then(() => true)
26+
.catch(() => false);
27+
setAuthenticated(result);
28+
};
2129

22-
const token = useMemo(() => {
23-
return storage.get(TOKEN_NAME);
24-
}, [storage]);
30+
useEffect(() => {
31+
getAuthenticated();
32+
}, [location]);
2533

26-
const [isAuthenticated, setAuthenticated] = useState(false);
34+
const TOKEN_NAME = 'access_token';
35+
const token = storage.get(TOKEN_NAME);
2736

28-
useEffect(() => {
29-
customAxios()
30-
.get('/users/me')
31-
.then((res) => {
32-
console.log(res.response);
33-
setAuthenticated(true);
34-
})
35-
.catch(() => {
36-
setAuthenticated(false);
37-
});
38-
}, [token]);
37+
console.log('[Provider] token:', token);
3938

4039
const storeToken = (accessToken) => {
4140
storage.set(TOKEN_NAME, accessToken);
@@ -48,7 +47,7 @@ export const AuthProvider = ({ afterLogin, children }) => {
4847
const url = new URL(location.href);
4948
const next = url.searchParams.get('next');
5049
const redirectUrl = afterLogin || next || '/';
51-
navigate(redirectUrl === '/login' ? '/' : redirectUrl);
50+
navigate(redirectUrl);
5251
};
5352

5453
const handleLogout = () => {
@@ -67,10 +66,10 @@ export const AuthProvider = ({ afterLogin, children }) => {
6766
};
6867

6968
export const ProtectedRoute = ({ redirectTo, children }) => {
70-
const { token, isAuthenticated } = useAuth();
69+
const { isAuthenticated } = useAuth();
7170
const location = useLocation();
7271

73-
console.log('token', token, 'isAuthenticated', isAuthenticated);
72+
console.log('isAuthenticated', isAuthenticated);
7473

7574
if (!isAuthenticated) {
7675
const origin = location?.origin || window.location.origin;

react-app/src/pages/Auth.jsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@ export const Login = () => {
1212
status: null,
1313
message: '',
1414
});
15-
const { login } = useAuth();
15+
const { login, isAuthenticated } = useAuth();
1616
const location = useLocation();
1717

18+
console.log('Component rendered: isAuthenticated', isAuthenticated);
19+
1820
const onSubmit = (username, password) => {
1921
const formData = qs.stringify({
2022
username,

0 commit comments

Comments
 (0)