Reactive subscription on user collection - meteor

I am trying to subscribe to profdle information of a different user than the logged in user, but I am facing issues as mentioned below
I am using angular-material and my code looks like below:
//publish user info upon following user
Meteor.publish("getUserInfo", function (userId) {
return (Meteor.users.find({_id: userId}, {fields: {profile: 1}}));
});
//subscribe
$scope.$meteorSubscribe("getUserInfo", askLikeController.$root.askLike[0].userId).then(function (subscriptionHandle) {
//Second element in the userProfile array will have the profile of required user
askLikeController.$root.usersProfile = $meteor.collection(Meteor.users, false);
});
Issues:
1. In the variable askLikeController.$root.usersProfile, I am getting both the loggedIn user and the desired userinfo having userId, I was expecting userinfo of only desired userId, why is this?
2. The subscription "getUserInfo" is not reactive, and even the subscription is lost after processing few blocks of code and then in the askLikeController.$root.usersProfile I am left with only user profile of logged in user, my guess is that my subscription is being replaced by inbuilt Meteor subscription for user.
How do I solve the issues?
Regards,
Chidan

First, make sure you have removed autopublish:
> meteor remove autopublish
To get reactivity in angular-meteor you need $meteor.autorun and $scope.getReactively. Here's an example:
// we need the requested id in a scope variable
// anytime the scope var changes, $scope.getReactively will
// ... react!
$scope.reqId = askLikeController.$root.askLike[0].userId;
$meteor.autorun($scope, function() {
$scope.$meteorSubscribe('getUserInfo', $scope.getReactively('reqId')));
}).then(function(){
askLikeController.$root.usersProfile = $meteor.collection(Meteor.users, false);
})
Getting only the user you selected: NOTICE- the logged in users is always published. So you need to specify which user you want to look at on the client side, just like you did on the publish method. So, in the subscribe method:
askLikeController.$root.usersProfile = $meteor.collection(function() {
return Meteor.Users.find({_id: $scope.getReactively('reqId')})
}, false);
At this point you might be better off changing it to an object rather than a collection:
askLikeController.$root.usersProfile = $scope.$meteorObject(Meteor.Users, {_id: $scope.getReactively('reqId')});

Related

Meteor: how to access another user's details?

