can not get current user after page refresh in Meteor.js - meteor

i'm trying to display Logged in User name .
After login i can get user name but once i refresh page it is undefined .
My code :
<p>{{currentUser.profile.full_name}}</p>
i try other way too
blaze Side
{{currentUser}}
js
Template.main.helpers({
"currentUser": function() {
if (Meteor.user())
return Meteor.user().profile.full_name;
}
});
after login i can get name but i can not get name after refresh page.
So, what is solution for get name if i refresh page in Meteor blaze ?

Try this:
Template.Default.onCreated(function() {
this.user = Meteor.user();
});
Template.main.helpers({
currentUser: function() {
var user = Template.instance().user;
if (user) {
return user.profile.full_name;
}
});
Also make sure that profile.full_name exists;

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

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.

Custom Meteor enroll template

In my application I want to seed the database with users and send them an enrollment link to activate their account (and choose a password). I also want them to verify/change some profile data.
On the server I seed the database like this:
Meteor.startup(function () {
if(Meteor.users.find().count() === 0) {
var user_id = Accounts.createUser({ email: 'some#email.com', profile: { some: 'profile' } });
Accounts.sendEnrollmentEmail(user_id);
}
})
The enrollment link is sent as expected, but I want to create a custom template for when the url in the email is clicked. Preferably handled by iron-router. (Not using the accounts-ui package).
I tried things like redirecting the user to a custom route like this:
var doneCallback, token;
Accounts.onEnrollmentLink(function (token, done) {
doneCallback = done;
token = token;
Router.go('MemberEnroll')
});
which is not working (it changes the url but not rendering my template)
I also tried to change the enroll URL on the server like this:
Accounts.urls.enrollAccount = function (token) {
return Meteor.absoluteUrl('members/enroll/' + token);
};
But when I do this, the Accounts.onEnrollmentLink callback does not fire.
Also, changing the URL is not documented so I'm not sure its a good practice at all.
Any help is appreciated.
In my application I'm doing like this
this.route('enroll', {
path: '/enroll-account/:token',
template: 'enroll_page',
onBeforeAction: function() {
Meteor.logout();
Session.set('_resetPasswordToken', this.params.token);
this.subscribe('enrolledUser', this.params.token).wait();
},
data: function() {
if(this.ready()){
return {
enrolledUser: Meteor.users.findOne()
}
}
}
})
As enrollment url is like this
http://www.yoursite.com/enroll-account/hkhk32434kh42hjkhk43
when users click on the link they will redirect to this template and you can render your template
In my publication
Meteor.publish('enrolledUser', function(token) {
return Meteor.users.find({"services.password.reset.token": token});
});
After taking the password from the user
Accounts.resetPassword(token, creds.password,function(e,r){
if(e){
alert("Sorry we could not reset your password. Please try again.");
}else{
alert("Logged In");
Router.go('/');
}
})
enroll link
Accounts.urls.enrollAccount = function (token) {
return Meteor.absoluteUrl('enroll-account/' + token);
};
Im afraid now isnt possible, what i did is changing the html and css using "rendered" function but it has some probs with delay
Meteor.startup(function(){
Template["_enrollAccountDialog"].rendered = function(){
document.getElementById('enroll-account-password-label').innerHTML = 'Escolha sua senha';
$('.accounts-dialog').css('background-color','#f4f5f5');
$('.accounts-dialog').css('text-align','center');
$('.accounts-dialog').removeAttr('width');
document.getElementById('login-buttons-enroll-account-button').className = ' create-account-button';
document.getElementById('login-buttons-enroll-account-button').innerHTML = 'Criar conta';
}
});

Meteor.user() login issue

I am testing a restrict login function with router code below
var requireLogin = function() {
if (! Meteor.user()) {
console.log("user not logged");
this.next()
} else {
console.log("user logged");
this.next()
}
}
Router.onBeforeAction(requireLogin, {except: ['home','login','about']});
when I try to enter restricted area like userprofile it ask me to log in and print "user not logged"
and after I successfully log in and try to access that area again. it printing both code starts with "user not logged" and then "user logged"
I want to know how to avoid this to happen? since some page become glitched when this happened.
I want it to only print "user logged" if I enter a restricted area page.
Any help would be appreciated.
You need to integrate Meteor.loggingIn() somewhere in your requireLogin function. Because, what's happening is that Meteor is still loading the user system and for every route change, it re-authenticates the user based on current session, if it exists.
var requireLogin = function() {
if(!Meteor.user()){
if(Meteor.loggingIn()){
this.render(this.loadingTemplate);
}else{
this.render('accessDenied');
}
}else {
this.next();
}
}
You will notice that it uses this.loadingTemplate. To keep this, you must also configure your routes to have a loading template. e.g.:
Router.configure({
loadingTemplate: 'loading'
});
or you could just simply swap that out with this.render('loading'); where 'loading' is the template name of your 'Now loading' yield/page.

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

Resources