Authenticate users with Firebase
Leandro Andrade
Posted on June 5, 2022
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
After that, just install firebase dependency:
npm i firebase
Now, lets create a file called firebase.js:
touch firebase.js
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
.
Type a name for your project and click on Continue
For our purpose, disable Google Analytics and click in Create project
Wait for a couple of seconds and our project will be created. Click on Continue
Now, we need to enable authentication using email. Let's click on Authentication
Select Sign-in method
and click in Email/Password
Enable Email/Password
and click in Save
Now, we need to get our firebase credentials. Let's go back to your main console page and click on Web App
Create an app nickname and click on Register app
After that, copy the content of firbeaseConfig
variable. This is the credentials that we need.
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);
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);
}
}
}
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);
We can check into firebase console and see our user created.
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);
}
}
}
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);
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!!!
Posted on June 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.