Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user has logged in on client side

Is there a safe way to check if the user has logged into the application rather than checking if "sid" cookie exists in user's machine ?

I want to allow the user to proceed on certain links on a page only if they have logged in.

I do the login validation on the server side but want to avoid the request trip.

Pure JS or JQuery solution would be appreciated.

Thank you.

like image 468
Me Unagi Avatar asked Feb 09 '16 12:02

Me Unagi


3 Answers

Please try this

Put this code after user first log in

jQuery(window).load(function() {
  sessionStorage.setItem('status','loggedIn') 
});

When ever user clicks a link you can check like

if (sessionStorage.getItem('status') != null))
    //redirect to page
}
else{
    //show validation message
}
like image 146
Rino Raj Avatar answered Oct 06 '22 06:10

Rino Raj


As you ask for a "safe way": No. You should always validate the user's session on the server side for all requests.

Something you could do though is to adapt the front end to the users current status. For example change the "Login"-Link to a "Logout"-Link. For this to work you could set some king of flag on the users machine. You could use the browser local storage for this (http://www.w3schools.com/html/html5_webstorage.asp).

Something else you could for example do is, to change the behavior of for example links:

$("a").click(function(e){
    if(localStorage.getItem("isLoggedIn") !== true) {
        e.preventDefault();
        // this prevents navigation and you can now do your js stuff here
    }
});
like image 44
newBee Avatar answered Oct 06 '22 04:10

newBee


if you are using ASP.Net Identity you can check it as follows

In Razor :

@inject SignInManager<ApplicationUser> SignInManager

@if (SignInManager.IsSignedIn(User))
        {
            <input type="hidden" id="logged" value="true" />
        }
        else
        {
            <input type="hidden" id="logged" value="false" />
        }

In JS:

function check() {
var signed = $('#logged').val();

if (signed === 'true') {
    //What you want to do
}
else {
    window.location.href = "/YourController/YourAction?ReturnUrl=/YourReturnUrl;
}
} 
like image 34
Hasan_H Avatar answered Oct 06 '22 04:10

Hasan_H