Skip to content

Commit 54005f2

Browse files
committed
Fix: Redirect /login to /dashboard if user already logged in
1 parent 6c36d1c commit 54005f2

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

course-matrix/frontend/src/App.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import Dashboard from "./pages/Dashboard/Dashboard";
55
import SignupPage from "./pages/Signup/SignUpPage";
66
import AuthRoute from "./components/auth-route";
77
import SignupSuccessfulPage from "./pages/Signup/SignupSuccessfulPage";
8+
import LoginRoute from "./components/login-route";
89

910
/**
1011
* App Component
@@ -36,7 +37,7 @@ function App() {
3637
<Route path="*" element={<Navigate to="/login" />} />
3738
<Route path="/" element={<Navigate to="/login" />} />
3839
<Route path="signup-success" element={<SignupSuccessfulPage />} />
39-
<Route path="/login" element={<LoginPage />} />
40+
<Route path="/login" element={<LoginRoute component={LoginPage} />} />
4041
<Route path="/signup" element={<SignupPage />} />
4142
<Route
4243
path="/dashboard/*"

course-matrix/frontend/src/components/auth-route.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,18 @@ interface AuthRouteProps {
66
component: React.ComponentType; // Type for the component prop
77
}
88

9+
/**
10+
* Login Route
11+
*
12+
* Checks if a user is logged in (session exists). If not then redirect to login.
13+
*/
914
const AuthRoute: React.FC<AuthRouteProps> = ({ component: Component }) => {
1015
const { data, isLoading, error } = useGetSessionQuery();
1116

1217
if (isLoading) {
1318
return <LoadingPage />;
1419
}
1520

16-
// TODO modify check based on return type of data
1721
return data?.user ? <Component /> : <Navigate to="/login" replace />;
1822
};
1923

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { useGetSessionQuery } from "@/api/authApiSlice";
2+
import { Navigate } from "react-router-dom";
3+
import LoadingPage from "@/pages/Loading/LoadingPage";
4+
5+
interface AuthRouteProps {
6+
component: React.ComponentType; // Type for the component prop
7+
}
8+
9+
/**
10+
* Login Route
11+
*
12+
* Checks if a user session exists in localstorage. If so then redirect to dashboard.
13+
*/
14+
const LoginRoute: React.FC<AuthRouteProps> = ({ component: Component }) => {
15+
const user = localStorage.getItem("userInfo");
16+
17+
return user ? <Navigate to="/dashboard" replace /> : <Component /> ;
18+
};
19+
20+
export default LoginRoute;

0 commit comments

Comments
 (0)