fix: redirect to previous page after login (#5102)

* Added redirect handling to autologin and Protected Route

* Redirect after login on ProtectedLoginRoute
This commit is contained in:
Lucas Oliveira 2024-12-06 12:01:13 -03:00 • committed by GitHub
commit 156597d3d1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 25 additions and 7 deletions

View file

@ -31,7 +31,18 @@ export const ProtectedRoute = ({ children }) => {
} }
}, [isAuthenticated]); }, [isAuthenticated]);
if (!isAuthenticated && autoLogin !== undefined && !autoLogin) { if (!isAuthenticated && autoLogin !== undefined && !autoLogin) {
return <CustomNavigate to="/login" replace />; const currentPath = window.location.pathname;
const isHomePath = currentPath === "/" || currentPath === "/flows";
const isLoginPage = location.pathname.includes("login");
return (
<CustomNavigate
to={
"/login" +
(!isHomePath && !isLoginPage ? "?redirect=" + currentPath : "")
}
replace
/>
);
} else { } else {
return children; return children;
} }

View file

@ -5,12 +5,14 @@ export const ProtectedLoginRoute = ({ children }) => {
const autoLogin = useAuthStore((state) => state.autoLogin); const autoLogin = useAuthStore((state) => state.autoLogin);
const isAuthenticated = useAuthStore((state) => state.isAuthenticated); const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
if (autoLogin === true) { if (autoLogin === true || isAuthenticated) {
return <CustomNavigate to="/" replace />; const urlParams = new URLSearchParams(window.location.search);
} const redirectPath = urlParams.get("redirect");
if (isAuthenticated) { if (redirectPath) {
return <CustomNavigate to="/" replace />; return <CustomNavigate to={redirectPath} replace />;
}
return <CustomNavigate to="/home" replace />;
} }
return children; return children;

View file

@ -44,7 +44,12 @@ export const useGetAutoLogin: useQueryFunctionType<undefined, undefined> = (
if (!isLoginPage) { if (!isLoginPage) {
if (!isAuthenticated) { if (!isAuthenticated) {
await mutationLogout(); await mutationLogout();
navigate("/login"); const currentPath = window.location.pathname;
const isHomePath = currentPath === "/" || currentPath === "/flows";
navigate(
"/login" +
(!isHomePath && !isLoginPage ? "?redirect=" + currentPath : ""),
);
} else { } else {
getUser(); getUser();
} }