I am building an application with AngularJS. I have authentication working and when the user is not authorized, he gets redirected to #/login which shows a login form.
However, when the user is authenticated and he manually goes to #/login, the login page is shown again, although the user is still logged in. Is there any way to direct him to the home page in that case?
This is how I do the redirections:
$routeProvider
.when( '/ds', {
templateUrl: 'partials/datasheets-list.html',
controller: 'DatasheetsListCtrl'
} )
.when( '/ds/:datasheetId', {
templateUrl: 'partials/datasheet-detail.html',
controller: 'DatasheetDetailCtrl'
} )
.when( '/login', {
templateUrl: 'partials/login.html',
controller: 'LoginController'
} )
.otherwise( {
redirectTo: '/ds'
} );
This is the code for the LoginController:
var datasheetsControllers = angular.module( 'datasheetsControllers', ['ngCookies', 'datasheetsServices'] );
datasheetsControllers.controller( 'LoginController', ['$scope', '$rootScope', '$location', '$http', '$cookieStore', 'LoginService', function ( $scope, $rootScope, $location, $http, $cookieStore, LoginService )
{
$scope.login = function ()
{
LoginService.authenticate( $.param( {username: $scope.username, password: $scope.password} ), function ( user )
{
$rootScope.user = user;
// Authenticate AngularJS Ajax calls
$http.defaults.headers.common[ xAuthTokenHeaderName ] = user.token;
// Authenticate jQuery Ajax calls
var headers = {};
headers[xAuthTokenHeaderName] = user.token;
$.ajaxSetup({
headers: headers
});
$cookieStore.put( 'user', user );
$location.path( "/" );
} );
};
}] );