Search code examples
angularjsangularjs-routing

AngularJS website with user logins


I want to make a website where people can register and log in, but if I'm right. Everytime the user refeshes the page he will be logged out? How do I prevent that?

For example:

User logged in ➞ does his stuff on the website ➞ refreshes the page ➞ is logged out


Solution

  • This is going to be a short answer to broad topic, but to answer your questions:

    First of all, you would need some kind of authentication service on the back-end to verify the user. On successful login it would return HTTP 200 and the user information:

    {
      "user":{
        "firstname": "MyFirstname"
        "lastname": "MyLastname"
      } 
    }
    

    The user information (and probably some sort of token or session-id), will be stored client-side. This will keep the data persisted (even if the browser window is closed) and you will always have access to it from the rest of your application.

    angular.module('app').factory('AuthenticationService', function() {
      // call the back-end login service
      // handle login, logout, authentication and authorization 
      // storing the userinfo in localstorage, cookie etc.
    });