Coding

create a file redis.js on root folder of the project and paste this code.

RedisStore function creates a store in redis to keep session data and return an object which have multiple methods like one we’ve used in getAllActiveSession() function which we’ll later use. The RedisStore function accepts following parameters.

client An existing client

An existing client host Redis server hostname

Redis server hostname port Redis server portno

Redis server portno ttl Server session time to live

We have created the redis store now connect this store to express session. To do so write this code in app.js

session here is middleware which would execute on every request. Now let’s create a login route which renders the login page. Write this code in app.js

The res.render function will search login.ejs file in views directory and and renders it to sends it’s html to the client. We don’t have a login page yet now we’ll create one. Create a login.ejs file in views directory and write this code

Login page is created, what will happen if a submit the login form? It will give an error because we haven’t yet created any route to handle login submission for this we’ll create a login route with POST method.

In this function first we’ll authenticate the user, If it exists in database and its password is correct (I’m not going to show you how to do cause I presume you already know it.). If user get authenticated a session will be created for the user and page will redirected to the list route.

In list route we can see list of all active users. List route will look like this

Remember we had defined a function getAllActiveSession() in redis.js, this function returns all active sessions of users from session store. List route is auth protected means you can’t go to this route if you are not logged in. To make this route protected I have created a middleware function requireLogin() which checks if the user is logged in or not if it is not logged in, this function redirects you to login page.

We got the active users data now we’ll pass this data to list page to show it on client’s end by assigning this data to res.locals.users we can access this in list.ejs file which is inside the views directory. So list.ejs file will look like this

See this <%-JSON.stringify(users)%> in script . why we are passing users object like this? Because ejs files renders on server and send html to the client, if we don’t stringify the object we’ll see [Object object] on client’s end. So to send object to the client, first we’ll stringify the object on server end and then parse this on client’s end and then we can use it.