Development

Custom OTP Verification System that Works with Firebase


Create an awesome OTP and OTP validator using Firebase and firestore in 10 mins, and easily integrate it with your applicaiton.

Let’s assume you are using Firebase and all the features it supports. And now you have to deal with some kind of custom email verification to access some sort of document within the Firestore. Or let’s say you have a guest user that you need to sign in, and instead of storing them in the authentication, you are using Firestore for their entry, and you want to send a custom code to their email that they can input in the frontend and by which you can authenticate them. How would you do it?

Well, there are a lot of ways to handle it and I am going to share with you my way of doing it. It requires you to have Cloud function access.

So let's get started with code.

So assuming you have an email verification form, the user inputs an email. On its submission, the user will receive an email with the code, which the user will later input in the front-end and get verified.

The very first function we will require will be responsible for the sending of email and storing the session code in the Firestore.

Here is the example code. πŸ–₯

const sendVerificationCode = ({ email }) => {

// Randomwords is a code generator function that will generate a code of five charactors.
const code = RANDOMWORDS(5);

// Setting up the expiry for the code, so it will get deleted once the 5 mins has passed so nobuddy can exploit it. 
const sessionExpiry = moment().add('5', 'minute');

// Storing the code/session to the firstore with an expiry
admin.Firestore().collection('sessions').doc(code).set({code,sessionExpiry}).then((e) => {

// A custom function to trigger emails
sendEmail({ email, message: 'Your otp is ' + code, subject: 'Requested OTP' });

// Adding a task to our task scheduler to delete the session from the Firestore.
addATask({task: 'deleteSession',data: { id: code },performAt:sessionExpiry._d,}).then((e) => {}).catch(console.log);

});

};

Here, we are using our custom Firebase scheduler which will rerun a function every minute checking if there is a task that needs to be completed. And upon finding one, it will execute that task and move on. The function addATask is a part of the scheduler function. Kindly go through this article first to set up a corn-job-like scheduler in Firestore with Cloud functions.

Random words are a function the generates a code. πŸ–₯

function RANDOMWORDS(length) {

let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
for (let i = 0; i < length; i += 1) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}

return result;

}

SendEmail is a custom function that you can have that is used to send an email to the person with code. I used a serverless Node.js Express app that sends an email to the email provided.

Now, we have a send an email to the person with the code and have the OTP stored in our DB. The next step is to validate the OTP and upon validation, deleting the code as well. πŸ–₯

const ValidateSession = async ({ code }) => {

// getting the code from the db
const document = await admin.Firestore().collection('sessions').doc(code).get();

// check for the existence
if (document.exists) {

// If Exist, deleting the code session.
admin.Firestore().collection('sessions').doc(code).delete();

return true;
}

return false;
};

We can use this function to validate the code/session/OTP and upon validation, we can authenticate the user.

That is it, folks. Let me know the better approach for it, I will always welcome feedback.

β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€”

Looking for a freelancer? Hire me via Fiverr.

β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€” β€”

Raja Osama

I Describe Myself as a Polyglot ~ Tech Agnostic ~ Rockstar Software Engineer. I Specialise in Javascript-based tech stack to create fascinating applications.

I am also open for freelance work, and in-case you want to hire me, you can contact me at rajaosama.me@gmail.com or contact@rajaosama.me