Firebase firestore in the forum application #2: Local server, Routing and template, Login Gmail

in #utopian-io5 years ago (edited)

Repository

https://github.com/firebase

What Will I Learn?

  • Local server with firebase
  • Routing and system template
  • Login with Gmail

Requirements

  • Basic Javascript
  • Install Firebase

Resources

Difficulty

Basic

Tutorial Content

In this tutorial, we will continue with our previous tutorial about forum applications using Firebase, in the previous tutorial there were not many things we made. but you have to follow the tutorial because the previous tutorial discussed the preparation and initialization of this project. For those of you who don't know what firebase is, you can visit the official documentation. let's just continue this tutorial.

Run forum app in local server

We have done a lot of preparation and this tutorial we will start making our forum application with database Firestore, the first thing to do is to create a local server to use in the development process of the application that is being created, remember this is only a development process not live. We can create our local server in the following way:

Run local server

Because we have installed node.js then we can create a local server that will run the firebase application, here I will do a firebase server.

firebase server --only functions, hosting

Screenshot_17.png

What we will run on a local server are functions and hosting. Because that's what we choose when we first initialize the project.

Routing in firebase

If it works then we can access routing that we made in the previous tutorial, here is the routing we have created:

app.get('/forum', function(req, res) {
    res.render('home')
});

by using an express instance from const app = express();. We can create a routing, we created the instance in the previous tutorial. Keep in mind that Firebase does not provide a routing system but we can use system routing from Express which is a framework from Node.js.

To make routing quite easy, we only need to use the get() function which has two parameters. The first is the URL and the second is the callback function function(req, res) { } that has the request and response parameters.

Render template

If we look at routing '/ forum', then we can see this URL will render a template res.render('home'). the template that will be rendered is home. The template system that we created is quite simple, you can see it in the previous tutorial here. I will create a directory that will contain the templates that will be used in this forum application.

app.engine('hsb', cons.handlebars);
app.set('view engine', 'hbs');
app.set('views', './views');

We can see in the code above I made a folder with the name views. This folder will become our template directory and we can see in the picture below in that folder we have a home template to render in the /forumURL.

Screenshot_1.png

And in the home.hbs the template I will use a simple template that uses a boost, here we can that we have successfully rendered the template in the routing /forum. The extension of the template that we are rendering is .hbs, this is the extension of the handlebars template. we can see the template that we are rendering like the following:

home.hbs

<!DOCTYPE html>
<html>
<head>
    <title>This the homepage</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="jumbotron">
  <h1 class="display-4">Hi, Welcome to forum app in firebase!</h1>
  <p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
  <hr class="my-4">
  <p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
  <p class="lead">
    <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
  </p>
</div>

</body>
</html>

ezgif.com-video-to-gif.gif

well, we can see in the picture above we have successfully rendered the page in the routing / forum.

Firebase configuration on the project

Here we will start using firebase, before using it we must configure it first, here firebase provides 3 options. For configurations on Android, iOS and on the Web. because we will use it on the web we can choose the configuration on the web, for more details we can see in the picture below:

Screenshot_3.png

I will configure it via CDN to make it easier. then on the home.hbs page, we can add the script given by firebase as you can see in the picture above.

home.hbs

<!DOCTYPE html>
<html>
<head>
    <title>This the homepage</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    (html comment removed:  The core Firebase JS SDK is always required and must be listed first )
    <script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-app.js"></script>

(html comment removed:  TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#config-web-app )
    <script>
      // Your web app's Firebase configuration
      var firebaseConfig = {
        apiKey: "AIzaSyBjqtIMpcWqEVA1SsI5lkDhDPQZHvdaKYM",
        authDomain: "forum-firebase-b3205.firebaseapp.com",
        databaseURL: "https://forum-firebase-b3205.firebaseio.com",
        projectId: "forum-firebase-b3205",
        storageBucket: "forum-firebase-b3205.appspot.com",
        messagingSenderId: "831909117594",
        appId: "1:831909117594:web:05602291ce42908b"
      };
      // Initialize Firebase
      firebase.initializeApp(firebaseConfig);
    </script>
</head>
<body>
<div class="jumbotron">
  <h1 class="display-4">Hi, Welcome to forum app in firebase!</h1>
  <p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
  <hr class="my-4">
  <p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
  <p class="lead">
    <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
  </p>
</div>

</body>
</html>

Of course, every script given by Firebase is different from other projects if you follow it, you definitely have a different configuration script than the one in the tutorial. so you can replace it with the existing script.

Login with Gmail

Well after configuring firebase, now we will make our first feature, the authentication system. there are many auth systems that we can make, which we will learn this time is auth with a Gmail account. What we need to do first is to enable the auth system with Gmail. By default, the value is still disabled. We can change it in our firebase console. For more details, we can see in the picture below:

Enable auth with Gmail

Screenshot_4.png

Well, after we enable auth with Google we can create a script for the login in the next section

Create a script for Gmail login

For the auth section script, I will separate it and in a separate file, here I will make it in the public/assets/js/auth.js directory. For more details, see the following image:

Screenshot_5.png

and the following is the contents of auth.js

var auth = firebase.auth();

function login() {
    var provider = new firebase.auth.GoogleAuthProvider();

    firebase.auth().signInWithPopup(provider).then(function(result) {

      alert("Successfully logged in..");
    }).catch(function(error) {
      console.log(error)
    });
}
  • We can create an instance of firebase.auth () to use the auth system var auth = firebase.auth();. Here we will create a function login(). which will be called on the interface button on the frontend.
<button class="btn btn-danger" type="button" name="button" onclick="login()">Login Gmail</button>
  • And then we can choose to provide what we will use for auth, here we will use Gmail so we can define it like this var provider = new firebase.auth.GoogleAuthProvider();. So later you can replace it with the provider you want, like twitter, facebook, GitHub or something else.

  • Then we can pass the provider variable into the signInWithPopup() function to bring up the login popup, thef function is promise so if it works we can see it in the function then() and if it fails we can see the results in the catch().

  • Now we will test whether our Gmail login is successful, here I will test it with my Gmail account, it's [email protected]. If the Gmail login is successful, we will alert alert("Successfully logged in..");.

ezgif.com-video-to-gif (1).gif

We can see in the demonstration above, we have successfully logged in with a Gmail account on our forum application. have finished our tutorial this time. hopefully, it will be useful for you, thank you.

Curriculum

  • Forum app

Firebase app#1

Proof of work done

https://github.com/milleaduski/firebase-forum

Sort:  

Thank you for your contribution @duski.harahap.
After reviewing your contribution, we suggest you following points:

  • Using the first person in the tutorials makes it difficult to understand the tutorials. We suggest using the third person in your text.

  • Use headings to distinguish sections of different functionalities.

  • Thanks for following some suggestions we gave in previous tutorials.

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!

Congratulations @duski.harahap! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You published more than 100 posts. Your next target is to reach 150 posts.

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Do not miss the last post from @steemitboard:

New japanese speaking community Steem Meetup badge
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Hi @duski.harahap!

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, @duski.harahap!

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!

Coin Marketplace

STEEM 0.28
TRX 0.11
JST 0.034
BTC 66396.53
ETH 3174.43
USDT 1.00
SBD 4.15