I have a single-page AngularJS app, working with Express, node.js, and MongoDB via Mongoose. Using Passport for user management/authentication.
I'd like the navbar items to change based on whether a user is logged in or not. I'm having trouble figuring out how to implement it.
I find out if a user is logged in through an http
request:
server.js
app.get('/checklogin',function(req,res){
if (req.user)
res.send(true);
else
res.send(false);
On the front end, I have a NavController
calling this using Angular's $http
service:
NavController.js
angular.module('NavCtrl',[]).controller('NavController',function($scope,$http) {
$scope.loggedIn = false;
$scope.isLoggedIn = function() {
$http.get('/checklogin')
.success(function(data) {
console.log(data);
if (data === true)
$scope.loggedIn = true;
else
$scope.loggedIn = false;
})
.error(function(data) {
console.log('error: ' + data);
});
};
};
In my nav, I am using ng-show
and ng-hide
to determine which selections should be visible. I am also triggering the isLoggedIn()
function when the user clicks on the nav items, checking whether the user is logged in during each click.
index.html
<nav class="navbar navbar-inverse" role="navigation">
<div class="navbar-header">
<a class="navbar-brand" href="/">Home</a>
</div>
<ul class="nav navbar-nav">
<li ng-hide="loggedIn" ng-click="isLoggedIn()">
<a href="/login">Login</a>
</li>
<li ng-hide="loggedIn" ng-click="isLoggedIn()">
<a href="/signup">Sign up</a>
</li>
<li ng-show="loggedIn" ng-click="logOut(); isLoggedIn()">
<a href="#">Log out</a>
</li>
</ul>
</nav>
Problem
There are other places in my app where the user can log in/out, outside of the scope of the NavController. For instance, there's a login button on the login page, which corresponds to the LoginController. I imagine there's a better way to implement this across my entire app.
How can I 'watch' whether req.user
is true
on the back end and have my nav items respond accordingly?
you can use $rootScope
to share info across the entire app:
.controller('NavController',function($scope,$http, $rootScope) {
$scope.isLoggedIn = function() {
$http.get('/checklogin')
.success(function(data) {
console.log(data);
$rootScope.loggedIn = data;
})
.error(function(data) {
console.log('error: ' + data);
});
};
};
now you can change the value of loggedIn
from other places in your app by accessing $rootScope.loggedIn
in the same way it is done in the code above.
With that said, you should abstract the relevant code into a service and a directive. This would allow you to have one central place to handle, log in, log out, and the state of $rootScope.loggedIn
. If you post the rest of the relevant code I could help you out with a more concrete answer
You can broadcast that event when user logs in successfully. And no need to keep polling your server if user is logged in you can keep a variable in memory that tells if you have a valid session or not. You can use a token-based authentication which is set in the server side:
services.factory('UserService', ['$resource',
function($resource){
// represents guest user - not logged
var user = {
firstName : 'guest',
lastName : 'user',
preferredCurrency : "USD",
shoppingCart : {
totalItems : 0,
total : 0
},
};
var resource = function() {
return $resource('/myapp/rest/user/:id',
{ id: "@id"}
)};
return {
getResource: function() {
return resource;
},
getCurrentUser: function() {
return user;
},
setCurrentUser: function(userObj) {
user = userObj;
},
loadUser: function(id) {
user = resource.get(id);
}
}
}]);
services.factory('AuthService', ['$resource', '$rootScope', '$http', '$location', 'AuthenticationService',
function ($resource, $rootScope, $http, $location, AuthenticationService) {
var authFactory = {
authData: undefined
};
authFactory.getAuthData = function () {
return this.authData;
};
authFactory.setAuthData = function (authData) {
this.authData = {
authId: authData.authId,
authToken: authData.authToken,
authPermission: authData.authPermission
};
// broadcast the event to all interested listeners
$rootScope.$broadcast('authChanged');
};
authFactory.isAuthenticated = function () {
return !angular.isUndefined(this.getAuthData());
};
authFactory.login = function (user, functionObj) {
return AuthenticationService.login(user, functionObj);
};
return authFactory;
}]);
services.factory('AuthenticationService', ['$resource',
function($resource){
return $resource('/myapp/rest/auth/',
{},
{
'login': { method: "POST" }
}
);
}]);
services.factory('authHttpRequestInterceptor', ['$injector',
function ($injector) {
var authHttpRequestInterceptor = {
request: function ($request) {
var authFactory = $injector.get('AuthService');
if (authFactory.isAuthenticated()) {
$request.headers['auth-id'] = authFactory.getAuthData().authId;
$request.headers['auth-token'] = authFactory.getAuthData().authToken;
}
return $request;
}
};
return authHttpRequestInterceptor;
}]);
controller:
controllers.controller('LoginCtrl', ['$scope', '$rootScope', 'AuthService', 'UserService',
function LoginCtrl($scope, $rootScope, AuthService, UserService) {
$scope.login = function () {
AuthService.login($scope.userInfo, function (data) {
AuthService.setAuthData(data);
// set user info on user service to reflect on all UI components
UserService.setCurrentUser(data.user);
$location.path('/home/');
});
};
$scope.isLoggedIn = function () {
return AuthService.isAuthenticated();
}
$scope.user = UserService.getCurrentUser();
}])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With