Search code examples
meteormeteor-publicationsmeteor-accounts

dynamic publications in Meteor based on logged in user's "role"


I would like to have some publications that only return the items a user has access to based on their role. I am using the alanning:roles package to handle the roles.

For instance, I have a publication like:

Meteor.publish('header_fields', function() {
    console.log("header_fields: %j", this.userId);
    if (Roles.userIsInRole(this.userId,['ADMIN','INSPECTOR'])) {
        // Inspectors and Admins can see all header fields
        return HeaderFields.find();
    } else {
        // Clients should only be able to see header fields for forms they have access to
        var user = Meteor.users.find({_id: this.userId});
        var formIds = [];
        _.each(Forms.find({client_id: user.profile.client_id}).fetch(), function(form) {
            this.push(form._id);
        }, formIds);
        return HeaderFields.find({form_id: {$in: formIds}});
    }
});

The problem I am having is that, in all the examples I have seen, publications are defined in a .js file in the server folder, and thus run and get when the client first connects. However, the user isn't logged in when the client first connects initially. But, I don't know where to put these publications or how it should work.


Solution

  • Meteor handles this particular use-case by default in an elegant way, quoting the official docs :

    this.userId

    Access inside the publish function. The id of the logged-in user, or null if no user is logged in. This is constant. However, if the logged-in user changes, the publish function is rerun with the new value.

    http://docs.meteor.com/#publish_userId

    So basically it means that if you subscribed in the client to a publication which returns different documents based on this.userId as in your example, everything should work out of the box !