I have created a angularJS application with yeoman, grunt and bower. I have tried a simple login example. After loggin in, it will goto home page. And for any route changes it will check for whether the user is logged in or not. If logged in, it will redirect to home or the particular route, otherwise re-route to login page. This all working fine for me.
Here is app.js
'use strict';
//Define Routing for app
angular.module('mainApp', []).config(['$routeProvider', '$locationProvider',
function($routeProvider,$locationProvider) {
$routeProvider
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'RegisterController'
})
.when('/home', {
templateUrl: 'views/home.html',
controller: 'homeController'
})
.otherwise({
redirectTo: '/home'
});
}])
.run( function($rootScope, $location) {
// register listener to watch route changes
$rootScope.$on( "$routeChangeStart", function() {
var url=$location.path();
var location=url.replace("/","");
var authnotallowed=false;
if(location.indexOf("login")!=-1||location.indexOf("register")!=-1){
authnotallowed=true
}
if ( $rootScope.loggedUser == null ) {
// not logged user, should be going to #login
if(authnotallowed){
$location.path(url);
} else{
$location.path( "/login" );
}
} else {
// not going to #login, should redirect now
if(authnotallowed){
$location.path("/home");
} else{
$location.path(url);
}
}
});
});
angular.module('mainApp').factory("page", function($rootScope){
var page={};
var user={};
page.setUser=function(user){
$rootScope.loggedUser=user;
}
return page;
});
Here is my loginControler.js
'use strict';
angular.module('mainApp').controller('LoginController', function($scope, $location, page) {
$scope.user = {};
$scope.loginUser=function(){
var name=$scope.user.name;
var pwd=$scope.user.password;
if(name=="1234" && pwd=="1234"){
page.setUser($scope.user);
$location.path( "/home" );
} else {
alert("Invalid credentials");
}
}
});
All are working fine for me.
Since I am using grunt, the url is like http://localhost:9000/#/login
After logging in it is going to home page, if I put like http://localhost:9000/#/login
or http://localhost:9000/#/register
or any other url. And if I logout and try any page, it goes to login.
The problem is,after logging in when I try just http://localhost:9000/
or I close tab and open the url again, it is going to login page (means the loggedUser is null).
Why it is happening? And how can I solve it?
Do I need to set some cookies or something? If so, how?