7. Get Authenticated User’s Data

To get authenticated user’s data, we will be sending the stored access token from local storage to the API using headers. So how can we do that?

We will be sending a header named “Authorization”. Its value will be “Bearer {access token}”.

Video tutorial:

So first go ahead and add the following global properties in your main.js file:

app.config.globalProperties.$user = null;
app.config.globalProperties.$login = false;
app.config.globalProperties.$headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + localStorage.getItem("accessTokenKey")
};

Then replace your <script> tag in your AppHeader.vue with the following:

<script>

    import axios from "axios"
    import swal from "sweetalert2"

    export default {
        data() {
            return {
                login: false,
                user: null
            }
        },

        methods: {

            getUser: async function () {
                const self = this

                // check if user is logged in
                if (localStorage.getItem(this.$accessTokenKey)) {
                    const response = await axios.post(
                        this.$apiURL + "/getUser",
                        null,
                        {
                            headers: this.$headers
                        }
                    )

                    if (response.data.status == "success") {
                        // user is logged in
                        this.$user = response.data.user
					console.log(this.$user)
                    } else {
                        // user is logged out
                        localStorage.removeItem(this.$accessTokenKey);
                    }

                    this.login = (localStorage.getItem(this.$accessTokenKey) != null);
                } else {
                    this.login = false;
                }

                global.user = this.user
            },
        },

        mounted: function () {
            this.getUser();
        }
    }
</script>

This will call an AJAX to the server to get the user’s data. It will attach the access token in the header so the server will know which user’s data needs to be fetched.

Creating Authentication Middleware

Middleware stands between the client and the actual API endpoint. Middleware is called before the request actually processed by API. We will be creating our own middleware for authentication.

We need to create a folder named “modules” in your api folder. And inside it, create a file named “auth.js”. Following will be the code of the auth.js file:

const jwt = require("jsonwebtoken");
const jwtSecret = "jwtSecret1234567890";

const mongodb = require("mongodb");
const ObjectId = mongodb.ObjectId;

module.exports = async function (request, result, next) {
    try {
        const accessToken = request.headers.authorization.split(" ")[1];
        const decoded = jwt.verify(accessToken, jwtSecret);
        const userId = decoded.userId;

        const user = await db.collection("users").findOne({
            accessToken: accessToken
        });

		if (user == null) {
			result.status(401).json({
	            status: "error",
	            message: "User has been logged out."
	        });
			return;
		}

        delete user.password;
        delete user.accessToken;
        delete user.createdAt;

        request.user = user;
        next();
    } catch (exp) {
        result.status(401).json({
            status: "error",
            message: "User has been logged out."
        });
    }
};

Here is what this middleware does:

  1. We are including JWT and Mongo DB modules as we will be needing them in this module too.
  2. Then we are creating an asynchronous function.
  3. In this function, we are first splitting the authorization header into 2 parts.
    1. Originally we had “Bearer {access token}”
    2. After the split, it will become an array of 2 elements [“Bearer”, “access token”]
    3. Then we get the value at index 1 which will be the access token since array indexes start from 0.
  1. Then we verify that token using JWT and our secret key.
  2. It will return the “userId” which we saved during login.
    1. If “userId” is not found, then it will throw an exception and we will return the 401 (un-authorized) status code.
  3. After that, we can get the user data using this access token.
  4. We will delete all the unnecessary keys.
  5. Attach the user with the current request object.
  6. next() function will continue to the API endpoint.

Creating an API endpoint

First, include the authentication middleware we just created in our server.js:

const auth = require("./modules/auth");

Then create an API for fetching user data.

app.post("/getUser", auth, async function (request, result) {
    const user = request.user;

    result.json({
        status: "success",
        message: "Data has been fetched.",
        user: user
    });
});

Notice how we are passing our middleware “auth” as the second parameter. If you refresh the page now and check your browser console, you will see authenticated user’s data like this:

user data
user data

Now we need to show it in the navbar. We also need to hide the login and registration links when the user is logged-in. So add the following v-if condition to your login and registration links in AppHeader.vue:

<li class="nav-item" v-if="!login">

Since we want to show the logout button when the user is logged-in, so add the following condition on the logout dropdown menu:

<li class="nav-item dropdown" v-if="login">

The login and registration links will be hidden and a dropdown is still displaying, which is good. But you need to show the user name in the dropdown. So add the v-text attribute to the <a> tag inside the logout dropdown menu:

<a v-text="$user.name" …>

Now you will see your name in the dropdown menu.

user name navbar
user name navbar

So now we need to work on this logout function.

Conclusion

In this chapter, we have learned how we can create a middleware and pass it to our API endpoints using Node JS.

We also learned how to pass headers from the Vue JS app and handle them in the Node JS server.

In the next chapter, we will learn how to log out the user. That will be pretty simple.