Best practise to allow/deny access to page based on users role?


currently I am creating a meteor app with 3 user roles (candidate/company/admin). These roles are attached to user entry when users creates an account on the system
Candidate can only access candidate pages, company can only access company pages and admin can access everything.
In my current build I am allowing/denying access to pages by adding things like:

if(Meteor.user() == null) {
        Materialize.toast('Please login', 3000);
    } else {
        if (Meteor.user()['profile']['type'] != 2) {
            Materialize.toast('You cannot access this page', 3000);

(oh yeah - I am using Flow-router for routing)
The more I read about Meteor security - the more I hear “never trust the client” things.
Question - is this a safe way to allow/deny access to parts of a Meteor app? Are there better alternatives for this?

P.S. I was thinking about sending userId to the server side and writing some decision login there - but the userId would have to come from the client (via Meteor.userId()?) - meaning that it can potentially be forged.

That is completely unsafe (sorry)!

Anyone can alter their profile.type to equal 2 (in your example), which would bypass the check you have written.

On the server, the current userId is available within publications and methods, and it is this value which should be used (i.e. on the server).

Edit: For more information check the Meteor Guide, particularly relating to methods and publications.


No need to apologise, thanks for the answer!

I did know that userId is available in publication setup, but had no idea that you can access it the same way in the methods.

So - is it better to call a meteor method from onCreated that would return a boolean of whether the user can access the page? Couldn’t you just forge the response from server then?

The point is that you ensure you do not send inappropriate data to the user. You ensure your publications only publish the data the user is allowed to see. Then it doesn’t matter if the user tries to elevate their ability - the server ignores it.

I can’t emphasis this strongly enough - read the Meteor Guide - it will answer all these questions and more - including don’t use .profile :smile:!