基于react-router中的权限进行路由

时间:2018-03-06 09:42:12

标签: reactjs react-router-v4 react-router-dom

我想根据特定用户拥有的权限路由路径。我正在使用react-router-dom

以下是我的示例代码:

 <Switch>

    <CustomRoute path="/add-user" name="Add user" component={AddUser} authorize='Can_Add_User' />
    <CustomRoute path="/del-user" name="Delete user" component={DelUser} authorize='Can_Del_User' />
    <CustomRoute path="/edit-user" name="Edit user" component={EditUser} authorize='Can_Edit_User' />
    <CustomRoute path="/list-user" name="List user" component={ListUser} authorize='Can_List_User' />

 </Switch>

我创建了CustomRoute课程,在那里我向其传递了额外的authorize自定义道具。在CustomRoute内,我将authorize道具与可用权限列表进行比较,如果成功返回Route,则返回null

以下是CustomRoute.js

import React, { Component } from 'react';
import { Route } from 'react-router-dom';


// get permissions sets of current user from server
const permissions_set = //load from server.

class CustomRoute extends Component {

    constructor(props) {
        super(props);
    }

    hasPermission() {
        const authorize = this.props.authorize;

        if (permissions_set.includes(authorize)) {
            console.log('Permission exists');
            return true
        }

        return false;
    }

    render() {
        const { name, component, path, exact } = this.props;

        if (this.hasPermission()) 
            return  <Route path={path} name={name} component={component} />
        else return null;

    }
}

export default CustomRoute;

现在,当权限成功匹配时,它会正确显示返回Route。但是当它没有许可并返回时 null,URL仍然有效,但不显示任何数据。不应该URL也不起作用。如何使URL也不存在?

注意:一种方法是重定向到else case中的另一个/未找到的网址,但这是不是很好的方法,还是有其他方法?

2 个答案:

答案 0 :(得分:0)

它绝对应该重定向到别的东西

<Redirect to={{
  pathname: pathname,
  state: { from: props.location }
}/> 

在react-router上查看此example

答案 1 :(得分:0)

React Router v4保护的路由和身份验证。 Click here to ref

import React from "react";
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  withRouter
} from "react-router-dom";

////////////////////////////////////////////////////////////
// 1. Click the public page
// 2. Click the protected page
// 3. Log in
// 4. Click the back button, note the URL each time

const AuthExample = () => (
  <Router>
    <div>
      <AuthButton />
      <ul>
        <li>
          <Link to="/public">Public Page</Link>
        </li>
        <li>
          <Link to="/protected">Protected Page</Link>
        </li>
      </ul>
      <Route path="/public" component={Public} />
      <Route path="/login" component={Login} />
      <PrivateRoute path="/protected" component={Protected} />
    </div>
  </Router>
);

const fakeAuth = {
  isAuthenticated: false,
  authenticate(cb) {
    this.isAuthenticated = true;
    setTimeout(cb, 100); // fake async
  },
  signout(cb) {
    this.isAuthenticated = false;
    setTimeout(cb, 100);
  }
};

const AuthButton = withRouter(
  ({ history }) =>
    fakeAuth.isAuthenticated ? (
      <p>
        Welcome!{" "}
        <button
          onClick={() => {
            fakeAuth.signout(() => history.push("/"));
          }}
        >
          Sign out
        </button>
      </p>
    ) : (
      <p>You are not logged in.</p>
    )
);

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      fakeAuth.isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

const Public = () => <h3>Public</h3>;
const Protected = () => <h3>Protected</h3>;

class Login extends React.Component {
  state = {
    redirectToReferrer: false
  };

  login = () => {
    fakeAuth.authenticate(() => {
      this.setState({ redirectToReferrer: true });
    });
  };

  render() {
    const { from } = this.props.location.state || { from: { pathname: "/" } };
    const { redirectToReferrer } = this.state;

    if (redirectToReferrer) {
      return <Redirect to={from} />;
    }

    return (
      <div>
        <p>You must log in to view the page at {from.pathname}</p>
        <button onClick={this.login}>Log in</button>
      </div>
    );
  }
}

export default AuthExample;