3
votes

I'm trying to selectively publish user data depending on the role of the user. I want email addresses to be published, and the user name. If the user is an admin, they should be able to see the whole user profile.

On the server (CS):

Meteor.publish "allUsers", ->
    if Roles.userIsInRole @userId, 'admin' then data = profile: 1
    else data = 'profile.name': 1
    data['emails.address'] = 1
    Meteor.users.find {}, fields: data

On the client (CS):

Meteor.subscribe("allUsers")

This works great most of the time. When a user logs out, and then logs in again, something is broken with the subscription and

Meteor.user().profile

returns nothing. Refreshing the page, and the profile field is filled in again. To try to fix the problem, I changed the server return statement to:

[
    Meteor.users.find {}, fields: data
    Meteor.users.find @userId
]

this did nothing. Is this a bug with Meteor or am I fundamentally misunderstanding the login/logout?

Update

I read a bit more and it seems that Meteor will randomly choose data for multiple subscriptions / publishes on the same collection. With that in mind, I changed the return query to:

Meteor.users.find _id: $ne: @userId, fields: data

The data from the other users is now not published! (Meteor.users.find().count() in console returns 1.)

1

1 Answers

0
votes

I believe your original return statement is fine. However, I would look at what happens with your Roles.userIsInRolefunction when @userId is null. Maybe there's a bug there that's causing the Publish function to crash.

I'm not a Coffeescripter, but if that's the problem, then I think adding this the top of your Publish function would resolve your problem:

if not @userId return