Picture Competition Web App - Node JS, Mongo DB and Vue JS

Create a Picture Competition Website in Express JS, MEVN

0
(0)

Logout

Since now the user is logged-in, we need to make him able to log out. We will clear the authentication token from Mongo DB once the user is logged out. We just need to create a “doLogout” function in our “navApp” object in the “footer.ejs” file:

doLogout: function () {
	// send beacon to server before redirecting
    var formData = new FormData();
    formData.append("accessToken", localStorage.getItem(accessTokenKey));

    navigator.sendBeacon(this.baseUrl + "/logout", formData);

    // remove access token from local storage
    localStorage.removeItem(accessTokenKey);
    return true;
},

Then we need to create a POST route in our “server.js” file that will clear out the authentication token from Mongo DB.

// empty the access token of user (logout)
app.post("/logout", async function (request, result) {
    var accessToken = request.fields.accessToken;
 
    await db.collection("users").findOneAndUpdate({
        "accessToken": accessToken
    }, {
        $set: {
            "accessToken": ""
        }
    });
 
    result.json({
        "status": "success",
        "message": "User has been logged out."
    });
});

Refresh the page now and try to click the “Log out” button. You will be redirected to the login page and you will again see the login and sign up button at the top navigation bar. The “accessToken” value from the “users” collection will also get empty from Mongo DB.

How useful was this post

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post





Leave a Reply