Reputation: 19787
I have a basic authentication check on route change which simply checks the existence of a SessionStorage key/val. However, I have noticed that if an unauthenticated user navigates to a forbidden page who's controller contains an AJAX call, the AJAX call still happens in the background even though the forbidden page doesn't load and the user is instead redirected to login. To get around this, I have added the same authentication check in every controller. This is becoming a bit tedious and I was wondering if there is a better way, or a way I can globally check authentication before a controller's methods are run. Here is the auth function on route change:
app.run(function ($rootScope, $location, authenticationService) {
$rootScope.clearAlerts = function(){
$rootScope.alerts = []
}
$rootScope.credentials = {
username: "",
password: ""
};
$rootScope.goto = function(url){
$location.path(url);
}
$rootScope.authenticated = authenticationService.isLoggedIn()
$rootScope.logOut = function () {
authenticationService.logOut();
}
var publicRoutes = ['/login'];
$rootScope.$on('$routeChangeStart', function (event, next, current) {
$rootScope.credentials.from = $rootScope.desiredPath || '/login'
$rootScope.authenticated = authenticationService.isLoggedIn();
if (!_(publicRoutes).contains($location.path()) && !$rootScope.authenticated) {
$rootScope.desiredPath = $location.path();
$location.path('/login');
}
})
})
Upvotes: 0
Views: 831
Reputation: 6963
I suggest you should check authentication on server side and return appropriate message on client side
Below is the url help http://www.espeo.pl/2012/02/26/authentication-in-angularjs-application
and Write global handler in client side to check it
Below is a sample code:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'], function ($routeProvider, $locationProvider, $httpProvider) {
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
window.location = "./index.html";
return;
}
// otherwise
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
Upvotes: 2