【问题标题】:Authorization component URIs react and redux based on route change授权组件 URIs react 和 redux 基于路由变化
【发布时间】:2019-03-21 18:23:54
【问题描述】:

我是 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;

【问题讨论】:

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


    【解决方案1】:

    这应该没问题。 你能提供 checkComponent 代码吗?可能是动作本身的问题。

    【讨论】:

    • 还增加了auth reducer和combining reducer
    • 所以,isAllowed 的默认状态是 true,而不是 false,这应该将用户重定向到组件,而不是 403 组件。您调用该操作的地方是正确的,我认为为了避免显示 403 组件的问题是添加在调用 checkComponent 操作后立即运行的加载程序,然后在响应中停止它。另外,您是否确认 isAllowed 道具具有正确的价值?
    • 是的,操作后它带有正确的值,并且第一次加载时使用默认值
    猜你喜欢
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 2017-05-09
    • 2020-06-18
    相关资源
    最近更新 更多