User Authentication With Firebase Auth and Realtime Database.

User Authentication With Firebase Auth and Realtime Database.

Firebase is a Google-backed backend as a service (BaaS) platform that offers developers the tools and resources they need to create high-quality apps. It includes many of the services that programmers would typically have to create on their own. Those services include file hosting, push notifications, real-time databases, and user authentication. The client-side can communicate with the backend services thanks to Firebase's SDKs, which frees the developer to concentrate on making the app user-friendly. The apps that can benefit from firebase products are virtually endless.

In this article, we will work on user authentication with firebase auth and user data storage with firebase real-time database. First, the project's HTML files would be created. These files should include a registration form, a login form, and a log-out button. The layout of the page is entirely up to you. Assign the necessary elements unique ids or classes so that javascript can easily access them.

register.html

 <section
        class="register-wrapper"
        style="
          width: 90%;
          margin: 20px auto;
          display: flex;
          justify-content: center;
        "
      >
        <form class="register-form">
          <div class="">
            <label for="full_name">full name</label>
            <input
              type="text"
              class="full_name"
              placeholder="enter full name"
              id="full_name"
            />
          </div>

          <div class="">
            <label for="email">email </label>
            <input
              type="text"
              class="email"
              placeholder="enter email"
              id="email"
            />
          </div>

          <div class="">
            <label for="pswd">password</label>
            <input
              type="password"
              class="pswd"
              placeholder="enter password"
              id="pswd"
            />
          </div>

          <section
            class="register-btn"
            style="width: 200px; margin: 20px auto; height: 40px"
          >
            <button style="width: 100%; height: 100%">register</button>
          </section>
        </form>
      </section>

login.html

 <section
        class="login-wrapper"
        style="
          width: 90%;
          margin: 20px auto;
          display: flex;
          justify-content: center;
        "
      >
        <form class="login-form">
          <div class="">
            <label for="email">email </label>
            <input
              type="text"
              class="email"
              placeholder="enter email"
              id="email"
            />
          </div>

          <div class="">
            <label for="pswd">password</label>
            <input
              type="password"
              class="pswd"
              placeholder="enter password"
              id="pswd"
            />
          </div>

          <section
            class="login-btn"
            style="width: 200px; margin: 20px auto; height: 40px"
          >
            <button style="width: 100%; height: 100%">login</button>
          </section>
        </form>
      </section>
<!--log-out button-->
<div
        class="logout-btn"
        style="width: 200px; margin: 20px auto; height: 40px"
      >
        <button style="width: 100%; height: 100%">log out</button>
      </div>

The next step is to create the various javascript files needed to integrate Firebase. You can add firebase to your project by following these steps:

  1. Create a new project on the firebase site and ensure you turn off google analytics if it is not necessary.

  2. Select the web app option on the project overview page.

  3. Add Firebase to your app by re-entering the project name and adding the SDK to your vanilla js project.

  4. For this project, we would be adding it using the script tag.

  5. Click on the "continue to the console" button to move to the next screen.

  6. Select the authentication option for the authentication method and the database usage, and select the real-time database option.

  7. Get started with firebase auth by selecting and enabling the preferred sign-in method. In this case, it is the email and password method.

Let us get started.

register.js

Firstly, link the file to the HTML file using the script tag. In the script element, add the type attribute with a value of module.

    <script src="./register.js" type="module" defer></script>

Next is to initialize firebase into your register.js file.

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "API key",
  authDomain: "vanillaauth-f0680.firebaseapp.com",
  projectId: "vanillaauth-f0680",
  storageBucket: "vanillaauth-f0680.appspot.com",
  messagingSenderId: "120111675939",
  appId: "1:120111675939:web:9f22f170ea95d7d369cf96",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

After initializing, import "getAuth" and "createUserWithEmailAndPassword" from firebase auth and add the following lines of code.

//import initializeApp here
import {
  getAuth,
  createUserWithEmailAndPassword
} from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js";

//initialize firebase here
const auth = getAuth();

