Skip to content

Commit

Permalink
fix: Possibly better 401 handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Veikkosuhonen committed Dec 4, 2023
1 parent 298b97c commit 573c922
Show file tree
Hide file tree
Showing 6 changed files with 27 additions and 32 deletions.
33 changes: 13 additions & 20 deletions src/client/Error.tsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,29 @@
import { Box, Button, Typography } from '@mui/joy'
import { useEffect } from 'react'
import { isRouteErrorResponse, useNavigate, useRouteError } from 'react-router-dom'
import * as Sentry from '@sentry/browser'
import { useTranslation } from 'react-i18next'
import { handleLogin } from './util/login'
import { useCurrentUser } from './hooks/useCurrentUser'
import { AxiosError } from 'axios'

export const Error = () => {
const { t } = useTranslation()
const user = useCurrentUser()
const error = useRouteError() as any
const navigate = useNavigate()

useEffect(() => {
if (isRouteErrorResponse(error)) {
console.log('Route error: ', error)
if (error.status === 401) {
handleLogin()
return
}
} else if (error instanceof AxiosError) {
console.log('Axios error: ', error)
if (error.response?.status === 401) {
handleLogin()
return
}
} else {
console.log('Unknown error: ', error)
Sentry.captureException(error)
if (isRouteErrorResponse(error)) {
if (error.status === 401) {
handleLogin()
return
}
}, [error, user])
} else if (error instanceof AxiosError) {
if (error.response?.status === 401) {
handleLogin()
return
}
} else {
console.log('Unknown error: ', error)
Sentry.captureException(error)
}

return (
<Box
Expand Down
9 changes: 6 additions & 3 deletions src/client/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,20 +64,23 @@ export const updateStatusAction = async ({ request, params }: ActionFunctionArgs

export const login = async () => {
const { data } = await privateClient.get('/login')

return data as UserParams
}

/**
* https://reactrouter.com/en/main/guides/data-libs
*/
export const loginLoader = () =>
queryClient.fetchQuery({
export const loginLoader = async () => {
const res = await queryClient.fetchQuery({
queryKey: ['currentUser'],
queryFn: login,
staleTime: 1000 * 60,
retry: false,
})

return res
}

export const logout = async () => {
const { data } = await privateClient.get('/logout')

Expand Down
8 changes: 2 additions & 6 deletions src/client/hooks/useCurrentUser.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import { UserParams } from '../../shared/types'
import { useQuery } from '@tanstack/react-query'
import { login } from '../api'
import { AxiosError } from 'axios'

export const useCurrentUser = () => {
const { data: user, ...rest } = useQuery<UserParams>({
const { data: user, ...rest } = useQuery<UserParams | null>({
queryKey: ['currentUser'],
queryFn: login,
retry: false,
throwOnError: (error) => {
if (error instanceof AxiosError && error.response?.status === 401) return false
return true
},
throwOnError: true,
})

return { user, ...rest }
Expand Down
2 changes: 2 additions & 0 deletions src/client/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const router = createBrowserRouter(
{
path: '',
element: <Home />,
errorElement: <Error />,
},
],
},
Expand All @@ -34,6 +35,7 @@ const router = createBrowserRouter(
{
path: '',
element: <Home />,
errorElement: <Error />,
},
{
path: 'contract-requests',
Expand Down
6 changes: 4 additions & 2 deletions src/client/util/login.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { inDevelopment, inE2E, PUBLIC_URL } from '../../config'
import { clearHeaders } from './mockHeaders'
import { clearHeaders, updateMockHeaders } from './mockHeaders'

const devLogin = () => {
clearHeaders()
window.location.pathname = '/private'
updateMockHeaders()
// window.location.pathname = '/private'
}

export const handleLogin = async () => {
console.log('Handle login')
if (inDevelopment || inE2E) return devLogin()

window.location.href = `${PUBLIC_URL}/api/oidc`
Expand Down
1 change: 0 additions & 1 deletion src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ app.listen(PORT, async () => {
await setupAuthentication()

console.log('Server running on port ' + PORT)
// logger.info(`Server running on port ${PORT}`)
})

connectToDatabase()

0 comments on commit 573c922

Please sign in to comment.