Skip to content

Commit

Permalink
Merge pull request #14 from Ryczko/unauthenticated_user_redirections
Browse files Browse the repository at this point in the history
Redirecting signed out user
  • Loading branch information
xdk78 authored Apr 22, 2022
2 parents f38df04 + d6c2645 commit e28106a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
21 changes: 21 additions & 0 deletions src/Components/ProtectedRoute/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Navigate, useLocation } from 'react-router-dom';
import { auth } from '../../firebase';
import { useAuthState } from 'react-firebase-hooks/auth';

type ProtectedRouteProps = {
children: JSX.Element;
};

const ProtectedRoute = ({ children }: ProtectedRouteProps) => {
const [user, loading, error] = useAuthState(auth);
const isLoggedIn = user && !loading && !error;
const location = useLocation();

if (!isLoggedIn) {
return <Navigate to="/login" state={{ from: location }} replace />;
} else {
return children;
}
};

export default ProtectedRoute;
28 changes: 24 additions & 4 deletions src/Pages/PageWrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { lazy, Suspense } from 'react';
import { Routes, Route, BrowserRouter, Navigate } from 'react-router-dom';
import ProtectedRoute from '../Components/ProtectedRoute';
import Navigation from '../Layouts/Navigation';
import HomePage from './HomePage';

Expand All @@ -26,13 +27,32 @@ function PageWrapper() {
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/survey/create" element={<SurveyCreatePage />} />
<Route
path="/survey/create"
element={
<ProtectedRoute>
<SurveyCreatePage />
</ProtectedRoute>
}
/>
<Route path="/survey/:surveyId" element={<SurveyPage />} />
<Route path="/surveys" element={<SurveyListPage />} />
<Route
path="/surveys"
element={
<ProtectedRoute>
<SurveyListPage />
</ProtectedRoute>
}
/>
<Route
path="/survey/answer/:answerId"
element={<SurveyAnswerPage />}
element={
<ProtectedRoute>
<SurveyAnswerPage />
</ProtectedRoute>
}
/>

<Route path="*" element={<Navigate to="/" />} />
</Routes>
</Suspense>
Expand All @@ -41,4 +61,4 @@ function PageWrapper() {
);
}

export default PageWrapper;
export default PageWrapper;

0 comments on commit e28106a

Please sign in to comment.