Meteor - template not updated after user sign in - meteor

I built an app with simple user login, using Accounts-unstyled. It all works fine, except that the template showing user data is not re-rendered with the user logs in. However if the user reloads the page, then his data is present.
My code doesn't really contain anything related to user, except for fetching the correct user's data. Do I need to manually trigger a refresh after the login?
The app is at www.barelinks.in. Test login: user=test; password=pwdpwd.
Upon first login nothing changes, but if you reload you will see the user's data.
Here is the code for the subscription:
if(Meteor.isServer) {
Meteor.publish('links', function linksPublication(userId) {
return Links.find({ user: userId });
});
}
And the helper fetching the right data (the Regex is for the search feature):
Template.body.helpers({
links: function() {
var nbSkip = linksPerPage*(Template.instance().page.get() - 1);
var queryRegex = new RegExp(Template.instance().query.get(), 'i');
return Links.find({ user: Meteor.userId(), title: queryRegex }, { sort: { createdAt: -1 }, limit: linksPerPage, skip: nbSkip });
},
});
Thanks!

I recognized that the content is updated when refreshing the page in a logged in state. Than you can switch forth and back and everything works as expected. I came usually across this behavior when the data subscription is not as it should be.
The server automatically updates the data according to a change of logged in state, you need to rely on the this.user property in the publish function.
if(Meteor.isServer) {
Meteor.publish('links', function linksPublication() {
return Links.find({ user: this.userId });
});
}

Related

meteorjs meteor-user-status mizzao package: cannot get other users

