Serving different version of website to different users in Meteor.js

167 views Asked by At

In Meteor.js, how do one generally give different users (say depending on a field role in the users collection, which can have values like admin, users, testers) different versions of the site (both clientside and serverside)?

1

There are 1 answers

0
CodeChimp On BEST ANSWER

First, I am using Iron Router for my routing. At some point I may drop it and write my own, at least for this project, as I am not using half of the features, but for now this is what I have.

For roles I am using the alanning:roles package. Again, I could probably write my own, but it does what I need it too for now, so I am happy with it.

Next I have a custom package I wrote. In it I set up a template for signin and signout, with routes etc. I also provide a utility class that provides a function called authenticationRequired. This function will check if the current user is logged in, and if roles are passed in that they have those roles. The code looks like this:

AccountUtils.authenticationRequired = function(router, roles) {
    if (!router) {
        throw new Meteor.Error(500, 'Router is a required parameter');
    }

    if (!Meteor.loggingIn()) {
        var currUser = Meteor.user();
        if (currUser) {
            if (roles) {
                if (!Roles.userIsInRole(currUser, roles)) {
                    console.log('User was not in the required roles: %j, %j', currUser.roles, roles);
                    //throw new Meteor.Error(403, 'Access Denied');
                    Router.go('notAuthorized');
                }
            }
        } else {
            console.log('User not found');
            Router.go(AccountUtils.settings.signinRoute);
        }
    }
}

Now, in my Router router I do something like:

this.route('admin', {
    path: '/admin',
    onBeforeAction: function() { AccountUtils.authenticationRequired(this, ['ADMIN']); }
});

There are a few moving parts around all of this, but that's the jest of it. In the onBeforeAction of the route, check if the user has the required role. If not, send them to the notAuthorize page. If they are, let them through. I am still missing a few pieces that I haven't worked out yet in this code, but it works for the most part.

Hope that gives you a jumping-off point.