totothegreat
totothegreat

Reputation: 1643

How should i recognize if user is logged in or not in angular/node application?

A scenario:

A user tries to login into the application, the credentials than passed to node to check if he exists, if so, some auth credential is placed to true, and the account of the user is than returned to the site, and with angular i have a service that does the following:

angular.module(myapp).service('accountService',function($http){
       var account= null;     
return {
       authUser = function(credentials){
             ....
       };
       setaccount = function(accountObj){
          account = accountObj;
          ... 
       }       
     }

Now it's ok if no refresh is going on, but when a refresh does happen, what is the best way to determine if a user is still logged in or not?

For example: i took a look into mean stack to see their approch, and what they do is like make the userObject exposed so i can do window.loggedinUser (That comes from a session storage of some kind?)

There are other examples i assume that deals with the run method doing something, but my question is this:

every time a user clicks refresh should the program do something in the run to determine if the user is still logged in or not (meaning dealing with server request in every refresh)?

What is the better solution to do so, a simple example will be appreciated....

Upvotes: 0

Views: 195

Answers (1)

Reactgular
Reactgular

Reputation: 54821

For most AngularJS applications the user credentials are fetched from the server via an asynchronous HTTP request. This creates a timing problem of when AngularJS starts up and when the application knows if there is a user session.

You'll have to set the user flag to false at startup, and when the asynchronous call finishes you'll have to change it's state (if the user is logged in).

This becomes a problem if the current route is restricted to signed in users only.

The best recommended approach is to use route promises. Your accountService should provide a method that will return a promise that fetches the current user's session. If it already has it, then great use that one, otherwise it has to perform a HTTP request to get. Either way, the result should always be a promise.

This is how you should make the user session availible in your application. Via a promise on the route.

Upvotes: 1

Related Questions