Meteor.users.findOne() gives me back my user document.
Meteor.users.findOne({_id: 'my ID'}) gives me back my user document.
Meteor.users.findOne({_id: 'another users's ID'}) gives me back UNDEFINED.
This is obviously restricted by security. But how can I access another users's account details e.g. _id, name, profile, etc?
You'll need to add a publisher for the user. Here's an example:
// The user fields we are willing to publish.
const USER_FIELDS = {
username: 1,
emails: 1,
};
Meteor.publish('singleUser', function (userId) {
// Make sure userId is a string.
check(userId, String);
// Publish a single user - make sure only allowed fields are sent.
return Meteor.users.find(userId, { fields: USER_FIELDS });
});
Then on the client you can subscribe like this:
Metor.subscribe('singleUser', userId);
or use a template subscription like this:
this.subscribe('singleUser', userId);
Security notes:
Always check the arguments to your publishers, or clients can do bad things like pass {} for userId. If you get an error, make sure you meteor add check.
Always use a fields option with the users collection. Otherwise you'll publish all of their secrets. See the "Published Secrets" section of common mistakes.
Run it on the server like so:
Server:
Meteor.publish("otherUsers", function (userID) {
return Meteor.users.findOne({_id: userID});
});
Client:
Meteor.subscribe("otherUsers", <userIdYouWantToGetDetailsFor>);
Then you can just do a Meteor.users.findOne on the client keep in mind you can only do it for your user and the userID that you passed in the meteor subscribe

How to bypass unique ID and reference child nodes

My firbase database looks like this:
app
users
-gn4t9u4ut304u9g4
email
uid
How do I reference email and uid? When I try this:
$rootScope.dashtype.child('users').orderByChild('uid').equalTo($rootScope.auth.uid).on('value', function(snapshot){
$rootScope.user = snapshot.val();
console.log($rootScope.user);
})
I get the correct object, but with the unique id as root:
Object {-JvaZVrWGvJis0AYocBa: Object}
And because this is a dynamic property, I don't know how to reference the child objects. I just want to be able to access the user fields like this: $rootScope.user.email etc.
Since you're requesting a value, you get a list of users as a result. It may only be one user, but it's still a list of one.
You will have to loop over the snapshot, to get to the child node:
$rootScope.dashtype.child('users').orderByChild('uid').equalTo($rootScope.auth.uid).on('value', function(snapshot){
snapshot.forEach(function(userSnapshot) {
$rootScope.user = userSnapshot.val();
console.log($rootScope.user);
});
});
Since there's only a single user in the list, the loop for execute just once.
You are mixing regular Firebase JavaScript with AngularFire here. This means that you will need to inform AngularJS that you updated the scope, so that it will rerender the view:
$rootScope.dashtype.child('users').orderByChild('uid').equalTo($rootScope.auth.uid).on('value', function(snapshot){
snapshot.forEach(function(userSnapshot) {
$timeout(function() {
$rootScope.user = userSnapshot.val();
console.log($rootScope.user);
});
});
});

Meteor Iron Router resubscribe on Rights change with meteor-roles

I am writing a meteor application with a user-role-system (alanning:roles) My Roles are group based. When a user knows my group url, it is allowed to access the group an get the role "defaultUser" in this group.
localUser is allowed to subscribe to all the local stuff of a group.
based on the group's ID, I also publish some contents.
The Problem is: the Subscription does not resubscribe.
Workflow:
user accesses app,
calls meteor-method to get the default role
gets the default role
subscribes to a publication
the publication (complete-group) publishes the contents if the user has the right role
My Publication looks like:
Meteor.publish "thisGroupPublic", (id) ->
return db.groups.find({_id: id}, {fields: {onlypublicones...}}
Meteor.publishComposite "thisGroupReactive", (id) ->
return {
find: () ->
if !Roles.userIsInRole(#userId, "defaultUser", id)
#ready()
console.log("[thisGroupReactive] => No Rights")
return;
return db.groups.find({_id: id});
children: [
{
find: (group) ->
return db.contents.find({groups: {$in: [group._id]}}, {fields: {apikey: 0}})
}
]
}
The user subscribes the subscription "thisGroupPublic" when the user is on the login page and gets the role "defaultUser" on its first visit to the group as a logged in user. But how do I need to configure iron:router to
resubscribe this subscription that the contents are shown and not only the public stuff?
Say that the user is on a route /something
You have some data that changes and you create a session variable:
Session.set("someDataThatChanges", myChangedData)
Your publish function takes some sort of input, which it uses to return different data from the collection:
Meteor.publish("myCollection", function(input){
return myCollection.find(
// do something here based on 'input'
);
});
Iron Router has a .subscribe method that is the same as Meteor.subscribe and also a subscriptions key that takes a function. You can wrap a Tracker.autorun around your .subscribe and put in your session variable to automatically re-subscribe to something based on the changing value of that session variable.
Router.route("/something", {
name: "templateName",
// a place to put your subscriptions
subscriptions: function() {
console.log("this in router ", this);
Tracker.autorun(function(){
this.subscribe('myCollection', Session.get("someDataThatChanges");
});
},
});

Meteor: How to assign different roles to users during sign up process

I am using the meteor package ian:accounts-ui-bootstrap-3 for accounts and alanning:roles for assigning roles.
On the sign up form I have two options one for Doctor and one for Advisor. I want to assign the selected option as a role to that user. Can someone let me know how to do this?
I have just started learning meteor and don't know much about its flow. I can assign roles to a user if I create the user manually like this:
var adminUser = Meteor.users.findOne({roles:{$in:["admin"]}});
if(!adminUser){
adminUser = Accounts.createUser({
email: "mohsin.rafi#mail.com",
password: "admin",
profile: { name: "admin" }
});
Roles.addUsersToRoles(adminUser, [ROLES.Admin]);
}
But I want to assign a roll automatically as a user signs up and select one of the options and that option should be assigned as his role.
You shouldn't need a hack for this. Instead of using Accounts.onCreateUser you can do it with the following hook on the Meteor.users collection. Something along the lines of the following should work:
Meteor.users.after.insert(function (userId, doc) {
if (doc.profile.type === "doctor") {
Roles.addUsersToRoles(doc._id, [ROLES.Doctor])
} else if (doc.profile.type === "advisor") {
Roles.addUsersToRoles(doc._id, [ROLES.Advisor])
}
});
To get around having to check on login every time it's possible to directly set the roles on the user object instead of using the Roles API.
A hack? Yep, you probably need to make sure the roles have already been added to roles... not sure if there's anything else yet.
if(Meteor.isServer){
Accounts.onCreateUser(function(options, user){
if(options.roles){
_.set(user, 'roles.__global_roles__', ['coach', options.roles]);
}
return user;
});
}
Note: _.set is a lodash method not in underscorejs.
There's no pretty solution because:
There's no server side meteor callback post complete account creation.
In onCreateUser the user hasn't been added to the collection.
Accounts.createUser's callback is currently only for use on the client. A method could then be used from that callback but it would be insecure to rely on it.
The roles package seems to grab the user from the collection and in onCreateUser it's not there yet.
you can use the Accounts.onCreateUser hook to manage that.
Please keep in mind the code below is fairly insecure and you would probably want to do more checking beforehand, otherwise anyone can assign themselves admin. (from docs):
options may come from an untrusted client so make sure to validate any values you read from it.
Accounts.onCreateUser(function (options, user) {
user.profile = options.profile || {};
if (_.has(options, 'role')) {
Roles.addUserToRoles(user._id, options.role);
}
return user;
});
Thanks for your response. I tried but it doesn't work for me.
I used Accounts.onLogin hook to to manage this. Below code works for me:
Accounts.onLogin(function (info) {
var user = info.user;
if(user.profile.type === "doctor"){
Roles.addUsersToRoles(user, [ROLES.Doctor])
}
else
if(user.profile.type === "advisor"){
Roles.addUsersToRoles(user, [ROLES.Advisor])
}
return user;
});

Prevent items in scope from writing to a different user's records

I was having success with using AngularFire in a scenario where there is one user on my application.
Now that I have authentication up and running, I'm noticing that assigning items to $scope.items is catastrophic when switching users, mainly due to the $scope failing to update correctly.
Reading directly from the docs...
var ref = new Firebase('https://<my-firebase>.firebaseio.com/items');
angularFire(ref, $scope, 'items');
I need these to be only the items of the currently authorized user. So currently, I do this (if there's a better way, don't hesitate to tell me!)
var ref = new Firebase('https://<my-firebase>.firebaseio.com/items/userId');
angularFire(ref, $scope, 'items');
I generate userId using auth.provider and auth.id, btw. Now that my items are namespaced in (let's say) user1
var ref = new Firebase('https://<my-firebase>.firebaseio.com/items/[user1id]');
angularFire(ref, $scope, 'items');
I add items to $scope.items
$scope.create = function(item) {
$scope.items.push(item)
/* Pretend the user adds these from the interface.
[
{ name: 'eenie' },
{ name: 'meenie' },
{ name: 'miney' },
{ name: 'moe' }
]
*/
}
The problem
Now if I just log out and login as someone else, magically that user has eenie meenie miney and moe because $scope.items held the array between logout and login.
I tried to set $scope.items = [] on logout event, but that actually empties all the records. I'm pulling my hair out. This is 0.001% of what I need to do in my project and it's taking my whole weekend.
Update New method
$scope.create = function() {
$scope.selectedDevice = {
name: 'New Device',
userId: $scope.user.provider + $scope.user.id
};
return $scope.devices.push($scope.selectedDevice);
};
$scope.$on('angularFireAuth:login', function(evt, user) {
var promise, ref;
ref = new Firebase('https://mysite.firebaseio.com/users/' + (user.provider + user.id) + '/registry/');
promise = angularFire(ref, $scope, 'devices');
});
It now will accurately create items under the user's id. However, still, once you logout and log back in, those items do not get cleared from $scope.devices. Therefore, they just add themselves to data but under the newly logged in user.
Update
I did a lot of trial and error. I probably set $scope.devices to [] and moved around login events in every possible combination. What eventually worked was #hiattp's fiddle in the accepted answer.
This is a result of the implicit data binding remaining intact as you switch users. If the new user shows up and creates a new binding, it will consider the existing data to be local changes that it should assimilate (that's why you see the original user's items being added to the new user), but if you try to clear them first without releasing the binding then you are implicitly telling Firebase to delete that data from the original user's item list (also not what you want). So you need to release the data bindings when you detect the logout (or login) events as needed.
The callback in the angularFire promise provides an "unbind" method (see here and here):
var promise = angularFire(ref, $scope, 'items');
promise.then(function(unbind){
// Calling unbind() will disassociate $scope.items from Firebase
// and generally it's useful to add unbind to the $scope for future use.
});
You have a few idiosyncrasies in your code that are likely causing it not to work, and remember that unbind won't clear the local collection for you. But just so you have an idea of how it should work (and to prove it does work) here is a fiddle.
You need to unbind $scope.items on logout. The best way to do this will be to save the unbind function given to your promise in $scope:
var ref = new Firebase('https://<my-firebase>.firebaseio.com/items/[user1id]');
angularFire(ref, $scope, 'items').then(function(unbind) {
$scope.unbindItems = unbind;
});
$scope.$on('angularFireAuth:logout', function() {
$scope.unbindItems();
});

Resources