Trying to implement mizzao/meteor-user-status user status package, but only getting the status for the currently logged in user (me). Others show undefined.
Code in /server folder:
Meteor.publish('userStatus', function() {
return Meteor.users.find({
"status.online": true
});
});
Code in /client folder:
Meteor.subscribe('userStatus');
Template.member.helpers({
isOnline: function(username) {
console.log(username); //gets each username, not just logged me logged in
var currentUser = Meteor.users.findOne({
username: username
});
console.log(currentUser.status.online); //gets undefined for other users other than me
return currentUser.status.online; //returns undefined for other users
}
});
Maybe this needs to reference "userStatus" somehow instead of Meteor.users.findOne(...), but since global object was not created, e.g. like UsersOnline = new Mongdb.Collection - I don't know how to implement this.
Getting error in Chrome debugging tool: TypeError: Cannot read property 'status' of undefined, obviously, it only gets currently logged in user.
Edit: To clarify: I get other users from a custom "profiles" collection in Mongo that I created specifically to overcome the issue of not being able to read "users" collection, due to security, I guess. So I get the list of profiles and supply the user name to this function that supposed to use mizzao package to see if they are online. Since the package reads from "users" collection, it only returns current user (me).
I would be totally OK if I could modify the package for it to write to my "profiles" collection, if someone suggests how to do that.
Another update:
I ran the count on the server, and it returns only one (me, I guess).
var cursor = Meteor.users.find({
"status.online": true
}, {
fields:{
_id: 1,
status: 1,
username: 1
// Any other fields you may need
}
});
console.log(cursor.count());
If you have a publication like this:
Meteor.publish('userStatus', function() {
return Meteor.users.find({
"status.online": true
});
});
it will return users that are online only. So you get undefined for users other than you, because they are not logged-in.
Try logging in as a different user at the same time (i.e. using different browser), and see whether you can now see the status of that user.
You can always change your publication to:
Meteor.publish('userStatus', function() {
return Meteor.users.find({}, {fields: {username : 1, status : 1}});
});
and you will get statuses for all users. But if you only need to check the "online" flag (i.e. you don't need other features of the package), it is better to only send data about the online users and consider not published user as offline.
I guess you trying to read users before subscription is ready.
Server:
Meteor.publish('userStatus', function() {
return Meteor.users.find({
"status.online": true
}, {
fields:{
_id: 1,
status: 1,
profile: 1,
username: 1
// Any other fields you may need
}
});
});
Client (you should return cursor, which will re-run once subscription is ready):
Meteor.subscribe('userStatus');
Template.member.helpers({
isOnline: function(username) {
console.log(username); //gets each username, not just logged me logged in
var cursor = Meteor.users.find({username: username});
if(cursor.count()){
var currentUser = cursor.fetch()[0];
if(currentUser.status && currentUser.status.online){
console.log(currentUser.status.online); //gets undefined for other users other than me
return currentUser.status.online; //returns undefined for other users
}
}
return {};
}
});

resetPassword issues in meteor

I sent enrollment email to the user and when he enters password and other details I'm trying to reset the password but it is throwing error
uncaught error extpected to find a document to change
As you can see in the mage
I've subscribed to the user record
my code
this.route('enroll', {
path: '/enroll-account/:token',
template: 'enroll_page',
onBeforeAction: function() {
Meteor.logout();
Session.set('_resetPasswordToken', this.params.token);
s = this.subscribe('enrolledUser', this.params.token).wait();
}
}),
After I'm displaying form and on the submit event
onSubmit: function(creds) {
var options = {
_id: Meteor.users.findOne()._id,
name: creds.name
}
var token=Session.get('_resetPasswordToken');
Meteor.call('updateUser', options, function(error, result) {
if(!error) {
Accounts.resetPassword(token, creds.password, function(error) {
if (error) {
toastr.error("Sorry we could not update your password. Please try again.");
return false;
}
else{
toastr.error("Logged In");
Router.go('/');
}
});
} else {
toastr.error("Sorry we could not update your password. Please try again.");
return false;
}
});
this.resetForm();
this.done();
return false;
}
Everything is working fine but resetpassword callback is not triggering and the above error is displaying in console.
my token is get deleted from the user record and I'm able to login using login form but
From the docs
Reset the password for a user using a token received in email. Logs the user in afterwards.
I'm not able to automatically login after resetting the password,above error is throwing
What am I missing here?
this.subscribe('enrolledUser', this.params.token).wait();
here you're subscribing using resetPassword token
when you call Accounts.resetPassword method the method will reset the password and delete the token from user record.
So your subscription is lost and there are no records available in client side to modify
(That is waht the error Expected to find a document to change)
Instead on first subscription save the user Id and subscribe to the user record using Id
so the subscription will not be lost
path: '/enroll-account/:token',
template: 'enroll_page',
onBeforeAction: function() {
Meteor.logout();
Session.set('_resetPasswordToken', this.params.token);
s = this.subscribe('enrolledUser', this.params.token).wait();
},
onAfterAction:function(){
if(this.ready()){
var userid=Meteor.users.findOne()._id;
Meteor.subscribe("userRecord",userid);
}
}
Alternatively, you could do something like as follows in your publication. This worked for me (but mine was a slightly more involved query than this).
Meteor.publish('enrolledUser', function (token) {
check(token, String);
return Meteor.users.find({
$or: [{
_id: this.userId
}, {
'services.password.reset.token': token
}]
});
});
From the docs, it says
Reset the password for a user using a token received in email. Logs the user in afterwards.
So basically, you have to subscribe to the logged in user after the fact as well. A little silly, but whatever.

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 to redirect New User to different page one time only?

ok so when my app starts after the first time you sign up I want to redirect the user to a different page.
In my server code I have this
Accounts.onCreateUser(function(options, user) {
Hooks.onCreateUser = function () {
Meteor.Router.to('/newUser');
}
});
but I want users to be redirected to another page if they have already been on more then once so I have this in my client code, it always defaults to the client, what am I doing wrong?
Hooks.onLoggedIn = function () {
Meteor.Router.to('/new');
}
If you want to redirect a signed user, simply set up a flag within user object denoting whether he was redirected:
Hooks.onLoggedIn = function (){
if(!Meteor.user()) return;
if(!Meteor.user().returning) {
Meteor.users.update(Meteor.userId(), {$set: {returning: true}});
Meteor.Router.to('/new');
}
}
Make sure to publish & subscribe to the returning field of user collection!
If you want similar functionality for all visitors, use cookies.
Hooks.onLoggedIn = function (){
if(!Cookie.get('returning')) {
Cookie.set('returning', true);
Meteor.Router.to('/new');
}
}
Here's the handy package for that: https://atmosphere.meteor.com/package/cookies
Create collection 'ExistingUsers' to keep track.
if (Meteor.isClient) {
Deps.autorun(function () {
if(Meteor.userId())
//will run when a user logs in - now check if userId is in 'ExistingUsers'
//If not display message and put userId in 'ExistingUsers'
});
Alternatively add field 'SeenMessage' to User collection

Cannot access other users' email addresses in Meteor app

Before I begin, I have followed the steps here: Meteor Querying other users by email
And I have read the Meteor documentation about publishing users and how to add more fields than the id, username, and profile. My situation exists in spite of all of these things.
I'm trying to access other user's email addresses, beyond just the currently logged in user. I have 2 templates that need this access. The first template works and is able to access it. The second template is unable to.
Here is the setup code I have for publishing the emails field, and subscribing (I've also tried not specifying 'address' [e.g. fields: {emails: 1}] but that has the same result)
if (Meteor.isServer) {
Meteor.publish("allUsers", function () {
return Meteor.users.find({});
});
Meteor.publish("allUserData", function () {
return Meteor.users.find({}, {fields: {"emails.address": 1}});
});
};
if (Meteor.isClient) {
Meteor.subscribe("allUsers");
Meteor.subscribe("allUserData");
};
Here is the code from the template that works:
Template.createPartner.events({
'click .setup-partner' : function(event, template) {
var partner = Meteor.users.findOne({"emails.address": 'example#mail.com' }); <-- works
}
});
Here is the code from the template that doesn't work:
Template.infoSelect.partnerEmail = function() {
var partnerId = Meteor.user().profile.partnerId; <-- works
var partner = Meteor.users.findOne({_id: partnerId}); <-- works but only _id and profile are returned
return partner.emails[0].address; <-- throws exception because the 'emails' field doesn't exist
};
I've also tried this, but no difference:
var partner = Meteor.users.find({_id: partnerId}, {fields: {"emails.address": 1}});
Why can I not see the user's email address in the second template, but I can in the first?
I think its because you're subscribing to two sets of the same collection. Meteor uses the first subscription and ignores the second. I'm not sure why it works on one occasion though.
If you remove the first subscription and go with the second It should work, basically remove the line:
Meteor.subscribe("allUsers");
One more tip. You could alter your email function to:
Template.infoSelect.partner = function() {
var partnerId = Meteor.user().profile.partnerId; <-- works
var partner = Meteor.users.findOne({_id: partnerId}); <-- works but only _id and profile are returned
return partner;
};
And your handlebar would be : (it just opens up more options for your partner variable so you could reference him/her by name too)
<template name="infoSelect">
{{partner.email.0.address}}
{{partner.profile.name}} <!--If you have configured profiles -->
</template>

Resources