授权组件URI会根据路由更改做出反应并进行还原

时间:2019-03-20 18:13:47

标签: reactjs react-redux react-router authorization acl

我是 react-redux 的初学者,我想实现授权。这是我的名为 RestrictedRoute 的容器,用于检查是否允许用户使用目标URI。现在的问题是默认状态isAllowed被检查为false。渲染组件时,默认的isAllowed状态为false值,渲染器检查isAllowed是否为false,然后重定向到 403 组件。我想在每个路由更改上呈现之前触发我的操作 checkComponent(),以便在每个路由更改上的API请求之后,它不会在DB允许的URI中为假

class RestrictedRoute extends Component {
       constructor(props) {
        super(props);
        this.state = {
           componentRoute:''
        }
       }
       componentWillMount() {
        const componentRoute = this.props.pathname;
        this.props.getUser();
        this.props.checkComponent(componentRoute);

      }

      componentDidMount() {
        if(this.state.componentRoute === ''){

          // const componentRoute = this.props.pathname;

        }else{

        }
        // console.log("restrictions");

      }
      componentDidUpdate(prevProps) {
        // console.log("prevProps", prevProps);
        // console.log("next props", this.props);
        if (this.props.pathname !== prevProps.pathname && this.pathname !== "/invalid_page") {
          // alert("hello");
          const componentRoute = this.props.pathname;
          this.props.getUser();
          // console.log(componentRoute);
          this.props.checkComponent(componentRoute);

        }
      }

      render() {
        const Component = this.props.component;
        // console.trace("restricted route allowed", this.props.rest);
        return (
          <Route 
          // {...this.props.rest} 
          render={
            (props) => {
              if (this.props.authUser===null) {
                return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
              } else {
                // alert("allowed", this.props.isAllowed);

                if(this.props.isAllowed || this.props.location.pathname==="/invalid_page"){

                return <Component {...props} />;
                }else{
                  // alert("usman hafeez");
                  return <Redirect to={{ pathname: '/invalid_page', state: { from: props.location } }} />
                }
              }
            }
          } />
        )
      }
    }

    function mapDispatchToProps(dispatch) {
      return bindActionCreators({
        checkComponent: checkComponent,
        getUser: getUser
      }, dispatch);
    }

    var mapStateToProps = ({ routing ,auth}, otherProps) => {
      // console.log("restricted route", routing);
      // console.log("restricted auth", auth);
      // console.log("restricted other", otherProps);
      return {
        // routing: routing,
        pathname: routing.location.pathname,
        authUser: auth.authUser,
        isAllowed: auth.isAllowed
      };
    }

    export default connect(mapStateToProps, mapDispatchToProps)(RestrictedRoute);

这是我的 checkComponent 操作

export const checkComponent = (componentUri) => {
console.log("KSDJ")
return (dispatch) => {
// alert("hello");
RestService.checkComponent(componentUri).then((resp) => {

  if (RestService.checkAuth(resp.data)) {
    if (resp.data.status === true) {
      dispatch({
        type: COMPONENT_ALLOWED,
        payload: resp.data.ComponentAllowed
      });

    } else {
      dispatch({
        type: INVALID_RESPONSE
      });
    }
  } else {
    dispatch({
      type: INVALID_TOKEN
    });
  }
 });
 }
};

这是我的auth.js还原器文件

import {
 HIDE_MESSAGE,
 INIT_URL,
 ON_HIDE_LOADER,
 ON_SHOW_LOADER,
 SHOW_MESSAGE,
 LOGIN_USER_SUCCESS,
 LOGOUT_USER_SUCCESS,
 LOGIN_FAILED,
 INVALID_TOKEN,
 COMPONENT_ALLOWED,
 ACCESS_DENIED,
 UPDATE_PROFILE,
 GET_USER
} from "constants/ActionTypes";
import RestService from '../services/RestServices';
import { message } from "antd";
     const INIT_STATE = {
  loader: false,
  alertMessage: '',
  showMessage: false,
  initURL: '',

  isAllowed: true,

  authUser: localStorage.getItem('authUser'),

};


export default (state = INIT_STATE, action) => {
  // console.log("auth.js");
  // console.log("states");
  // console.log("auth user state");
  // console.log(state.authUser);
  // console.log("actions");
  // console.log(action.type);

  switch (action.type) {

    case LOGIN_USER_SUCCESS: {
      // console.log("logged in");
      return {
        ...state,
        loader: false,
        authUser: action.payload
      }
    }
    case GET_USER: {
      return {
        ...state,
        authUser:{
          id: action.payload.id,
          connected_dealer: action.payload.connected_dealer,
          email: action.payload.email,
          dealerId: action.payload.dealerId,
          firstName: action.payload.firstName,
          lastName: action.payload.lastName,
          name: action.payload.name,
          type: action.payload.type,
          dealer_pin: action.payload.dealer_pin
        }
      }
    }
    case LOGIN_FAILED: {
      // console.log({
      //   ...state,
      //   alertMessage: action.payload.msg,
      //   showMessage: true,
      //   loader: false
      // });

      return {
        ...state,
        alertMessage: action.payload.msg,
        showMessage: true,
        loader: false
      }
    }
    case INIT_URL: {
      return {
        ...state,
        initURL: action.payload
      }
    }
    case LOGOUT_USER_SUCCESS: {
      return {
        ...state,
        authUser: {
          id: null,
          connected_dealer: null,
          email: null,
          dealerId: null,
          firstName: null,
          lastName: null,
          name: null,
          token: null,
          type: null
        },
        initURL: '/',
        loader: false
      }
    }

    case UPDATE_PROFILE: {
      if (action.response.status) {
        message.success(action.response.msg);
        state.authUser.firstName = action.response.data.first_Name;
        state.authUser.lastName = action.response.data.Last_Name;
        localStorage.setItem('firstName', action.response.data.first_Name);
        localStorage.setItem('lastName', action.response.data.Last_Name);

        // console.log('user detail',action.response);
        // console.log('user state',state.authUser);

      }
      else {
        message.error(action.response.msg);
      }
      return {
        ...state,

        loader: false,

      }
    }
      break;

    case INVALID_TOKEN: {
      RestService.authLogOut();
      return {
        ...state,
        alertMessage: "Login expired",
        showMessage: true,
        authUser: {
          id: null,
          connected_dealer: null,
          email: null,
          dealerId: null,
          firstName: null,
          lastName: null,
          name: null,
          token: null,
          type: null
        },
        initURL: '/',
        loader: false
      }
    }
    case SHOW_MESSAGE: {
      return {
        ...state,
        alertMessage: action.payload,
        showMessage: true,
        loader: false
      }
    }
    case HIDE_MESSAGE: {
      return {
        ...state,
        alertMessage: '',
        showMessage: false,
        loader: false
      }
    }

    case ON_SHOW_LOADER: {
      return {
        ...state,
        loader: true
      }
    }
    case ON_HIDE_LOADER: {
      return {
        ...state,
        loader: false
      }
    }
    case COMPONENT_ALLOWED: {

      // console.log("dsfsdfsdf",action.payload)
      return {
        ...state,
        isAllowed: action.payload
      }
      break;
    }
    case ACCESS_DENIED: {
      return {
        ...state,
        initURL: '/invalid_page'
      }
      break;
    }
    default:
      return state;
  }
}

reducer结合index.js

import { combineReducers } from "redux";
import { routerReducer } from "react-router-redux";
import Auth from "./Auth";

const reducers = combineReducers({

  auth: Auth,
});

export default reducers;

1 个答案:

答案 0 :(得分:0)

应该没问题。 您可以提供checkComponent代码吗?也许是动作本身的问题。