I want to authenticate states in my angular application. The resources that are available are too complicated and I don't understand why.
My simple logic is to set a variable
$rootScope.is_authenticated = true
and check whenever a state is loaded to see if the variable is true or not.
How can I achieve this and why is login and authentication so complicated in angular.
my config file
.config(function($stateProvider,$urlRouterProvider) {
$stateProvider
.state('auth', {
url: '/auth',
templateUrl: 'partials/auth.html',
controller: 'AuthCtrl'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'partials/dashboard.html',
controller: 'DashboardCtrl',
resolve:{
check: function($rootScope, $state){
if($rootScope.is_authenticated == true){
return true;
}
else{
$state.go('auth');
}
}
}
})
$urlRouterProvider
.otherwise("/auth");
login function in my AuthCtrl
//login
$scope.login = function(user){
console.log(user);
$http({
method : "POST",
url : "myapi.com/login",
data : user
}).then(function mySucces(response) {
$scope.data = response.data;
$rootScope.is_authenticated = true;
$state.go('dashbooard');
}, function myError(response) {
$scope.error = response.statusText;
$rootScope.is_authenticated = false;
});
}
logout function
$scope.logout = function(){
$rootScope.is_authenticated = false;
$state.go('auth');
}
I've added another property to my state, resolve. Now the state can only be accessed if the user is logged in. Is this the correct way and if not, what are the problems associated with it