How to verify if a Meteor.user username exists? - meteor

I'm building a messenger application, and before a conversation is created I want to verify if a user exists. If it does, then it will create the conversation. If not, then it should return an error. I've been working with this code on the server side but for some reason it won't work. I've tried many different tweaks, but this is basically my structure:
Meteor.methods({
createConversation: function(secondPerson) {
function doesUserExist(secondPerson) {
var userx = Meteor.users.findOne({username: secondPerson});
if (userx === secondPerson) {
return false;
} else {
return true;
}
}
if (doesUserExist()) {
Conversations.insert({
person1: Meteor.user().username,
person2: secondPerson
});
} else {
Conversations.insert({
person1: "didn't work"
});
}
}
});

The main point you were missing is that find returns a cursor, whereas findOne returns a document. Here is one way to implement the method:
Meteor.methods({
createConversation: function(username) {
check(username, String);
if (!this.userId) {
throw new Meteor.Error(401, 'you must be logged in!');
}
if (Meteor.users.findOne({username: username})) {
return Conversations.insert({
person1: Meteor.user().username,
person2: username
});
} else {
throw new Meteor.Error(403, username + " does not exist!");
}
}
});
Note the following features:
validates that username is a string
requires that the user be logged in to create a conversation
reduces the user existence check to a single line
returns the id of the new conversation
uses Meteor.Error with explanations which can be seen on the client
To use it just open your browser console and try making calls like:
Meteor.call('createConversation', 'dweldon', function(err, id){console.log(err, id);});

Related

Meteor - registerHelper, can't access user value

I am using meteor to build a website similar to reddit. I used the account-ui package for user accounts, but I had trouble getting the user value. I was able to create an account and login, but when I post a comment, it shows that I am an anonymous user. Here's the code -
Template.registerHelper('getUser', function(user_id) {
var user = Meteor.users.findOne({_id: user_id});
if (user) {
return user.username;
}
else {
return "anon";
}
});
post a comment -
Template.comment_form.events({
"submit .js-save-comment-form":function(event){
if (Meteor.user()) {
// here is an example of how to get the comment out of the form:
var comment = event.target.comment.value;
console.log("The comment is: "+comment);
Comments.insert({
website: Router.current().params._id,
comment: comment,
createdOn: new Date(),
user: Meteor.user()._id
});
event.target.comment.value = "";
}
else {
alert('You need to be logged in to submit comments!');
}
return false; // stop the form submit from reloading the page
}
});
I was logged in as user test, but when I posted a comment, it shows it's posted by anon, which means the server didn't return the user value
See if this makes the usernames show up. It's not the production solution, but it should give you some idea what's going on if it works.
Meteor.publish(null, function () {
if (!this.userId) return null;
return Meteor.users.find({},{fields: {'username': 1, '_id': 1}});
});

Meteor reactive transform

I have a mobile app in development and I'm transforming one of the collections to get the user last seen time, avatar etc.
PlayerRecord.prototype = {
constructor : PlayerRecord,
getAssociatedUser: function () {
return Meteor.users.findOne( this.user_id );
},
lastSeenFormatted: function () {
var user = this.getAssociatedUser();
return (user && user.last_seen) ? user.last_seen : 'Never';
}
}
My problem is that, if the user last seen returns Never initially but then the user is seen, my string return over there is not updated...obviously.
How would you advise me to handle this situation?
Did you check whether any user had a value for last_seen? This field has to be explicitly published.
According to the Meteor docs (http://docs.meteor.com/#/full/meteor_user):
By default, the current user's username, emails and profile are
published to the client. You can publish additional fields for the
current user with:
// server
Meteor.publish("userData", function () {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {'last_seen': 1}});
} else {
this.ready();
}
});
// client
Meteor.subscribe("userData");

Meteor never see's me as looged in

