Menu
Dev Bay – front-end tips
  • Front-end tips
  • Back-end tips
  • Converters
Dev Bay – front-end tips

FIREBASE: AUTHENTICATION IN WEB APP

Posted on March 21, 2021July 26, 2022

In our previous article about Firebase here we described how to create Firebase account, how to add it to our project and how to deploy whole project on Firebase hosting.

We added here to our project Firebase user authentication service in web application. And here we will continue that – we will integrate Firebase authentication inside our web application (in my case it was VueJS app).

You can find whole front-end VueJS app project’s files HERE ON GITLAB.

Table of Contents

  • Firebase authentication in web app – example
    • Related posts:

Firebase authentication in web app – example

Let’s go further in step by step instructions with integration Firebase with our VueJS web application:

  1. We have to import Firebase.ts configration file created in previous article HERE:

    Firebase config in out web app
    Firebase config in out web app
  2. USER REGISTRATION – we will use two methods. First to create an account, the second one to send verification email – here as actions in Vuex store (this is a VueJS CLI project):
    actions: {
        async createAccount ({ dispatch }, { email, pass }) {
          let res: firebase.auth.UserCredential | boolean;
     
          try {
            res = await firebase.auth().createUserWithEmailAndPassword(email, pass);
          } catch (error) {
            alert(`${error.code}: ${error.message}`);
            return;
          }
     
          const { user }: { user: firebase.User | null } = res;
          
          console.log(res);
     
          if( res && user && user.emailVerified === false) {
            dispatch("sendVeryfication");
          } else {
            debugger;
          }
        },
        async sendVeryfication () {
          let res: Promise<void> | undefined;
     
          try {
            res = firebase.auth().currentUser.sendEmailVerification(); //TO SPRAWDZIC KONIECZNIE!!!
            //https://stackoverflow.com/questions/40349987/how-to-suppress-error-ts2533-object-is-possibly-null-or-undefined
            alert("WELL DONE! Verification email sent!")
          } catch (error) {
            alert("Error: " + error);
          }
        }
      }
    

     

  3. Login- we have to login first, then download from Firebase the auth token and save it in the application (here in vuex state):
    async login ({ dispatch }, { email, pass }: { email: string, pass: string }) {
       try {
         const res: firebase.auth.UserCredential = await firebase.auth().signInWithEmailAndPassword(email, pass);
         dispatch('getIdToken');
       } catch (err) {
         alert(`Error: ${err.code} - ${err.message}`);
       }
     },
     
     async getIdToken ({ commit }) {
       const idToken: string | undefined = await firebase.auth().currentUser?.getIdToken(true);
       commit('set_userIdToken', idToken ? idToken : "");
     },
    
  4. After initializing the web JavaScript application, every time (in main component in hook, for example mounted in VUEJS) we have to use the method which communicates with FIREBASE and checks user status:
        listenUserInfo ({ commit, dispatch }) {
          firebase.auth().onAuthStateChanged((user) => {
            if(user) {
              commit("set_userLogin", user.email);
              commit("set_userVerified", user.emailVerified);
              dispatch('getIdToken');
            } else {
              commit("set_userLogin", "");
              commit("set_userVerified", false);
            }
          });
        }
    
  5. Logout action is really simple:
    logout ({ commit }) {
      firebase.auth().signOut();
      commit("set_clearUserData");
    }
    
  6. HERE you can find Firebase documentation about integrating the authentication functionality.

Check next article how to verify logged in user in NodeJS back-end API and give access to protected endpoint.

Related posts:

VueJS – loading spinner component FIREBASE: Add Firebase to your JavaScrpt project + Firebase CLI installation + Firebase hosting deploy Insert JavaScript vuejs/react/angular apps into SalesForce page
©2023 Dev Bay – front-end tips | Powered by SuperbThemes & WordPress