Route using wrong controller? - meteor

I have 2 controllers (iron-router), one for access bits (login etc.) and one for the logged in area. But for some reason one of my routes is choosing to use the wrong controller, even though I'm explicitly stating which one to use. Here is the code:
// Controllers
AccessController = RouteController.extend({
layoutTemplate: 'AccessMaster',
onBeforeAction: function () {
if (Meteor.user()) { // If user is logged in then take them to the Dashboard
this.redirect('/app/dashboard');
} else {
this.next();
}
}
});
DashboardController = RouteController.extend({
layoutTemplate: 'DashboardMaster',
onBeforeAction: function () {
if (!Meteor.user()) { // If user is not logged in then take them to the login
this.redirect('/app/login');
} else {
this.next();
}
}
});
// Routes
Router.route("/app/signup", {
name: 'Signup',
controller: 'AccessController'
});
Router.route("/app/login", {
name: 'Login',
controller: 'AccessController'
});
Router.route("/app/account", {
name: 'Account',
controller: 'DashboardController',
loadingTemplate: 'Loading',
action: function () {
this.render('Account');
}
});
Router.route("/app/dashboard", {
name: 'Dashboard',
controller: 'DashboardController',
loadingTemplate: 'Loading',
waitOn: function () {
…
},
action: function () {
this.render('Dashboard', {
data: {
…
}
});
}
});
When I visit app/account I'm redirected to app/dashboard, as directed in the AccessController. Why is the app/account route using the wrong controller logic?
Edit: Oddly, if I remove the controller declaration in the offending route (controller: 'DashboardController') then the template loads fine. So it only uses the wrong controller when I ask it to us a controller.
I must be missing something but that's awfully odd.

I think that your problem comes from the fact that you are using Meteor.user() in both controllers, which is the actual user document. And like any other collection it may not be immediately ready when the application starts.
If you add a console.log(Meteor.user()) in your controllers, you will see that it is first briefly undefined before returning the user document.
So the route is using the right controller but Meteor.user() is undefined so you are redirected to /app/login where Meteor.user() (probably ready now) returns the documents so you get redirected to /app/dashboard.
To prevent such behavior I use Meteor.userId() which is always available no matter what. And I only use Meteor.user() when I have first tested that Meteor.userId() returned something and if I need more information about the user.

Related

Meteor: Publishing all user not working without autopublish package

I would to show a list of all users, in my template.
I have:
//publications.js
Meteor.publish('users', function() {
return Meteor.users.find({}, { fields: {username: 1, profile: 1} });
});
//router.js
Router.route('/users/add/:_id?', {name: 'users.add', controller: 'UserAddController'});
UserAddController = RouteController.extend({
subscriptions: function(){
return [ Meteor.subscribe('hospitals'),
Meteor.subscribe('roles'),
Meteor.subscribe('users') ];
},
action: function() {
this.render('addUser', {
data: function(){
return { hospital_id : this.params._id }
}
});
}
});
//client
Template.listUsers.helpers({
users: function() {
return Meteor.users.find({});
}
});
But the list keep showing only the current logged-in user. I have created a list of users using Account.createUser() function What am I doing wrong?
Thanks.
You have to subscribe to a publication using this.subscribe() in subscriptions hook:
// a place to put your subscriptions
subscriptions: function() {
this.subscribe('items');
// add the subscription to the waitlist
this.subscribe('item', this.params._id).wait();
}
Or use waitOn:
// Subscriptions or other things we want to "wait" on. This also
// automatically uses the loading hook. That's the only difference between
// this option and the subscriptions option above.
waitOn: function () {
return Meteor.subscribe('post', this.params._id);
}
By default, Meteor publishes the current user. I see that you have a addUser template and a listUsers template. The problem is that while addUser is subscribed to the users publication, listUsers is not (this would depend on what else you have in your router of course). To fix this, change the call to this.render to render the listUsers template. Then, your users helper should work, and you can render the information however you like.
I tested this with my own app (the Microscope project from DiscoverMeteor) and it worked for me. Hope it works for you too. Comment here if not, and be sure to accept this answer if it worked. =)

Correct way to manage routes after sign in for different roles

I have 2 roles, admins and users. I have a home route '/' that is just a sign in page. When admin users sign in they must go to one route ('adminPortal') and when user users log in they must go to the 'userPortal' route. On signing out both roles should route back to '/'.
Before I had an admin role, I was routing on sign in like so:
Router.onBeforeAction(function() {
this.render('loading');
if (! Meteor.userId()) {
this.render('Home');
} else {
this.next();
}
});
which worked fine (actually it was breaking my waitOn: render loading template stuff which I just discovered but more on that later). I then added roles like this (from a Stack Overflow answer I can't find right now):
server/
insertUsers=function(){
var adminId=Accounts.createUser({
username:"admin",
password:"password"
});
Roles.addUsersToRoles(adminId,"admin");
var userIdd = Accounts.createUser({
username:"user",
password:"password"
});
Roles.addUsersToRoles(userIdd,"user");
};
and
Meteor.startup(function () {
// always start from scratch (you will want to comment this line at some point !)
Meteor.users.remove({});
if(Meteor.users.find().count()===0){
insertUsers();
}
})
and
Meteor.publish("user", function () {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {'roles': 1}});
} else {
this.ready();
}
});
And I tried to route to the user/admin portals like this:
router.js
Router.route('/', {
before: function() {
if (! Meteor.userId()) { // I acutally added this check that the user is not logged in after the infinite loading problem but I thought the question was getting too long so I just left it in rather
this.render('Home')
} else {
if (Roles.userIsInRole(Meteor.user(), 'admin')) {
Router.go('/admin')
} else {
Router.go('/user')
}
}
},
waitOn: function () {
return Meteor.subscribe('user');
}
});
Now this very almost works! If I log is as either user I go to the right portal. However, when I sign out, my onBeforeAction (i.e. first code block in this question) only renders the Home template and does not actually change the URL to '/' (i.e. the URL remains either '/user' or '/admin'). Now when I try log in a second time, it will always take me to the route that I was taken to on the first log in unless I manually change the browser URL to '/'. So I thought I'd just replace the this.render('Home') with a Router.go('/'); but that seems to have created some sort of infinite loop where the Home template never renders (it did incidentally now for the first time correctly render my loading template though).
So thanks for reading all that! What's the right way to do this?
Try adding Router.go('/'); in your logout button event, along with Meteor.logout();
Example:
Template.loginButtons.events({
'click #login-buttons-logout' : function (event, template) {
Meteor.logout(function(err) {
Router.go('/');
});
}
});
I had the same issue as you, and that was the simplest way I've found to return to home page after logout.

