Ghazanfar Ghazanfar - 2 months ago 31
AngularJS Question

$rootScope.$on($stateChangeStart) redirect to login page if base url hits

I am using angular ui-router , angular-cookies for authentication in my ionic mobile application.
Here is my states

.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LogInCtrl'
})
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})

.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templates/search.html'
}
}
})

.state('app.browse', {
url: '/browse',
views: {
'menuContent': {
templateUrl: 'templates/browse.html'
}
}
})
.state('app.playlists', {
url: '/playlists',
views: {
'menuContent': {
templateUrl: 'templates/playlists.html',
controller: 'PlaylistsCtrl'
}
}
})

.state('app.single', {
url: '/playlists/:playlistId',
views: {
'menuContent': {
templateUrl: 'templates/playlist.html',
controller: 'PlaylistCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
});


Here is my runs method code

$rootScope.globals = $cookieStore.get('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
}

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
// redirect to login page if not logged in
var shouldLogin = typeof $rootScope.globals.currentUser == 'undefined';

// NOT authenticated - wants any private stuff
if(shouldLogin || fromState.name === "") {
var token = $rootScope.globals.currentUser == undefined ? null : $rootScope.globals.currentUser;
if (token == null) {
if(toState.name === 'login')
return;
$state.go('login');
event.preventDefault();
} else {
if(toState.name === toState.name)
return;
//TODO: Check token
$state.go(toState.name);
event.preventDefault();
}
}
});


Authentication work fine but when I changed my url to http://localhost:8100/ it redirects to login page , however it show go to playlist page . Need help what I am doing wrong.

Answer

Your page is being redirected to the base url because:

$urlRouterProvider.otherwise('/login');

There's no state defined for /, so the router hits the otherwise condition and redirects to /login