How to manage authorization based on athentication in meteor react app?


#1

Hi,
How do you manage the access to route based on who you are ( pro, admin ou user ) in react meteor app, with react router??

I try to manage it with lifecycle of the parent component, it does the job but not the best, I can still entre some route even I m not authorized, if I write the url.


#2

I don’t think it’s necessary to protect against this to have a secure app - you should be securing your API, not the UI.

But yeah, I think the best way to do it is to put it in the “page component”, as shown here: https://guide.meteor.com/routing.html#route-rendering-logic


#3

@sashko, thanks for the link,
Have you tested onEnter hook ?


#4

I wouldn’t use onEnter for this, but it’s up to you.


#5

@sashko what s the cons of use it ??


#6

Well, it seems to me like tying stuff to routes is a relic of the old server-side rendered app days. In modern apps the UI often changes without a route change, so it’s better to do the logic in the UI component directly. For example, what if the user logs out without changing routes?


#7

@sashko I understand you, in the same direction, I ve found a better solution based on rendering {this.props.children} only if the user is logged and authorized by his role; else, it redirects the user to login page. Its effcient like systeme and I recommand it; however, I ve a little issu, even if I am logged and authorized, it redirecte me to login page sometimes, knowing that I wait for data before rendering.
Thanks


#8

For any one want to implemnt the same thing, I fixe it with waiting for data before render, and render {this.props.children} only if the user is authorized and logged, else, it ll be rendred based on his role or to login page if not logged.


#9

Would you be so kind to share some code?
Thanks!


#10

@tetiogit, of course, here a snipt of code


export default class PagesPro extends Component {


  getChildContext() {
     return { muiTheme: getMuiTheme(baseTheme) };
      }

ManageAuthentication(){

  if (!!Meteor.user()) {
   if (Meteor.user().profile.role !== 'pro') {
        if (Meteor.user().profile.role === 'user') {
                 Router.browserHistory.push('/');
        } else if (Meteor.user().profile.role === 'admin') {
                Router.browserHistory.push('/EspaceAdmin');
        }else{
             Router.browserHistory.push('/log');
        };
      } else if (Meteor.user().profile.role === 'pro'){

           return <div>{this.props.children}</div>;
      };
  } else {
    
     Router.browserHistory.push('/log');
  };

}





  render() {


    if (!!this.props.isAuthenticated && !this.props.handleprofileInfo) {
      return <div> 
              <p>Loading </p>
                 <CircularProgress size={2} />
            </div>
          }


    return (
    	<div>
			{this.ManageAuthentication()}
	    </div>
    );
  }
}