Частный маршрут React router получает доступ к маршрутам, к которым он не должен обращаться - PullRequest
1 голос
/ 05 мая 2020

Это приложение имеет учетную запись для входа / регистрации и учетную запись Google OAuth.

Моя проблема заключается в сообщении частного маршрута к без доступа к маршрутам аутентификации, таким как панель инструментов / профиль редактирования и т. Д. c. При выходе из системы googleOauth .

Например, эта панель навигации делает именно то, что я хочу, но этот logi c не работает в компоненте частного маршрута.

его этот logi c

props.isAuthenticated === true || props.googleAccount != ""

поэтому, если isAuthenticated (обычная учетная запись) имеет значение true, показывать эти аутентифицированные навигационные кнопки, или если googleAccount вошел в систему, показывать аутентифицированные навигационные кнопки. Я хочу реализовать этот же logi c в частном маршруте, но он не защищает ни один из маршрутов.

props.googleAccount - это просто строка (googleId)

props.isAuthenticated является логическим

Router.tsx

const user = props.currentUser.user ? props.currentUser.user : "";
    const googleId = props.currentUser && props.currentUser.user ? props.currentUser.user.googleId : null;
    console.log("router", user);
    console.log("dsdsdsds", props.googleAccount);
    return props.hasError ? (
        <div>Error</div>
    ) : (
        <Router history={history}>
            <AppBar position="static">
                <Toolbar>
                    <Grid justify="space-between" container={true}>
                        <Typography variant="h6" style={{ color: "#fff" }}>
                            TypeScript React App
                        </Typography>
                        <Grid item={true}>
                            {props.isAuthenticated === true || props.googleAccount != "" ? (
                                <Fragment>
                                    <Button>
                                        <Link
                                            style={{
                                                color: "#fff",
                                                fontWeight: "500",
                                                textDecoration: "none",
                                            }}
                                            to="/"
                                        >
                                            Home
                                        </Link>
                                    </Button>
                                    <Button>
                                        <Link
                                            style={{
                                                color: "#fff",
                                                textDecoration: "none",
                                                fontWeight: "500",
                                            }}
                                            to="/dashboard"
                                        >
                                            Dashboard
                                        </Link>
                                    </Button>
                                    <Button>
                                        <Link
                                            style={{
                                                color: "#fff",
                                                textDecoration: "none",
                                                fontWeight: "500",
                                            }}
                                            to={{
                                                pathname: `/${user.id}/likes`,
                                            }}
                                        >
                                            Your Likes
                                        </Link>
                                    </Button>
                                    <Button>
                                        <Link
                                            style={{
                                                color: "#fff",
                                                fontWeight: "500",
                                                textDecoration: "none",
                                            }}
                                            to="/editProfile"
                                        >
                                            Edit Profile
                                        </Link>
                                    </Button>
                                    <Notification
                                        userId={user.id}
                                        id={id}
                                        handleClose={handleClose}
                                        open={open}
                                        anchorEl={anchorEl}
                                        handleNotificationClick={handleNotificationClick}
                                        title={"Notifications"}
                                    />
                                    <Button>
                                        <Link
                                            style={{
                                                color: "#fff",
                                                fontWeight: "500",
                                                textDecoration: "none",
                                            }}
                                            to={{
                                                pathname: `/profile/${user.username}`,
                                            }}
                                        >
                                            Profile
                                        </Link>
                                    </Button>
                                    <Button style={{ color: "#fff" }} onClick={props.logOut}>
                                        Logout
                                    </Button>
                                </Fragment>
                            ) : (
                                <Fragment>
                                    <Button>
                                        <Link
                                            style={{
                                                color: "#fff",
                                                fontWeight: "500",
                                                textDecoration: "none",
                                            }}
                                            to="/"
                                        >
                                            Home
                                        </Link>
                                    </Button>
                                    <Button>
                                        <Link
                                            style={{
                                                color: "#fff",
                                                fontWeight: "500",
                                                textDecoration: "none",
                                            }}
                                            to="/register"
                                        >
                                            Sign Up
                                        </Link>
                                    </Button>
                                    <Button>
                                        <Link
                                            style={{
                                                color: "#fff",
                                                fontWeight: "500",
                                                textDecoration: "none",
                                            }}
                                            to="/login"
                                        >
                                            Log In
                                        </Link>
                                    </Button>
                                </Fragment>
                            )}
                        </Grid>
                    </Grid>
                </Toolbar>
            </AppBar>
            <Switch>
                <Route exact={true} path="/" component={Landing} {...props} />
                <Route path="/login" component={Login} />
                <Route path="/register" component={Register} />
                <Route path="/emailConfirmation" component={EmailConfirmation} {...props} />
                {/* <Route path='/resendEmailConfirmation'></Route> */}
                <Route path="/emailConfirmationSuccess/:userId/:token" component={EmailConfirmationSuccess} {...props} />
                <PrivateRoute exact={true} path="/profile/:username" component={Profile} {...props} />
                <PrivateRoute exact={true} path="/editProfile" component={EditProfile} {...props} />
                <PrivateRoute exact={true} path="/:userId/likes" component={Likes} {...props} />
                <PrivateRoute exact={true} path="/dashboard" component={Dashboard} {...props} />
                <PrivateRoute path="/post/:id" component={Post} {...props} />
                <Route component={NotFound} />
            </Switch>
        </Router>
    );

PrivateRoute.tsx

import React from "react";
import { Redirect, Route } from "react-router-dom";
const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={(props) => (rest.isAuthenticated || rest.googleAccount != null ? <Component {...props} /> : <Redirect to={{ pathname: "/login" }} />)} />
);
export default PrivateRoute;

1 Ответ

2 голосов
/ 05 мая 2020

это может быть связано с этим условием

rest.isAuthenticated || rest.googleAccount != null

это условие возвращает истину, даже если rest.googleAccount равно "" (пустая строка)

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