Search code examples
javascriptmongodbmeteorserveradmin

Meteor Check if User is Admin


I have a Meteor App in which I need to set some type of variable for the app if a user is an admin so that I can use that later to show/hide certain elements of the HTML. To figure out if the user is an admin, I have to check an object in the LocalStorage on the device and see if it matches the secret string, which would grant the user admin access. However, I don't want the client to see the secret string. For now, I have a file server/server.js which has a function in it like this:

function isAdmin(cookie) {
    if(cookie == "secret") {
        return true;
    } else {
        return false;
    }
}

However, it seems I can't access that function from my main .js file for the app which I'm using like this:

Meteor.startup(function(){
    admin = false;
    if(typeof(Storage) !== "undefined") {
        cookie = localStorage.getItem("admin");
        admin = isAdmin(cookie);
    }
});

I don't know if I'm trying to go about this wrong, all I need it to do is check the localStorage for a cookie each time the site is loaded by a client and compare it to the secret string, and then set a variable indicating whether the user is an admin which I can use in the rest of the app. I also need it to be secure so the client cannot just set the variable or anything else to be an admin.


Solution

  • The Roles package is exactly what you need,

    To add this package, execute this command:

    meteor add alanning:roles
    

    You can add roles to users like this:

    Roles.addUsersToRoles(someUserId, 'super-admin', Roles.GLOBAL_GROUP)
    

    and then you can verify if a user has a role like this:

    if (Roles.userIsInRole(someUserId, ['super-admin'], 'real-madrid.com')) {
    
      // if a user has the 'super-admin' role he will be able to access here
    
    }