登录身份验证后重定向

时间:2020-02-15 22:42:07

标签: javascript reactjs typescript authentication redirect

我有一个登录屏幕,其中已通过GraphQL API实现了身份验证。身份验证工作正常,我得到了令牌,但我不知道如何继续。点击“登录”按钮后,我想重定向到/ panel页面。如果身份验证无效,则用户不应访问/ panel。

当我使用React Router时,

/ panel通常可以正常工作。但是我想在单击登录按钮后立即访问它。我怎样才能解决这个问题?

export default class LoginPage extends Component <{}, { email: string,password: string }>{
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      email: '',
      password: '',
    };
  }

  _SignIn = (e: { preventDefault: () => void; }) => {
    axios({
      url: 'https://xzy/graphql',
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        query: `
            mutation{
               loginMethod(email: "${this.state.email}",
               password: "${this.state.password}")
}`,
      },
    })
      .then((result: { data: any }) => {
        const token = JSON.stringify(result.data.data.loginEmail).slice(1,-1);
        if (token){
          alert(token)
          //return <Redirect to='/users' /> 
        }
      })
      .catch((err: any) => {
        console.log(err);
      });
      e.preventDefault();
  };


  render() {
    return (
      <Container component="main" maxWidth="xs">
        <CssBaseline />
        <div style={{
         display: 'flex',
         flexDirection: 'column',
         alignItems: 'center'}}>
          <Avatar>
            <LockOutlinedIcon />
          </Avatar>
          <Typography component="h1" variant="h5">
            Sign in
          </Typography>
          <form style={{width: '100%'}} noValidate>
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              id="email"
              label="Email Address"
              name="email"
              autoComplete="email"
              autoFocus
              onChange={e => {
                this.setState({email: e.target.value})
              }}
            />
            <TextField
              variant="outlined"
              margin="normal"
              required
              fullWidth
              name="password"
              label="Password"
              type="password"
              id="password"
              autoComplete="current-password"
              onChange={e => {
                this.setState({password: e.target.value})
            }}
            />
            <FormControlLabel
              control={<Checkbox value="remember" color="primary" />}
              label="Remember me"
            />
            <Button
            onClick={this._SignIn}
            >
            Submit</Button>
            <Grid container>
              <Grid item xs>
                <Link href="#" variant="body2">
                  Forgot password?
                </Link>
              </Grid>
            </Grid>
          </form>
        </div>
        <Box mt={8}>
          <Copyright />
        </Box>
      </Container>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您可以将“ / users”推送到历史记录,为此, 首次导入

const createHistory = require("history").createBrowserHistory;

然后添加

  let history = createHistory();
history.push("/");

确保您的index.js文件已包装 与历史

<Router history={history}>
      <div>
          <HashRouter>
        <App />
        </HashRouter>
      </div>
    </Router>

编辑2

  function App() {
  const checkAuth = () => { 
    const token = localStorage.getItem('token');
    if (!token) {
      return false;
    }

    try {
      // { exp: 12903819203 }
      const { exp } = decode(token);

      if (exp < new Date().getTime() / 1000) {
        return false;
      }

    } catch (e) {
      return false;
    }

    return true;
  }

  const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (
        <Component {...props} />
      ) : (
          <Redirect to={{ pathname: '/login' }} />
        )
    )} />
  )

  return (
    <div className="row">
      <Router>
        <Switch>
          <AuthRoute exact path="/users" component={Users} />
          <AuthRoute exact path="/panels" component={Panels} />
          <Route exact path="/login" component={Login} />
          <Route exact path="/logout" component={Logout} />
        </Switch>
      </Router>
    </div>
  );
}