Meteor assign _id when creating user - meteor

I want to assign the _id of meteor user when I create them. Meteor.createUser() doesn't seem to allow this.
Is there another way to go about this?

Accounts.onCreateUser exists on the server to allow customisation of the user doc before it is inserted. The code below modifies the doc, the new user appears in the db, and the user on client gets logged in with customised _id.
//in server js code
Accounts.onCreateUser( function( options, user){
user._id = 'myId' + Math.floor( Math.random() * 1000 ) + 1;
if (options.profile)
user.profile = options.profile; //careful not to drop the profile if it exists
return user;
});
Function documentation and a very similar example are here - http://docs.meteor.com/#accounts_oncreateuser

Related

Reactive subscription on user collection

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')});

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;
});

Accounts.onCreateUser adding extra attributes while creating new users, good practices?

I'm creating new user with Accounts.createUser() and it works normally if you are not doing anything fancy. But I want to add some other fields to new user that are not listed on documentation. Here is my code:
var options = {
username: "funnyUserNameHere",
email: "username#liamg.com",
password: "drowssap",
profile: {
name: "Real Name"
},
secretAttribute: "secretString"
};
var userId = Accounts.createUser(options);
In this example I have added secretAttribute to my options object. Because this is not documented it's just fair it's not adding my attribute under user object.
So I googled and figured out that something like this might work:
Accounts.onCreateUser(function(options, user) {
if (options.secretAttribute)
user.secretAttribute = options.secretAttribute;
return user;
});
And yes! This works, but there is always BUTT.. *BUT.. After this one it's not saving profile anymore under the user object. However this makes it work:
Accounts.onCreateUser(function(options, user) {
if (options.secretAttribute)
user.secretAttribute = options.secretAttribute;
if (options.profile)
user.profile = options.profile;
return user;
});
So what I want from you guys?
I want to know why onCreateUser loses profile (before the fix above) in my case?
Is my approach good practice?
Is there better solution adding extra attributes for user object while creating them?
ps: I thinks it's obvious why I don't want to save all extra fields under profile ;)
Well it wasn't so hard.. Here it stands in documentation: "The default create user function simply copies options.profile into the new user document. Calling onCreateUser overrides the default hook." - Accounts.onCreateUser
Try this:
Accounts.onCreateUser((options, user) => (Object.assign({}, user, options)));
The best thing I found to this issue is:
Accounts.onCreateUser(function(options, user) {
// Use provided profile in options, or create an empty object
user.profile = options.profile || {};
// Assigns first and last names to the newly created user object
user.profile.firstName = options.firstName;
user.profile.lastName = options.lastName;
// Returns the user object
return user;`enter code here`
});
https://medium.com/all-about-meteorjs/extending-meteor-users-300a6cb8e17f

Publication of items where User is in group (Alanning Roles and Publications)

I am using Alanning Roles to maintain a set of groups/roles for the users of my application. When a user creates an "Application", I generate a new role for them as the app_name + UUID, then add that as a group with the roles of Admin to the user that created it. I can then use the combination of the generated group name plus either the Admin or Viewer roles to determine which Applications the user has rights to see and/or edit.
The issue that I am having is that I can't figure out a good way to get the publication to only publish the things the user should see. I know that, by default at least, publications are not "reactive" in the way the client is, and they they are only reactive for the cursors they return. But, in my code I create the group/role first, add it to the user, then save the "Application", which I thought would rerun my publication, but it did not:
Meteor.publish('myApplications', function(groups) {
if (this.userId) {
console.log('Running myApplications publication...');
console.log('Found roles for user ' + this.userId + ': ', Roles.getGroupsForUser(this.userId));
return Applications.find({group: {$in: Roles.getGroupsForUser(this.userId)}});
} else {
//console.log("Skipping null user");
return null;
}
});
But, contrary to what I thought would happen (the whole publication method would re-run), I am guessing what really happens is that only the Cursor is updates. So for my next attempt, I added the mrt:reactive-publications package and simply got a cursor to the Meteor.users collection for the user, thinking that would "trigger" the publication to re-run when the user gets updated with the new group/role, but that didn't work.
I have this finally working by simply passing in the groups for the user:
Meteor.publish('myApplications', function(groups) {
if (this.userId) {
if (!groups || groups.length === 0) {
groups = Roles.getGroupsForUser(this.userId);
}
console.log('Running myApplications publication...');
console.log('Found roles for user ' + this.userId + ': ', Roles.getGroupsForUser(this.userId));
return Applications.find({group: {$in: groups}});
} else {
//console.log("Skipping null user");
return null;
}
});
And then I just call the publication like Meteor.subscribe('myApplications', Roles.getGroupsForUser(Meteor.userId())) in my route's waitOn, but this would mean that any client could call the same publication and pass in any groups they like, and potentially see documents they were not intended to see. That seems like a pretty large security flaw.
Is there a better way to implement this such that the client would not be able to coax their way to seeing stuff not theirs? I think the only real way would be to gather the groups on the publication side, but then it breaks the reactivity.
After sifting through a bunch of docs and a few very helpful stack posts, this is the alternative I came up with. Works like a charm!
My objective was to publish 'guest' users' info to the group admins for approval/denial of enhanced permissions.
Meteor.publish('groupAdmin', function(groupId) {
// only publish guest users info to group admins
if(Roles.userIsInRole(this.userId, ['group-admin'], groupId)) {
// I can't explain it but it works!
var obj = {key: {$in: ['guest']}};
var query = {};
var key = ('roles.' + groupId);
query[key] = {$in: ['guest']};
return Meteor.users.find(query, {
fields: {
createdAt: 1,
profile: 1
}
});
} else {
this.stop();
return;
}
});
Reference: How to set mongo field from variable
& How do I use a variable as a field name in a Mongo query in Meteor?

