Last Updated: February 25, 2016
· filipefmelo

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 ($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

I hope this has shed some light onto your software as it has on mine.

3 Responses
Add your response

Can you post your login system application using AngularJS?

over 1 year ago ·

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

over 1 year ago ·

Hi filipefmelo, I am also trying to implementing the login authentication system..I tried using json file where I stored username and password.

over 1 year ago ·