Skip to content

Commit

Permalink
SMA-80: fixed PrivateRoute
Browse files Browse the repository at this point in the history
  • Loading branch information
ivamach committed Apr 14, 2024
1 parent 60c623b commit 96b3936
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions frontend/sportsmatch-app/src/components/PrivateRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,33 @@ import { OpenAPI, ExSecuredEndpointService, ApiError } from '../generated/api'

const PrivateRoute = () => {
const requestedUrl = window.location.pathname
const [isLoggedIn, setLoggedIn] = useState<boolean>(false)
const [isAuthorized, setAuthorized] = useState<boolean>(true)

useEffect(() => {
if (!localStorage.getItem('token')) {
setAuthorized(false)
}
},[])

Check failure on line 13 in frontend/sportsmatch-app/src/components/PrivateRoute.tsx

View workflow job for this annotation

GitHub Actions / test

Insert `·`

Check failure on line 13 in frontend/sportsmatch-app/src/components/PrivateRoute.tsx

View workflow job for this annotation

GitHub Actions / test

Insert `·`

useEffect(() => {
const init = async () => {
OpenAPI.TOKEN = localStorage.getItem('token')!
try {
await ExSecuredEndpointService.getUserMainPage()
setLoggedIn(true)
} catch (error) {
const code = (error as ApiError).status
if (code === 401 || code === 403) {
localStorage.removeItem('token')
setLoggedIn(false)
if (localStorage.getItem('token')) {
OpenAPI.TOKEN = localStorage.getItem('token')!
try {
await ExSecuredEndpointService.getUserMainPage()
} catch (error) {
const code = (error as ApiError).status
if (code === 401 || code === 403) {
localStorage.removeItem('token')
setAuthorized(false)
}
}
}
}
init()
}, [])

if (isLoggedIn) {
if (isAuthorized) {
return <Outlet />
} else {
return <Navigate to={'/login'} state={requestedUrl} />
Expand Down

0 comments on commit 96b3936

Please sign in to comment.