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
Let’s go further in step by step instructions with integration Firebase with our VueJS web application:
- We have to import Firebase.ts configration file created in previous article HERE:
- 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); } } }
- 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 : ""); },
- 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); } }); }
- Logout action is really simple:
logout ({ commit }) { firebase.auth().signOut(); commit("set_clearUserData"); }
- HERE you can find Firebase documentation about integrating the authentication functionality.