Firebase Miniseries 1: Auth

urielbitton

Uriel Bitton

Posted on May 10, 2022

Firebase Miniseries 1: Auth

What is Firebase Auth?

Firebase auth is an authentication api that lets you register, login and manage users on your website/app.

Implementing auth on your app may seem complicated, but if you follow these simple steps i will show you how simple and quick it is to use it.

Step 1 - Initializing our firebase app

Head to Firebase.com and go to the console. Create a new project, enter a project name and disable google analytics on the next slide.
Once your project is created, on the current page you are redirected to, under the title: "Get started by adding Firebase to your app" click on the code icon that is called "web" next to iOS and android. Enter a name for your web project, usually it should be called "my-project-web". No need for firebase hosting, so just hit continue. On the next slide, click continue to console. You have now created your first firebase app!

Step 2 - Setting up the auth

On the left sidebar, click authentication. On the header, click get started. We're gonna start with simple email/password auth for now. So click the first option box called email/password, then click enable, then hit save.
That's really all the configuration we need to do to set up auth on your app.

Step 3 - Implementing the auth on our app.

The first thing we need to do is get the firebase config code. To do that we can head to our firebase app. On the sidebar at the top near Project overview, click the settings (cog) icon and select Project Settings. Scroll down until you see SDK setup and configuration. Copy the code you see inside:

const firebaseConfig = {
  apiKey: '',
  etc...
}
Enter fullscreen mode Exit fullscreen mode

Create a config file inside your project folder, called firebase.js and copy this code in, replacing your config values accordingly:

import firebase from "firebase"

const config = {
  apiKey: "fill in with your real values",
  authDomain: "fill in with your real values",
  projectId: "fill in with your real values",
  storageBucket: "fill in with your real values",
  messagingSenderId: "fill in with your real values",
  appId: "fill in with your real values"
}
const firebaseApp = firebase.initializeApp(config)

const db = firebaseApp.firestore()
const auth = firebaseApp.auth()
const storage = firebaseApp.storage()

export { db, auth, storage } 

Enter fullscreen mode Exit fullscreen mode

Note: if you get an error with firebase, its probably some doc mistakes, to solve it just use this version of firebase npm: "firebase": "^8.9.1",

Login

Now in your project, usually in the folder called auth, you can create 2 files, one will be to log users in and the other to create their accounts. So we can name the first login.js and the second register.js. In the Login file you can copy this code in:

import { auth } from 'your/firebase.js/path' 
const handleLogin = () => { 
    auth.signInWithEmailAndPassword(email, password)
    .then(() => {
      authListener()
    })
    .catch(err => {
      switch(err.code) {
        //visit firebase for full list of error codes to display to user when their auth is incorrect.
      }  
    }) 
  }

const authListener = () => {
    auth.onAuthStateChanged(user => {
      if(user) {
        setMyUser(user) //if using react
      }
      else {
        setMyUser(null) //if using react
      }
    })
  }
Enter fullscreen mode Exit fullscreen mode

What happens here is when the user clicks on the login button that runs the function handleLogin(), we call the firebase function auth.signInWithEmailAndPassword, providing the user's entered email and password and then we call onAuthStateChanged() which will set a state that you can define to receive the firebase user's data. That covers Login! Let's take a look at registering a user.

Register

Inside our Register.js file let's copy the following code:

const handleSignup = () => {
      auth.createUserWithEmailAndPassword(email, password
      .then(() => {
        auth.onAuthStateChanged(user => {
          if(user) {
            user.updateProfile({
              displayName: `${firstName} ${lastName}`,
              photoURL: 'user-uploaded-img'
            })
            .then(() => { 
              navigate('/')
            })
            .catch(err => {
              console.log(err)
            })
          }
        })
      })
      .catch(err => {
        switch(err.code) {
          //switch error codes 
        }
      })
  }
Enter fullscreen mode Exit fullscreen mode

As you can see the Register file is very similar to the login, the only difference is we call a slightly different function from firebase's auth API called createUserWithEmailAndPassword(). This function also takes in an email and password as parameters and will create a user once both values are valid. We then update the user's displayName and photoURL with values which you can optionally ask the user for when they create their account.

Conclusion

That's all it takes. You now have a fully functioning auth system on your app. By making use of the 2 functions signInWithEmailAndPassword() and createUserWithEmailAndPassword() firebase auth provides us, we can authenticate users by creating their account and/or logging them in.

💖 💪 🙅 🚩
urielbitton
Uriel Bitton

Posted on May 10, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Firebase Miniseries 1: Auth
auth Firebase Miniseries 1: Auth

May 10, 2022