Skip to content

Commit

Permalink
[SOK-32]
Browse files Browse the repository at this point in the history
*fix after review PR
  • Loading branch information
gloginov committed Oct 11, 2024
1 parent 723d177 commit bedf831
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 42 deletions.
1 change: 1 addition & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ DOCKER_BUILDKIT=1 #Build only stages required for target
COMPOSE_FILE=docker-compose.yml:docker-compose.dev.yml
VITE_AUTH_URL='https://ya-praktikum.tech/api/v2'
VITE_SRC_URL='https://ya-praktikum.tech/api/v2/resources'
VITE_AUTH_PATHNAMES='/sign-in, /sign-up'
49 changes: 22 additions & 27 deletions packages/client/src/components/hoc/withAuthUser.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { ComponentType, useEffect } from 'react'
import { actions, getUser, UserType } from '@/store/reducers/auth-reducer'
import { UserType } from '@/store/reducers/auth-reducer'
import { toast } from 'react-toastify'
import { useNavigate, useLocation } from 'react-router-dom'
import { RootState, useAppDispatch } from '@/store'
import { useSelector } from 'react-redux'
import { userService } from '@/services/userService'

type WithAuthUserProps = {
userIsLogged: boolean
Expand All @@ -18,42 +19,36 @@ export default function withAuthUser<P extends object>(
const user = useSelector<RootState, UserType>(
state => state.authReducer.user
)
const userIsLogged = window.sessionStorage.getItem('userIsLogged') === '1'
const userIsLogged = userService.isLoggedIn()
const navigate = useNavigate()
const dispatch = useAppDispatch()
const location = useLocation()
const { pathname } = location
const { pathname } = useLocation()
const isAuthPath = import.meta.env.VITE_AUTH_PATHNAMES.split(', ').includes(
pathname
)

const handleAuthentication = async () => {
const isAuthenticated = await userService.fetchUser(dispatch)

const successAuth = (redirectTo: string) => {
toast.success('Вы уже авторизованы')
navigate(redirectTo)
if (!isAuthenticated && !isAuthPath) {
toast.error('Необходимо авторизоваться', { autoClose: 1500 })
navigate('/sign-in')
}
}

useEffect(() => {
if (!userIsLogged || user === null) {
dispatch(getUser())
.unwrap()
.then(data => {
dispatch(actions.setUser(data))
window.sessionStorage.setItem('userIsLogged', '1') // 0

if (redirectTo) {
successAuth(redirectTo)
}
})
.catch(() => {
window.sessionStorage.setItem('userIsLogged', '0') // 1

if (!['/sign-in', '/sign-up'].includes(pathname)) {
toast.error('Необходимо авторизоваться')
navigate('/sign-in')
}
})
handleAuthentication()
} else if (redirectTo) {
successAuth(redirectTo)
toast.success('Вы уже авторизованы', { autoClose: 1500 })
navigate(redirectTo)
}
}, [user, userIsLogged])

return <Component {...props} userIsLogged={userIsLogged} user={user} />
if (userIsLogged || isAuthPath) {
return <Component {...props} userIsLogged={userIsLogged} user={user} />
}

return <h1>Загрузка...</h1>
}
}
23 changes: 9 additions & 14 deletions packages/client/src/layouts/PrivateLayout/PrivateLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,14 @@ import { Outlet } from 'react-router-dom'
import withAuthUser from '@/components/hoc/withAuthUser'
import './PrivateLayout.scss'

const PrivateLayout = (props: any & { userIsLogged: boolean }) => {
const { userIsLogged } = props

if (userIsLogged) {
return (
<div className="private-layout">
<Header className="private-layout__header"></Header>
<main className="private-layout__body">
<Outlet />
</main>
</div>
)
}
return <h1>Загрузка...</h1>
const PrivateLayout = () => {
return (
<div className="private-layout">
<Header className="private-layout__header"></Header>
<main className="private-layout__body">
<Outlet />
</main>
</div>
)
}
export default withAuthUser(PrivateLayout)
20 changes: 20 additions & 0 deletions packages/client/src/services/userService.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { actions, UserType, getUser } from '@/store/reducers/auth-reducer'
import { useAppDispatch } from '@/store'

export const userService = {
async fetchUser(dispatch: ReturnType<typeof useAppDispatch>) {
try {
const data: UserType = await dispatch(getUser()).unwrap()
dispatch(actions.setUser(data))
window.sessionStorage.setItem('userIsLogged', '1')
return true
} catch {
window.sessionStorage.setItem('userIsLogged', '0')
return false
}
},

isLoggedIn() {
return window.sessionStorage.getItem('userIsLogged') === '1'
},
}
2 changes: 1 addition & 1 deletion packages/client/src/store/reducers/auth-reducer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { AppDispatch, InferAppActions } from '@/store'
import { InferAppActions } from '@/store'
import backendApi from '@/api/backendApi'

export type UserType = {
Expand Down

0 comments on commit bedf831

Please sign in to comment.