Dynamic publications in Meteor based on user input role

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

For example, I have a post 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 facing is that in all the examples I have seen, posts are defined in a .js file in the server folder and thus are triggered and retrieved when the client first connects. However, the user is not logged in when the client first connects initially. But I don't know where to place these publications and how they should work.

+3


source to share


1 answer


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

this.userId

Access to the publish function. The ID of the registered user, or zero if the user is not registered. It's permanent. However, if the user is logged in, the publish function restarts with a new value.



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

So this basically means that if you've signed up on a client for a publication that returns different documents based on this.userId

, like your example, everything should work out of the box!

+3


source







All Articles