Authenticate users with Firebase

leandroandrade

Leandro Andrade

Posted on June 5, 2022

Authenticate users with Firebase

Every day a mount of applications need to authenticate users, maybe to do something or to access some feature. Anyway, authentication is an important part of any software and at moment is not a smart decision to create our own solution.

Exist a lot of solutions for authenticating users, some of those are free, and some are paid based on amount of users. A solution that I really like is Google Firebase Auth because is free, simple, has amazing documentation, and works pretty well.

Firebase provide for us a lot of type of authentication using email, Facebook, Google... I'd suggest to check the documentation for more details.

Our purpose is to show the simplest way how to authenticate and register users using just an email and passowrd.

First of all, we need to create a directory called sample-firebase-auth, enter into it and start a new Node.js project using:

npm init -y
Enter fullscreen mode Exit fullscreen mode

After that, just install firebase dependency:

npm i firebase
Enter fullscreen mode Exit fullscreen mode

Now, lets create a file called firebase.js:

touch firebase.js
Enter fullscreen mode Exit fullscreen mode

Our base project is configured. Now, we need to create a new project into firebase console. Let's show the images below to see show to do this. Lets go to firebase console https://console.firebase.google.com and click on Add project.
firebase-1

Type a name for your project and click on Continue
firebase-2

For our purpose, disable Google Analytics and click in Create project
firebase-3

Wait for a couple of seconds and our project will be created. Click on Continue
firebase-4

Now, we need to enable authentication using email. Let's click on Authentication
firebase-5

Select Sign-in method and click in Email/Password
firebase-6

Enable Email/Password and click in Save
firebase-7

Now, we need to get our firebase credentials. Let's go back to your main console page and click on Web App
firebase-8

Create an app nickname and click on Register app
firebase-9

After that, copy the content of firbeaseConfig variable. This is the credentials that we need.
firebase-10

We did all of the things that we needed. Let's go to the code and create our base structure to start our sample:

const firebase = require('firebase/app');
const {
    getAuth,
    signInWithEmailAndPassword,
    createUserWithEmailAndPassword,
} = require('firebase/auth');

const firebaseConfig = {
    apiKey: "YOU_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_SENDER_ID",
    appId: "YOUR_APP_ID"
  };

firebase.initializeApp(firebaseConfig);
Enter fullscreen mode Exit fullscreen mode

The firebase library segregates different types of functions into sub dependencies like firebase/app and firebase/auth.

After initializing our firebase app, we can build a function that creates a user and a password into firebase:

async function createUser(auth, email, password) {
    try {
        const signUp = await createUserWithEmailAndPassword(
            auth,
            email,
            password
        );
        console.log('Create user:', signUp.user.uid);
    } catch (err) {
        // auth/weak-password
        if (err.code === 'auth/email-already-in-use') {
            console.error('User already registered!');
        } else {
            console.error(err);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, we can run this function and see the uid created by firebase:

async function run() {
    const auth = getAuth();
    const email = 'firebase_auth@gmail.com';
    const password = '123456';

    await createUser(auth, email, password);
}
run().catch(console.error);
Enter fullscreen mode Exit fullscreen mode

We can check into firebase console and see our user created.
firebase-11

If you try to run this function more than one time with the same values, you will see a message User already registered!. Great, firebase validate this for us.

Now, lets create a function that authenticate our users:

async function login(auth, email, password) {
    try {
        const signIn = await signInWithEmailAndPassword(
            auth,
            email,
            password
        );
        console.log('Login user:', signIn.user.uid);
    } catch (err) {
        if (err.code === 'auth/wrong-password') {
            console.error('Invalid user or password!');
        } else {
            console.error(err);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, we can run this function and see the uid of the user previously created:

async function run() {
    const auth = getAuth();
    const email = 'firebase_auth@gmail.com';
    const password = '123456';
    await login(auth, email. password);
}
run().catch(console.error);
Enter fullscreen mode Exit fullscreen mode

If you change the password and send a new request, you will see the message Invalid user or password!.

Exist a lot of functions in Firebase like change password, signout, and some other things. Is good to see the documentation.

Here is the source code: https://github.com/leandroandrade/sample-firebase-auth

I hope that it will help you.

Thanks!!!

💖 💪 🙅 🚩
leandroandrade
Leandro Andrade

Posted on June 5, 2022

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

Sign up to receive the latest update from our blog.

Related