//form element
const register = document.querySelector(".register-form");
// form validation
register.addEventListener("submit", (e) => {
  e.preventDefault();
//form details
  const email = document.querySelector(".email").value;
  const password = document.querySelector(".pswd").value;
  const full_name = document.querySelector(".full_name").value;
  // firebase sign up
  createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed in
      const user = userCredential.user;
      //console.log({ user });
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      // ..
    });
});

On click of the submit button , it sends the necessary data- email, password and unique id- to the firebase users tab in the authentication page.

login.js

In the login.js file, perform the same steps as in register.js. The only difference is that instead of importing "createUserWithEmailAndPassword" with "getAuth" , import "signInWithEmailAndPassword".

//import initializeApp here
import {
  getAuth,
 signInWithEmailAndPassword
} from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js";

//initialize firebase here
const auth = getAuth();

//form element
const login = document.querySelector(".login-form");
// form validation
login.addEventListener("submit", (e) => {
  e.preventDefault();
//form details
  const email = document.querySelector(".email").value;
  const password = document.querySelector(".pswd").value;
  // firebase sign up
 signInWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed in
      const user = userCredential.user;
      //console.log({ user });
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      // ..
    });
});

Firebase Realtime-database

This allows the storage of the app user's information. It works the same way databases work and is a NoSQL database.

The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. When you build cross-platform apps with our Apple platforms, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data.

Create database

  1. Navigate to the Firebase console's Real-time Database section. You'll be asked to choose an existing Firebase project.

  2. Select a location from the dropdown options.

  3. Select a starting mode for your security rules. For this project, the lock mode would be used.

  4. Import database into your project and start working.

The code snippet below shows the integration of the real-time database into the register.js file.

//import initializeApp here
import {
  getAuth,
  createUserWithEmailAndPassword
} from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js";
import {
  getDatabase,
  set,
  ref,
} from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";

//initialize firebase here
const auth = getAuth();
//initialize database
const database = getDatabase();


//form element
const register = document.querySelector(".register-form");
// form validation
register.addEventListener("submit", (e) => {
  e.preventDefault();
//form details
  const email = document.querySelector(".email").value;
  const password = document.querySelector(".pswd").value;
  const full_name = document.querySelector(".full_name").value;
  // firebase sign up
  createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed in
      const user = userCredential.user;
      // realtime database
      set(ref(database, "users/" + user.uid), {
        full_name: full_name,
        email: email,
      });
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      // ..
    });
});

In the login.js file, add the code snippets below.

//import initializeApp here
import {
  getAuth,
 signInWithEmailAndPassword
} from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js";
import {
  getDatabase,
  update,
  ref,
} from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";

//initialize firebase here
const auth = getAuth();

//form element
const login = document.querySelector(".login-form");
// form validation
login.addEventListener("submit", (e) => {
  e.preventDefault();
//form details
  const email = document.querySelector(".email").value;
  const password = document.querySelector(".pswd").value;
  // firebase sign up
 signInWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed in
      const user = userCredential.user;
      const date = new Date();
      update(ref(database, 'users/' + user.uid), {
        last_login: date
      } )
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      // ..
    });
});

In the login.js section, update() is for updating the user info in the database.

Log-out user

To sign out a user with firbase/auth is as easy as adding a signout method to the button. Literally.

  1. HTML.
<body>
<!--codes go here-->
     <div
        class="logout-btn"
        style="width: 200px; margin: 20px auto; height: 40px"
      >
        <button style="width: 100%; height: 100%">log out</button>
     </div>
</body>
  1. Javascript.
import {
  getAuth,
  signOut,
} from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js";

const logout = document.querySelector(".logout-btn");
const auth = getAuth();
logout.addEventListener("click", (e) => {
  signOut(auth)
    .then(() => {
      // Sign-out successful.
      alert("successfully signed out");
    })
    .catch((error) => {
      // An error happened.
    });
});

Conclusion

Firebase has both disadvantages and advantages. The goal of this article is to teach you how to use Firebase's authentication and database services. There is a lot more you can do with Firebase than just on the web and hopefully , this article clarifies and answers your question on the authentication process.