I need to restrict users from accessing the /dashboard view and /add-item view, as well as any other views in my AngularJS application.
Here is my router configuration:
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('login');
$stateProvider.
state('app.dashboard', {
url: '/dashboard',
templateUrl: appHelper.viewsPath('dashboard/views/dashboard'),
controller: 'DashBoardController as DashBordCtrl',
}).
// Add Item
state('app.add-item', {
url: '/add-item',
templateUrl: appHelper.viewsPath('item/views/add-item'),
controller: 'ItemController as ItemCtrl',
})
});
Once a user logs in, I store their token in local storage. My goal is to prevent access to any view if the token is not present.
This is my login controller code snippet:
$scope.register = function(credentials){
LoginService.post(credentials,function(success){
$state.go('app.add-item');
SessionService.set("token",success.accessToken);
},function(error){
FlashService.showError("Please Enter Valid Email Password");
});
}
}
In case of a 401 error, I redirect the user back to the login page using this interceptor:
app.config(function ($httpProvider) {
// $http.defaults.headers.common.Authorization = '';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.interceptors.push(function ($location, $q, SessionService, FlashService) {
return {
request: function (config) {
config.headers = config.headers || {};
config.headers.Authorization = SessionService.get('token');
return config;
},
responseError: function (response) {
if (response.status === 401) {
SessionService.unset('token');
$location.path('/login');
}
return $q.reject(response);
}
};
});
});
If a user tries to directly access /add-item through the URL, the page briefly opens before closing due to a server-side 401 error, redirecting them to the login page. I want to prevent any unauthorized views from opening without a successful login. As a newcomer to AngularJS, I'm seeking guidance on how to achieve this. Please assist.