We're making a meteor app using angular and ui-router to control the states. We want to show a promo site if the user doesn't have access to the main part of the site. There will be a flag on the user's document in the User collection in mongodb as to whether they have access or not.
How would we direct to this promo state before a state is loaded if they don't have access? The basic flow would be calling a function to check whether they have access, and then loading a state based on that.
In the route for the protected page (or in my case the parent of a set of protected pages), put this:
.state('app', {
abstract: true,
template: '<mymenu></mymenu>',
controller: Menu,
resolve: {
currentUser: ($q) => {
var deferred = $q.defer();
Meteor.autorun(function () {
if (!Meteor.loggingIn()) {
if (Meteor.user() == null) {
deferred.reject('AUTH_REQUIRED');
} else {
deferred.resolve(Meteor.user());
}
}
});
return deferred.promise;
}
}
});
The resolve part will reject the route (see below for the handler), and also ensure that Meteor.user() is fully loaded before activating the route.
Put this handler in your .run method:
function run($rootScope, $state) {
'ngInject';
$rootScope.$on('$stateChangeError',
(event, toState, toParams, fromState, fromParams, error) => {
console.log("$stateChangeError: "+error);
if (error === 'AUTH_REQUIRED') {
$state.go('login');
}
}
);
}
It will redirect you to the login page (or any other page of your choice)