How to know if user is logged in with passport.js?

后端 未结 6 1025
日久生厌
日久生厌 2020-12-02 05:01

I\'ve been reading passport.js info and samples for two days, but I\'m not sure after that I did all the process of authenticating.

How do I know if I\

6条回答
  •  日久生厌
    2020-12-02 05:31

    I was searching such solution and came across this page. Question is how to check login status on client side.

    After logging I hide the Login button and show the logout button. On page refresh I again see the login button instead of logout button. The only solution is to save an item in sessionStorage if you are using session (and localStorage if you are using JWT). Delete this item when you logout. Then in every page load check this sessionStorage item and do accordingly.

    if (sessionStorage.getItem('status')) {
        $("#btnlogout").show();
        $("#btnlogin").hide();
    // or what ever you want to do
    } else {
        $("#btnlogout").hide();
        $("#btnlogin").show();
    }
    
    
    
    function Login() {
                var data = {
                    username: $("#myModal #usr").val(),
                    password: $("#myModal #pw").val()
    
                };
                $.ajax({
                    type: 'POST',
                    url: '/login',
                    contentType: 'application/JSON; charset=utf-8',
                    data: JSON.stringify(data),
                    success: funcSuccess,
                    error: funcFail
                });
                function funcSuccess(res) {
                    sessionStorage.setItem('status', 'loggedIn');
    
                    $("#btnlogout").show();
                    $("#btnlogin").hide();
                }
                function funcFail() { $("#pp").text('Login Failed'); };
            };
    
    function Logout() {
        $.ajax({
            type: 'GET',
            url: '/logout',
            contentType: 'application/JSON; charset=utf-8',
            success: funcSuccess,
            error: funcFail,
        });
        function funcSuccess(res) {
            $("#btnlogout").hide();
            $("#btnlogin").show();
            sessionStorage.removeItem("status");
        };
        function funcFail() { alert('Login method Failed'); };
    }; 
    

提交回复
热议问题