Meteor Iron Router goes to a route's waitOn first instead of Router.onBeforeAction

I've got the Meteor Roles package and I'm trying to define an admin route:
var requireLogin = function() {
if (! Meteor.user()) {
debugger // #1
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
console.log("no user");
this.render('AdminLogin');
}
} else {
this.next();
}
};
Router.onBeforeAction(requireLogin, {only: ['AdminMain']});
Router.route('/admin', {
name: 'AdminMain',
layoutTemplate: 'AdminLayout',
waitOn: function(){
debugger // #2
return [
Meteor.subscribe("appointments")
]
}
});
I've got this in server/publications:
Meteor.publish('appointments', function() {
if (Roles.userIsInRole(this.userId, ['assistant','admin'])) {
return Appointments.find();
} else {
console.log("no user");
return [];
}
});
The first debugger that gets set off is debugger #2 in the waitOn. Why? I have an OnBeforeAction specified precisely for that route. According to the Iron Router guide, Our onBeforeAction hook function will run before our route function when the user navigates to "/admin". If the user is not logged in, the route function will never get called and the AdminPage will not render to the page.
Well, it certainly looks like the route function is being called before the OnBeforeAction considering that debugger stops first to waitOn for a Meteor subscription. Since this subscription requires an admin user to be logged in on the server, if I press continue on debugger the server console logs "no user" and the loading screen goes on forever and forever. The actual OnBeforeAction function for requireLogin never gets called.
waitOn is called before OnBeforeAction. This behavious is corect. From the iron-router docs:
Another alternative is to use waitOn instead of subscribe. This has the same effect but automatically short-circuits your route action and any before hooks (see below), and renders a loadingTemplate instead.
Source
For handling subscriptions you can use 'subscriptions' option:
Router.route('/post/:_id', {
subscriptions: function() {
// returning a subscription handle or an array of subscription handles
// adds them to the wait list.
return Meteor.subscribe('item', this.params._id);
},
action: function () {
if (this.ready()) {
this.render();
} else {
this.render('Loading');
}
}
});
Source

Meteor - Problems caused by Meteor.user() not defined at initial page load. How can I wait until Meteor.user() is available/defined?

In my Meteor app I have some collections I would like to subscribe to immediately upon login, and other collections I would like to subscribe to when the user visits or revisits the initial home page, but not otherwise.
The first set of collections should always be subscribed to throughout, but the second set should be turned off and on as the user leaves and returns to the initial screen.
I have the following code:
Meteor.startup(function () {
Meteor.subscribe('collection_one', Meteor.user().profile.setting_one);
Meteor.subscribe('collection_two', Meteor.user().profile.setting_two);
});
Router.route('/', {
name: 'home',
path: '/',
template: 'home',
waitOn: function() {
return [
Meteor.subscribe('collection_three', Meteor.user().profile.setting_three),
Meteor.subscribe('collection_four', Meteor.user().profile.setting_four),
]
}
});
My problem is that immediately upon startup and immediately upon going to the home page, Meteor.user() returns undefined. I would like to wait until Meteor.user() is defined, and then take these actions. How can I do this?
Meteor.startup() does not run code as a reactive computation, so even though Meteor.user() is a reactive data source it won't trigger a computation.
The reactivity section of the docs has a list of functions that run code as reactive computations.
You can use Tracker (previously called 'Deps') to create a reactive computation, like this:
Tracker.autorun(function () {
if (Meteor.user()) {
Meteor.subscribe('collection_one', Meteor.user().profile.setting_one);
Meteor.subscribe('collection_two', Meteor.user().profile.setting_two);
}
});
But it looks like you're using Iron Router so you could also set a global waitOn() with Router.configure to solve it, like this:
Router.configure({
layoutTemplate: 'MasterLayout',
loadingTemplate: 'Loading',
notFoundTemplate: 'NotFound',
templateNameConverter: 'upperCamelCase',
routeControllerNameConverter: 'upperCamelCase',
// This method will re-run when ever Meteor.user() changes.
waitOn: function () {
// Making sure setting_one and setting_two are available (which they won't be initially)
var setting_one = Meteor.user() && Meteor.user().profile && Meteor.user().profile.setting_one;
var setting_two = Meteor.user() && Meteor.user().profile && Meteor.user().profile.setting_one;
// Subscribe to the published version of the server side collections
return [
Meteor.subscribe('collection_one', setting_one),
Meteor.subscribe('collection_two', setting_two)
];
}
});
The key is to use Tracker.autorun()
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
let username = ''
Tracker.autorun( function(currentComputation) {
if (Meteor.user()) {
username = Meteor.user().username
if (username) // do something with username
return
}
})
currentComputation is optional

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