We added here to our project Firebase user authentication service. And here we will continue that – we will integrate Firebase authentication inside our web application (in my case it was VueJS app (Vue CLI)).
You can find whole front-end app project files HERE ON GITLAB.
Let’s go further in step by step instructions:
- We have to import firebase.ts configration file created in previous article HERE:
Add firebase auth to your front-end project - USER REGISTRATION – we will use two methods. First one 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 log in first, then download 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 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.