I want to detect if a logged in user has no records in the collection and then start them with some default values. So I use this at the beginning of my isClient part;
if (Meteor.isClient) {
if(Meteor.user()){
Meteor.subscribe('collection');
var currentUserId = Meteor.userId();
if (collection.find({"userID": currentUserId}).count() == 0)
{
Meteor.call('initUser', currentUserId);
}
} else {
console.log("You are not logged in");
}
}
Problem is that it never see's me as logged in. Do I need to be calling this from a template or something? In the tutorial that I did they just had it all by itself.
Your code looks good to me but it does not live in a reactive computation, meaning that it's going to run only once at the beginning of your code and never again, just like regular sequential programming.
You need to surround your code with a Tracker.autorun like this :
if (Meteor.isClient) {
Tracker.autorun(function(){
// Meteor.userId() is a reactive data source that will trigger invalidation
// of the reactive computation whenever it is modified (on login/logout)
var currentUserId = Meteor.userId();
if(currentUserId){
Meteor.subscribe('collection',function(){
if (collection.find({
userID: currentUserId
}).count() === 0){
Meteor.call('initUser', currentUserId);
}
});
} else {
console.log("You are not logged in");
}
}
}
I've refactored it to only use Meteor.userId() because you don't use the currentUser properties in this piece of code.

Add extra user field

In my Meteor app I use the default accounts package, which gives me the default login and registration functionality. Now I want to add an extra field to user, say nickname, and for the logged in user the possibility to edit this information.
For editing the profile I suppose I should be doing something like this:
Template.profileEdit.events({
'submit form': function(e) {
e.preventDefault();
if(!Meteor.user())
throw new Meteor.Error(401, "You need to login first");
var currentUserId = this._id;
var user = {
"profile.nickname": $(e.target).find('[name=nickname]').val()
};
Meteor.users.update(currentUserId, {
$set: user
}, function(error){
if(error){
alert(error.reason);
} else {
Router.go('myProfile', {_id: currentUserId});
}
});
}
});
But I doesn't store the info if I look in Mongo. Also when showing the profile, {{profile.nickname}} returns empty. What is wrong here?
Edit: added collections\users.js to show permissions:
Meteor.users.allow({
update: function (userId, doc) {
if (userId && doc._id === userId) {
return true;
}
}
});
Meteor.users.deny({
update: function(userId, user, fieldNames) {
return (_.without(fieldNames, 'profile.nickname').length > 0);
}
});
Yeah, I believe that should do the job, although I haven't actually run the code. The idea is certainly right.
The main things to be aware of are:
The necessity to allow the user doc to be edited from the client with an appropriate Meteor.users.allow() block on the server, assuming you're going to remove the "insecure" package (which you need to before doing anything in production).
The fact that "by default the server publishes username, emails, and profile", so you'll need to write a Meteor.publish function on the server and subscribe to it if you want to expose any other fields within the user document to the client once you've removed the "autopublish" package (which again, you really should).

How do you change the email associated with a user in firebase simple login?

As the title suggests I would like to provide functionality to allow a user to update the email they use to login to my app using Firebase Simple Login. Cannot figure out an elegant way to do this. App uses AngularFire if that is relevant.
Does one exist or do I need to create a new account and delete the old one using the $removeUser() and $createUser() methods?
Update for Firebase 2.1.x
The Firebase SDK now provides a changeEmail method.
var ref = new Firebase('https://<instance>.firebaseio.com');
ref.changeEmail({
oldEmail: 'kato#domain.com',
newEmail: 'kato2#kato.com' ,
password: '******'
}, function(err) {
console.log(err ? 'failed to change email: ' + err : 'changed email successfully!');
});
Historical answer for Firebase 1.x
In Simple Login, this is equivalent to changing the user's ID. So there is no way to do this on the fly. Simply create the new account, remove the old one as you have already suggested.
If you're user profiles in Firebase, you'll want to move those as well. Here's brute force, safe method to migrate an account, including user profiles. You could, naturally, improve upon this with some objectification and futures:
var ref = new Firebase('URL/user_profiles');
var auth = new FirebaseSimpleLogin(ref);
// assume user has logged in, or we obtained their old UID by
// looking up email address in our profiles
var oldUid = 'simplelogin:123';
moveUser( auth, ref, oldUid, '123#abc.com', '456#def.com', 'xxx' );
function moveUser( auth, usersRef, oldUid, oldId, newId, pass ) {
// execute activities in order; first we copy old paths to new
createLogin(function(user) {
copyProfile(user.uid, function() {
// and once they safely exist, then we can delete the old ones
removeOldProfile();
removeOldLogin();
});
});
function copyProfile(newId, next) {
ref.child(oldUid).once('value', function(snap) {
if( snap.val() !== null ) {
ref.child(newId, snap.val(), function(err) {
logError(err);
if( !err ) { next(); }
});
}
});
}
function removeOldProfile() {
ref.child(oldId).remove(logError);
}
function createLogin(next) {
auth.createUser(newId, pass, function(err, user) {
logError(err);
if( !err ) { next(user); }
});
}
function removeOldLogin() {
auth.removeUser(oldId, pass, logError);
}
}
function logError(err) {
if( err ) { console.error(err); }
}

Resources