How to build a sports prediction application on the steem blockchain using Node/ExpressJS - 2
Repository
https://github.com/nodejs/node
What Will I Learn?
This post contains the second part in a series of tutorials on how you can build a prediction app that allows users to predict the outcome of sport events and post their predictions on the steem blockchain.
You can check out my blog to go through the introduction post.
The application we'll be building will have the following features.
Users will be able to login using their steem account credentials.
A page for creating prediction tickets
User dashboard for viewing prediction tickets by the user and other users
Steem Wallet that allows users to transfer funds
User Profile Page
In the introduction post we covered the user authentication aspect of the app by adding a login page where users can login with their steem username and password.
In this tutorial we'll be creating a page where users can view the list of all sport events happening on a particular day and also make predictions on each event.
Requirements
In order to be able to follow this tutorial the user has to be able to use the following
- HTML/CSS
- JavaScript/JQuery
- TheSportsDB public api
- AxiosJS
- NodeJS/Express
- SteemJS Api
Difficulty
Intermediate
Tutorial Content
By the end of this tutorial we would have created the following,
- Authentication guard, to prevent users that are not logged in from accessing protected pages
For the remainder of this post we'll be working on a page dashboard.html..
In the project folder, in the sub-directory client add a new file dashboard.html.
We want to make it so that whenever a user that's not logged in tries to access dashboard.html they are redirected to the login page.
The contents of the next section covers how to do that.
Authentication Guard
If you recall in our last tutorial, whenever a user logs in some values are returned to the frontend and logged in the console.
The data returned to the client includes
A boolean value
trueindicating that login is successfulA token for the session
An array containing currently logged in user data.
In order to add the authentication guard for our application, we need to set some parameters in login.js on the client side.
Starting from where we stopped in our last tutorial, open login.js and replace console.log(response) with the following
const loginData = response.data;
if (loginData.auth === true ) {
sessionStorage.setItem('authtoken', loginData.token);
// remove current user name and set a new value for current user name, store in local storage
sessionStorage.removeItem('currentUser');
sessionStorage.setItem('currentUser', loginParam.username);
window.location.replace("./dashboard.html");
Save and reload all files then try to login and you will be redirected to dashboard.html
Before moving on, we need to create a logout feature so users can easily log out of the application. This feature will be implemented in dashboard.html.
Open dashboard.html and add the following code to initialize all needed modules.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>SteemPredict User Dashboard</title>
<link rel="stylesheet" href="./css/dashboard.css">
</head>
<body>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js"></script>
<script src="./js/dashboard.js"></script>
</body>
</html>
Directly inside the body tag we want to add a header/banner which will also contain our logout button and the username of the logged in user.
In dashboard.html, add the following code on the line after the opening <body></body> tag.
<section class="banner">
<h1 class="username"></h1>
<a class="logout-btn" onclick="logout()">logout</a>
</section>
In dashboard.js, add the following code
$(document).ready(function() {
$('.username').text(sessionStorage.getItem('currentUser'))
})
If we save all files and reload dashboard.html now, we'll have an interface like below
In dashboard.js, we want to add a new function that helps us log out of the application.
Add the following code in dashboard.js
function logout() {
// remove token from local storage
sessionStorage.removeItem('authtoken');
axios.get('http://localhost:3000/logout').then(response => {
console.log(response);
}).catch(err => {
console.log(err);
})
}
window.location.replace("./login.html");
In the block above, once the logout button is fired the set token for that session will be removed from the database.
Then a request is sent to the server to log the user out from the application.
Finally, the user is redirected back to the login page.
In app.js we are going to add the request route to the list of existing routes, look for the line app.post('/login', loginRouter); and add the following code below it
app.get('/logout', loginRouter);
In routes/login.js add the following code in order process all requests directed at /logout
// log user out
router.get('/logout', function(req, res){
// send response to falsify authentication and nullify token
res.status(200).send({
auth: false,
token: null
})
})
The block above will return a response to the client indicating successful logout.
After the addition of our logout feature, we want to guard our dashboard.html file against users that are not logged in
So, in dashboard.js, add the following code on the line directly above $('.username').text(sessionStorage.getItem('currentUser'))
const sessionToken = sessionStorage.getItem('authtoken');
if (sessionToken === null) {
window.location.replace("./login.html");
}
Now, if you logout of the application and try to re-access dashboard.html without logging in you will be redirected to login.html.
In the next tutorial we will continue working on the dashboard where we'll be displaying different sport events for a particular day and also the prediction options that each user can choose from per event.
Thank you for your contribution @gotgame.
After analyzing your tutorial we suggest the following points below:
The level of your tutorial is basic!
The section with the HTML structure wasn't needed in the tutorial.
The structure of your contribution is a bit confusing. In the next tutorial you are more careful with the structure, because it is important that the contribution is organized so that the reader understands well what you are explaining.
It would be interesting to have some gifs with the demonstration of what you have developed for this tutorial.
Thank you for your work in developing this tutorial.
Looking forward to your upcoming tutorials.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Chat with us on Discord.
[utopian-moderator]
Thank you for your review, @portugalcoin! Keep up the good work!
Hi @gotgame!
Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server
Hey, @gotgame!
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!
Hi, @gotgame!
You just got a 0.18% upvote from SteemPlus!
To get higher upvotes, earn more SteemPlus Points (SPP). On your Steemit wallet, check your SPP balance and click on "How to earn SPP?" to find out all the ways to earn.
If you're not using SteemPlus yet, please check our last posts in here to see the many ways in which SteemPlus can improve your Steem experience on Steemit and Busy.