Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor - Publish all Users to Client just for admin

I have the folowing problem with Meteor: I have one admin, that needs to see all registered users. But all the other users shouldn't have the ability to see the other users. Therefore I published the following code on the serverside

Meteor.publish("adminUsers", function(){

   var result; 
   if (Roles.userIsInRole(this.userId, ["admin"]))
   {
        result = Meteor.users.find();
   }
   //console.log(result);
   return result;
});

On client side I subscribe to this with

Meteor.subscribe("adminUsers");

And do

AllUsers = new Meteor.Collection("adminUsers");

Now I want to get all the Users in a Template with this code:

Template.adminUserverwaltung.AllUsers = function(){
console.log(AllUsers.find());
return AllUsers.find();
}

and show the result in the template with this code:

    <template name="adminUserverwaltung">
  {{#each AllUsers}}
    {{this.username}}
  {{/each}}
</template>

But unfortunately it is not working... Can anyone help me maybe?

like image 935
Lasse Kathke Avatar asked Dec 18 '13 13:12

Lasse Kathke


2 Answers

When you subscribe to the collection the subscription name is adminUsers but the users collection is still Meteor.users which is already defined.

So just alter it to use that instead

Template.adminUserverwaltung.AllUsers = function(){
    return Meteor.users.find();
}
like image 141
Tarang Avatar answered Nov 17 '22 22:11

Tarang


You're almost there... This answer uses the meteor-roles package as the OP posed in the question.

Meteor.publish("adminUsers", function(){
   var result = [];
   if (Roles.userIsInRole(this.userId, ["admin"])) {
        result = Meteor.users.find();
   } else {
        this.stop();
        // YOUUU SHALL NOT.... PASS!!!  ~Gandalf
   }
   return result;
});

On client side, subscribe to this with:

Meteor.subscribe("adminUsers");

Don't do this. Omit it. Meteor.users is is your collection.

// NOO!! AllUsers = new Meteor.Collection("adminUsers");

Now I want to get all the Users in a Template with this code:

Template.adminUserverwaltung.helpers = {
    AllUsers: function(){
        return Meteor.users.find();
    }
};

and show the result in the template with this code:

<template name="adminUserverwaltung">
{{#each AllUsers}}
    {{this.username}}
{{/each}}
</template>

And it should now be working. :)

like image 3
4Z4T4R Avatar answered Nov 17 '22 21:11

4Z4T4R