My AngularJS app (Angular v1) has a secure login system in place. Users who are not authenticated can only access the login page, forgotten password page, and cookie policy.
I am utilizing ngRoute
as shown below:
$routeProvider
.when('/login:param', {
templateUrl: 'app/login/login.html',
controller: 'loginCtrl',
controllerAs: 'vm'
})
/* ... other routes ... */
.otherwise({
redirectTo: '/login'
});
Now, my goal is to redirect logged-in users directly to the dashboard without allowing access to the "public routes" (routes accessible without authentication), and redirect non-logged-in users to the login page.
To achieve this, I have implemented a check within the Angular run
function and using the $locationChangeStart
event listener:
$rootScope.$on('$locationChangeStart', function (event, next, current) {
if (routeClean($location.path()) && AuthenticationService.isLoggedIn()) {
$location.url(DASHBOARD);
} else {
$location.url(LOGIN);
}
});
Here, DASHBOARD
and LOGIN
constants define the routes to /dashboard
and /login
respectively.
Before proceeding further, I have a couple of questions:
- Is
run
the right place for this check? (though it works, maybe there's a better location) - What is the best practice for achieving this functionality?
The AuthenticationService
service handles user authentication, while routeClean
function checks if a route is included in an array:
var routeClean = function (route) {
for (var i = 0; i < CLEAN_ROUTES.length; i++) {
var pattern = new RegExp(CLEAN_ROUTES[i]);
var bool = pattern.test(route);
if (bool)
return true;
}
return false;
};
Where CLEAN_ROUTES
contains all the "public routes".
CLEAN_ROUTES = [
'/login',
'/forgotten-password',
'/verify-code',
'/reset-password',
'/cookie-policy'
]
Lastly, some final questions:
- Is there a more efficient way to check for "public routes" in Angular?
If, for example, I need to display different login templates based on user roles like:
/login?user=client /login?user=seller /login?user=editor /login?user=admin
Can ngRoute
dynamically handle this differentiation?
Essentially, when logging out and being redirected to the general login page defined by the LOGIN
constant (/login
), is there a way to identify seller, client, etc., and redirect them to the appropriate login page/template?