Meteor: insert document upon newly created user

This is probably more simple than I'm making it sound.
I'm allowing my users to create their myprofile when the signin. This is a document that is stored in MyProfile = new Meteor.Collection('myprofile');. The principle is exactly the same as LinkedIn...you login, and you fill out a profile form and any edits you make simply updates that one document.
Within the document there will be fields such as 'summary' 'newsInterest' and others, also 'owner' which is the users Id.
1) How can I insert a document into the MyProfile collection with the 'owner' field being the userId of the newly created user on StartUp?
This is so that the data of this document, the values of these fields will be passed onto the myprofile page. Initially the values returned will be blank but as the user types, upon keyup the myprofile document will be updated.
Users are created as follows on the client. This is fine for now.
2) In addition, please provide any links if people have created users on the server. I called a method to insert the following as an object into Meteor.users.insert(object);but this does not work.
Template.join.events({
'submit #join-form': function(e,t){
e.preventDefault();
Accounts.createUser({
username: t.find('#join-username').value,
password: t.find('#join-password').value,
email: t.find('#join-email').value,
profile:{
fullname: t.find('#join-fullname').value,
summary: [],
newsInterest: [],
otherstuff: []
}
});
Router.go('myprofile');
}
});
1) In order to solve issue one you have two options.
Instead of having a separate collection for profiles like you would in a normalized MySQL database for example. Add the users profile data within the profile object already attached to objects in the user collection. You can then pass in the values you want in the options parameter of the Accounts.createUser function
Template.join.events({
"submit #join-form": function (event) {
event.preventDefault();
var firstName = $('input#firstName').val(),
lastName = $('input#lastName').val(),
username = firstName + '.' + lastName,
email = $('input#email').val(),
password = $('input#password').val(),
profile = {
name: firstName + ' ' + lastName
};
Accounts.createUser({
email: email,
username: username,
password: password,
profile: profile
}, function(error) {
if (error) {
alert(error);
} else {
Router.go('myprofile');
}
});
}
});
This is an example using jQuery to get the values but your t.find should work equally fine.
If you really do want to use a separate collection then I recommend using the following code inside the onCreateUser function (server side) instead:
Accounts.onCreateUser(function(options, user) {
user._id = Meteor.users._makeNewID();
profile = options.profile;
profile.userId = user._id;
MyProfile.insert(profile);
return user;
});
When you want to update or add additional data into the profile field for a user you can use the following:
var newProfile = {
summary: 'This summary',
newsInterest: 'This newsInterest',
otherstuff: 'Stuff'
};
Meteor.users.update(Meteor.userId, {$set: {profile: newProfile}});
Or if you went for the separate collection option the following:
var newProfile = MyProfile.findOne(Meteor.userId);
newProfile.summary = 'This summary';
newProfile.newsInterest = 'This newsInterest';
newProfile.otherstuff = 'Stuff';
MyProfile.update(Meteor.userId, newProfile);
Haven't tested this so let my know if I have any syntax / typo errors and I'll update.
Q2: you have to send email, password and profile object to server and use the same Accounts.createUser. Everything works fine.
Question 1 is easily resolved using the Accounts.onCreateUser callback on the server - it provides the user object to the callback, so you can just take the userId from this and insert a new "myProfile" with that owner.
As Will Parker points out below, the user document won't actually have an _id at this point though, so you need to create one and add it to the user object that the callback returns. You can do this with:
user._id = Meteor.users._makeNewID();

Resources