Заставьте redux-auth-wrapper подождать, пока сессия будет проверена - PullRequest
0 голосов
/ 09 апреля 2020

так вот мой аутентификатор. js код:

import locationHelperBuilder from 'redux-auth-wrapper/history4/locationHelper';
import { connectedRouterRedirect } from 'redux-auth-wrapper/history4/redirect';
import { createBrowserHistory } from 'history';

// import Spinner from '../components/layout/Spinner';

const locationHelper = locationHelperBuilder({});
createBrowserHistory();

export const UserIsAdmin = connectedRouterRedirect({
  wrapperDisplayName: 'UserIsAdmin',
//   AuthenticatingComponent: Spinner,
  redirectPath: (state, ownProps) => 
    locationHelper.getRedirectQueryParam(ownProps) || '/',
  allowRedirectBack: true,
  authenticatedSelector: state => state.user.isAuthenticated && state.user.isAdmin
});

export const UserIsAuthenticated = connectedRouterRedirect({
  wrapperDisplayName: 'UserIsAuthenticated',
//   AuthenticatingComponent: Spinner,
  redirectPath: (state, ownProps) =>
    locationHelper.getRedirectQueryParam(ownProps) || '/',
  allowRedirectBack: true,
  authenticatedSelector: state => state.user.isAuthenticated
});

export const UserIsNotAuthenticated = connectedRouterRedirect({
  wrapperDisplayName: 'UserIsNotAuthenticated',
//   AuthenticatingComponent: Spinner,
  redirectPath: (state, ownProps) =>
    locationHelper.getRedirectQueryParam(ownProps) || '/',
  allowRedirectBack: true,
  authenticatedSelector: state => !state.user.isAuthenticated
});

и вот где мне нужно сделать redux-auth-wrapper для ожидания, пока я не обновлю состояние с пользовательскими данными, чтобы отправить его где бы он ни находился до обновления страницы:

const MainRoutes = ( { cookies } ) => {
    // state
    const { isAuthenticated } = useSelector( state => state.user );

    // dispatch
    const dispatch = useDispatch();

    const login = () => dispatch( loginAction() );
    const logout = () => dispatch( logoutAction() );

    // check if session is active ( cookie ) 
    useEffect(() => {
        if( !isAuthenticated ) {

            const checkSession = async () => {
                const cookie = cookies.get('token');
                if( cookie && cookie.trim() !== '' ) {
                    axiosClient.defaults.headers.Authorization = `Bearer ${ cookie }`;
                    login();
                } else logout();
            };

            checkSession()
        }

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [ cookies, isAuthenticated ]);

    return (  
        <Switch>
            <Route exact path="/" component={ Courses } />

            <Route path="/admin" component={  UserIsAdmin( Admin )  } />
            <Route path="/profile" component={  UserIsAuthenticated( Profile )  } />

            <Route exact path="/login" component={ UserIsNotAuthenticated( Login ) } />
            <Route exact path="/signin" component={ UserIsNotAuthenticated( Signin ) } />
            <Route exact path="/send-email" component={ UserIsNotAuthenticated( Email ) } />
            <Route exact path="/recover" component={ UserIsNotAuthenticated( Recover ) } />

            <Route exact path="/policy" component={ Policy } />
            <Route exact path="/usage" component={ Usage } />
            <Route exact path="/faqs" component={ FAQS } />
        </Switch>
    );
}

export default withRouter(withCookies(MainRoutes));

Здесь в основном я проверяю, существует ли сеансовый повар ie, поэтому я автоматически регистрирую пользователя. Проблема в том, что когда я go обращаюсь к некоторым route (например: / admin, который защищен и поэтому контролируется redux-auth.wrapper), и я повторно ссылаюсь на sh страницу, она всегда возвращает меня обратно в '/', потому что проверка isAuthenticated и isAdmin выполняется до того, как мой компонент MainRoutes может войти в систему пользователя, что, конечно, не проходит проверку в аутентифицированном селекторе auth. js и отправляет меня в '/'. Моя первая идея для решения этой проблемы состояла в том, чтобы сохранить эти 2 флага в localStorage, так что я перейду к предыдущему пути, даже если мой пользователь не завершил вход в систему. Но мне было интересно, есть ли какой-либо способ, в частности, сказать, чтобы приурочить -auth-wrapper, чтобы дождаться завершения моей функции useEffect.

Спасибо.

1 Ответ

0 голосов
/ 09 апреля 2020

Это должно задержать первый рендер и дать компоненту возможность проверить статус входа в систему, попробовать его.

Но мне было интересно, есть ли какой-либо способ конкретно сказать, чтобы приставить- auth-wrapper, чтобы дождаться завершения моей функции useEffect.

Примечание: решение не указано c для redux-auth-wrapper.

const MainRoutes = ( { cookies } ) => {

    const { isAuthenticated } = useSelector( state => state.user );

    /* use a state to hold the render */
    const [isFirstRender, setFirstRender] = useState(true)

    const dispatch = useDispatch();

    const login = () => dispatch( loginAction() );
    const logout = () => dispatch( logoutAction() );

    /* after the first render the user should be logged in (if previously was) */
    useEffect(() => {
        setFirstRender(false)
    }, [])

    useEffect(() => {
        if( !isAuthenticated ) {

            const checkSession = async () => {
                const cookie = cookies.get('token');
                if( cookie && cookie.trim() !== '' ) {
                    axiosClient.defaults.headers.Authorization = `Bearer ${ cookie }`;
                    login();
                } else logout();
            };

            checkSession()
        }

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [ cookies, isAuthenticated ]);

    /* If the effect checking the auth runs fast you can leave 
    the return as this, otherwise you might want to show a loading 
    indicator */
    return (
        <>  
            {!isFirstRender &&
                <Switch>
                    <Route exact path="/" component={ Courses } />
                    <Route path="/admin" component={  UserIsAdmin( Admin )  } />
                    <Route path="/profile" component={  UserIsAuthenticated( Profile )  } />
                    <Route exact path="/login" component={ UserIsNotAuthenticated( Login ) } />
                    <Route exact path="/signin" component={ UserIsNotAuthenticated( Signin ) } />
                    <Route exact path="/send-email" component={ UserIsNotAuthenticated( Email ) } />
                    <Route exact path="/recover" component={ UserIsNotAuthenticated( Recover ) } />
                    <Route exact path="/policy" component={ Policy } />
                    <Route exact path="/usage" component={ Usage } />
                    <Route exact path="/faqs" component={ FAQS } />
                </Switch>
            }
        </>
    );
}

export default withRouter(withCookies(MainRoutes));
...