I’m building an app for 1 admin to be able to log in and edit content. When logged in the app will serve up a private html doc structure instead of those not logged in being presented the normal public docs. I’m using Angular-route, Session and Passport for authentication. I want to check if a user is logged in whenever they link to another page on the site. So, if they go somewhere they’re not authorized to be, they can’t edit content on the site.
I’m getting an $injector:modulerr when I run the app on a localhost. The ReferenceError says checkAuth is not defined.
I tried creating a global variable using $rootScope as suggested here:
app.run(['$rootScope', '$http', function($rootScope, $http){
$rootScope.checkAuth = function(){
console.log("rootScope things are happening");
$http.get('/login/loggedin').success(function(user){
if (user !== '0') {
console.log('Authenticated');
return true;
} else {
console.log('Not Authenticated');
return false;
}
});
};
}]);
So, if the user’s logged in, I should get a true and if they’re not logged in, I’ll get a false. But, I still get the checkAuth is not defined injector error and I never see any of my console logs.
The Angular documentation for $rootScope says to use this format:
$rootScope.Scope([providers], [instanceCache]);
So, I tried this:
$rootScope.Scope(['$rootScope', '$http', function($rootScope, $http){...
Unfortunately, that doesn’t work either.
This is an example of using Passport and Angular together which I found somewhat helpful, but they’re allowing multiple users to register (which I don’t want) and it still doesn’t solve the question of a global function for checking if a user is logged in across multiple pages in a website. It may help you to see a similar controller and route file though.
I know that you can use factories and services to do something similar as suggested in previous similar questions, but I was hoping to go this route before trying a different path. Obviously though, if that's the best way, I'll give it a go.
The provided rootscope declaration seems ok to me.
Assign a rootscope value.
app.run(function($rootScope) {
$rootScope.checkAuth = function(){
$http.get('/login/loggedin').success(function(user){
if (user !== '0') {
return true;
} else {
return false;
}
})
};
});
Use it like (don't forget $rootscope dependancy)
app.controller('myCtrl', function($scope, $rootScope) {
$scope.authenticated = function() {
return $rootScope.checkAuth ;
};
});
See live sample to compare: http://jsfiddle.net/TmPk5/6/