Skip to content

Commit

Permalink
fix(auth.provider): validate token when page changed
Browse files Browse the repository at this point in the history
  • Loading branch information
joonas-yoon committed Sep 14, 2022
1 parent 20220cf commit bc39a53
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 20 deletions.
37 changes: 18 additions & 19 deletions react-app/src/components/AuthProvider.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,25 @@ export const useAuth = () => {

export const AuthProvider = ({ afterLogin, children }) => {
const navigate = useNavigate();
const [isAuthenticated, setAuthenticated] = useState(false);
const location = useLocation();

const TOKEN_NAME = 'access_token';
const getAuthenticated = async () => {
const result = await customAxios()
.get('auth/authenticated-route')
.then(() => true)
.catch(() => false);
setAuthenticated(result);
};

const token = useMemo(() => {
return storage.get(TOKEN_NAME);
}, [storage]);
useEffect(() => {
getAuthenticated();
}, [location]);

const [isAuthenticated, setAuthenticated] = useState(false);
const TOKEN_NAME = 'access_token';
const token = storage.get(TOKEN_NAME);

useEffect(() => {
customAxios()
.get('/users/me')
.then((res) => {
console.log(res.response);
setAuthenticated(true);
})
.catch(() => {
setAuthenticated(false);
});
}, [token]);
console.log('[Provider] token:', token);

const storeToken = (accessToken) => {
storage.set(TOKEN_NAME, accessToken);
Expand All @@ -48,7 +47,7 @@ export const AuthProvider = ({ afterLogin, children }) => {
const url = new URL(location.href);
const next = url.searchParams.get('next');
const redirectUrl = afterLogin || next || '/';
navigate(redirectUrl === '/login' ? '/' : redirectUrl);
navigate(redirectUrl);
};

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

export const ProtectedRoute = ({ redirectTo, children }) => {
const { token, isAuthenticated } = useAuth();
const { isAuthenticated } = useAuth();
const location = useLocation();

console.log('token', token, 'isAuthenticated', isAuthenticated);
console.log('isAuthenticated', isAuthenticated);

if (!isAuthenticated) {
const origin = location?.origin || window.location.origin;
Expand Down
4 changes: 3 additions & 1 deletion react-app/src/pages/Auth.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ export const Login = () => {
status: null,
message: '',
});
const { login } = useAuth();
const { login, isAuthenticated } = useAuth();
const location = useLocation();

console.log('Component rendered: isAuthenticated', isAuthenticated);

const onSubmit = (username, password) => {
const formData = qs.stringify({
username,
Expand Down

0 comments on commit bc39a53

Please sign in to comment.