Problem verifying if a user is authenticated in AngularJS
Just last month I was coding some sweet pice of software when I stumbled into a bit of a problem when it came to verify if a user was already authenticated.
The thing was that if a user refreshed the browser, the authentication token would be gone or if the user would change the route of the application, the token wouldn't be verified.
The solution I came up with was the following:
//when the application runs
//Session, is a service that takes care of the session persistence
app.run(function ($rootScope, $location, Session, $timeout) {
// register listener to watch for route changes
// this event will fire every time the route changes
$rootScope.$on("$routeChangeStart", function (event, next, current) {
//ask the service to check if the user is in fact logged in
if (!Session.isUserLoggedIn()) {
// no logged user, we should be going to the login route
if (next.templateUrl == "partials/login.html") {
// already going to the login route, no redirect needed
} else {
// not going to the login route, we should redirect now
$location.path("/login");
}
}
});
});
I hope this has shed some light onto your software as it has on mine.
Written by Mandingo Brown
Related protips
3 Responses
Can you post your login system application using AngularJS?
Hi krishyalla, I've made some improvements on that particular subject and I'll share them with you. I'll post it over the weekend. Thank you for reading my post ;)
EDIT: here it is https://coderwall.com/p/f6brkg
Hi filipefmelo, I am also trying to implementing the login authentication system..I tried using json file where I stored username and password.