User Profiles / Router - meteor

I'm trying to figure out how I would be able to view user profiles by traveling to /player/:username. I have the template, now I just need to call Meteor.users to find the user account by the :username that is specified in the URL. I'm using the Router package.
'/player/:username': {
to: 'user_profile',
and: function(){
var user = Meteor.users.findOne({ username: username });
}
},
Thanks in advance,
Nathan

I would set the Session variable in the route function, and then use that to return the user in a template helper. So:
'/player/:username': {
to: 'user_profile',
and: function(username){
Session.set('currentUsername', username);
}
},
And then in the template helper
Template.user_profile.helpers({
currentUser: function() {
return Meteor.users.findOne({username: Session.get('currentUsername')});
}
})
And then in your template
<template name="user_profile">
{{#with currentUser}}
User name is {{username}}
{{/with}}
</template>

You could try var user = Meteor.users.findOne({ username: username }); -- then to look up profile properties of the user, you could do user.profile.foobar.

Related

Get current user email meteor

I am having a bit of difficulty getting the email of the current user in Meteor.
publish.js
Meteor.publish('allUsers', function(){
if(Roles.userIsInRole(this.userId, 'admin')) {
return Meteor.users.find({});
}
});
Meteor.publish('myMail', function(){ {
return Meteor.user().emails[0].address;
}
});
profile.html
<template name="Profile">
<h1> My Profile </h1>
{{#if currentUser}}
<p>{{currentUser.profile.firstName}}</p> <p>{{currentUser.roles}}</p>
<p>{{currentUser.userEmail}}</p>
{{/if}}
</template>
profile.js
Template.Profile.helpers({
users: function() {
return Meteor.users.find();
},
userEmail: function() {
return Meteor.user().emails[0].address;
}
});
Firstname and ._id display fine, emailaddress unfortunately does not. Does anyone have a tip? thanks!
Your 'myMail publication is both redundant and incorrect. You should either return a cursor (or an array of cursors), or observe a cursor and send handle the publication lifecycle yourself (a fairly advanced feature, irrelevant to your question). You are using it a-la Meteor.methods, and you should not really user Meteor.user() in a publication anyway.
It's redundant because Meteor's accounts package publishes the current user's emails field automatically.
In your template, you are treating userEmail as an attribute of the current user, instead of calling it as a helper.
I would advise to use a guard and make sure that the user actually has an email address, something in the lines of:
JS:
Template.Profile.helpers({
users: function() {
return Meteor.users.find();
},
userEmail: function(user) {
if (user.emails && user.emails.length > 0) {
return user.emails[0].address;
}
return 'no email';
}
});
HTML:
<template name="Profile">
<h1> My Profile </h1>
{{#if currentUser}}
<p>{{currentUser.profile.firstName}}</p> <p>{{currentUser.roles}}</p>
<p>{{userEmail currentUser}}</p>
{{/if}}
</template>
I would also strongly advise against publishing all of the fields in the 'allUsers' publication, as it will expose sensitive data that should not leave the server under almost any circumstances (e.g, password data).

find a document with the current username in a helper

I'm trying to create a helper like this:
this.helpers({
data() {
return Customers.findOne({ user: Meteor.user().username });
}
});
but an error occurs, It seems that the user is logging in when the helper is executing, How can I execute the helper after the user is logged in ?
Don't know if is the best solution but I created a deferred promise that wait for the user to login and resolve the $state.
resolve: {
currentUser: ($q) => {
var deferred = $q.defer();
Meteor.autorun(function() {
if(!Meteor.loggingIn()) {
if(!Meteor.user()) {
deferred.reject('PERMISSION_REQUIRED');
} else {
deferred.resolve();
}
}
});
I hope that it can be useful for someone else.
Try this:
data() {
if(Meteor.user()){
return Customers.findOne({ user: Meteor.user().username });
}
}
Try builtin currentUser users helper, which check whether the user is logged in. Like that:
{{#if currentUser}}
{{data}}
{{/if}}

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 routing filter not working

i am trying to create an admin interface for my meteor project and for this i created a custom accounts register form which says
Accounts.createUser({
email: userEmail,
password: userPassword,
admin: true
})
and in my router.js code i have this
Router.route('/admin', {name: 'admin'})
var requireAdminLogin = function(){
if(!Meteor.user({admin: true})){
this.render('accessDenied')
}else{
this.next();
}
}
Router.onBeforeAction(requireAdminLogin, {only: 'admin'})
the problem is even when i change my register code to say that the new user signing up is not admin, i can still get to my admin page. Can anyone help? thank you
Meteor.user() doesn't take any arguments. You probably want:
if (Meteor.user() && Meteor.user().admin) {
// admin
} else {
// access denied
}
I also suspect that passing the admin option to Accounts.createUser doesn't do anything. On the server, you could do var userId = Accounts.createUser followed by Meteor.users.update(userId, {$set: {admin: true}});.
A package called houston:admin did exactly what I wanted to do.

How do I use the current user's username as a Router parameter in iron:router

I have a 'profile' template where I will display user related stuffs. So I wanna make a route for the template, but in the 'path' I want to dynamically insert the current user's username. Just the way we dynamically change the url with regard to post's id and everything.
Here's the router code block as of now.
Router.map(function() {
this.route('profile', {
path: '/profile', //here instead of 'profile' I wanna dynamically insert the current user's username.
});
});
By the way, I was able to load the user related data's to the said template.
I tried loading the username(/username) to the route path in a trial and error way, but in vain. :(
I guess I'm not very good with Iron Router after all. Please help.
I too was struggling with this one for a while... then I came across this SO answer. In my case, I was doing everything right except for failing to pass the username along with the template pathFor link helper.
For some reason, when using :_id in iron router routes, there's no need to reference it in the pathFor helper. This was the source of my confusion, perhaps others' as well.
Here is sample code of using the username in a path for iron router:
router.js
this.route('/:username', {
name: "dashboard",
waitOn: function() {
return Meteor.subscribe("allUserData");
},
data: function() {
return Meteor.users.findOne();
}
});
publications.js
Meteor.publish("allUserData", function() {
if (this.userId) {
return Meteor.users.find(this.userId)
} else {
this.ready()
}
})
page.html
<a href="{{pathFor 'dashboard' username=username}}">
User Dashboard
</a>
Again, at least in my particular case, I was missing the above username=username.
Have you tried this?
this.route('profile', {
path: '/:username',
data: function() { return Meteor.user().username; }
});
Use router parameters:
Router.map(function() {
this.route('profile', {
path: '/:_username', //dynamic parameter username
data: function() {
//here you will get the username parameter
var username = this.params.username;
return {
user: Meteor.users.find({ username: username }) //you can use user object in template
};
}
});
});
Don't forget the waitOn property on routes. Most of the time it's just the timing that's off, creating a publication for this is the best way to get rid of that issue..
Server side, publications.js:
Meteor.publish('me', function() {
if(!this.userId) return false;
else return Meteor.users.find({_id: this.userId});
});
In one of your Router.map() routes:
this.route('me', {
template: 'profile',
notFoundTemplate: 'profile_not_found',
path: '/profile',
waitOn: function() {
return Meteor.subscribe("me");
},
data: function() {
return Meteor.user();
}
});
Don't forget these configuration bits as well:
// Router config.. pretty self explanatory
Router.configure({
layoutTemplate: 'main',
notFoundTemplate: 'not_found',
loadingTemplate: 'loading'
});
// handle the loading screen
Router.onBeforeAction('loading');
// make sure you define routes here that rely on data to throw back
// 404/not found equivalent pages. e.g. no search results found,
// or in this case profile not found
Router.onBeforeAction('dataNotFound', {only: ['profile']});
and you can use the profile template:
<template name="profile">
Current user Id: {{_id}}
</template>
<template name="profile_not_found">
Profile not found. Are you logged in?
</template>

Resources