diff --git a/src/components/Routes/AuthRoute.jsx b/src/components/Routes/AuthRoute.jsx new file mode 100644 index 0000000..16565f7 --- /dev/null +++ b/src/components/Routes/AuthRoute.jsx @@ -0,0 +1,16 @@ +import { Navigate } from 'react-router-dom'; +import { useSelector } from 'react-redux'; +import { + selectIsLoggedIn, + selectIsRefreshing, +} from '../../redux/auth/selectors'; + +const AuthRoute = ({ component: Component, redirectTo = '/' }) => { + const isLoggedIn = useSelector(selectIsLoggedIn); + const isRefreshing = useSelector(selectIsRefreshing); + + const shouldRedirect = !isLoggedIn && !isRefreshing; + return shouldRedirect ? : ; +}; + +export default AuthRoute; diff --git a/src/components/Routes/GuestRoute.jsx b/src/components/Routes/GuestRoute.jsx new file mode 100644 index 0000000..f80dfb6 --- /dev/null +++ b/src/components/Routes/GuestRoute.jsx @@ -0,0 +1,11 @@ +import { Navigate } from 'react-router-dom'; +import { useSelector } from 'react-redux'; +import { selectIsLoggedIn } from '../../redux/auth/selectors'; + +const GuestRoute = ({ component: Component, redirectTo = '/' }) => { + const isLoggedIn = useSelector(selectIsLoggedIn); + + return isLoggedIn ? : ; +}; + +export default GuestRoute; diff --git a/src/redux/auth/slice.js b/src/redux/auth/slice.js index e69de29..9392c0e 100644 --- a/src/redux/auth/slice.js +++ b/src/redux/auth/slice.js @@ -0,0 +1,46 @@ +import { createSlice } from '@reduxjs/toolkit'; +import { register, logIn, logOut, refreshUser } from './operations'; + +const initialState = { + user: { name: null, email: null }, + token: null, + isLoggedIn: false, + isRefreshing: false, +}; + +const authSlice = createSlice({ + name: 'auth', + initialState, + reducers: {}, + extraReducers: builder => { + builder + .addCase(register.fulfilled, (state, action) => { + state.user = action.payload.user; + state.token = action.payload.token; + state.isLoggedIn = true; + }) + .addCase(logIn.fulfilled, (state, action) => { + state.user = action.payload.user; + state.token = action.payload.token; + state.isLoggedIn = true; + }) + .addCase(logOut.fulfilled, (state, action) => { + state.user = action.payload.user; + state.token = action.payload.token; + state.isLoggedIn = false; + }) + .addCase(refreshUser.pending, state => { + state.isRefreshing = true; + }) + .addCase(refreshUser.fulfilled, (state, action) => { + state.user = action.payload; + state.isLoggedIn = true; + state.isRefreshing = false; + }) + .addCase(refreshUser.rejected, state => { + state.isRefreshing = false; + }); + }, +}); + +export const authReducer = authSlice.reducer;