Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phone Number with Password Authentication using Firebase

In my current project, I'm registering a user with email ID and then in profile section when the user updates a phone number, I authenticate that phone number & using PhoneAuthCredetials I'm merging both Authentication methods for the same user.

Now the real pain is, My user can sign in with Phone number or Email ID but for Email ID user has to enter password & for phone number it'll need OTP. (I Tried that, Entered phone number & password for signInWithEmailAndPassword() but not worked)

I wanted the user to log in with email or phone with a password. the way Flipkart does.

Is there any way I can manage that?

like image 810
akshay bhange Avatar asked Jun 20 '19 07:06

akshay bhange


1 Answers

Create cloud function with following code

const functions = require('firebase-functions');
const firebase = require('firebase');
const admin = require('firebase-admin');

admin.initializeApp();
firebase.initializeApp({
    //Add config for web-app here
    //Required because Admin SDK doesn't include signInWithEmailAndPassword method
});

exports.signInWithPhoneAndPassword = functions.https.onCall(async (data, context) => {
    const phoneNumber = data.phone;
    if (phoneNumber === undefined) {
        return {'s':400,'m':'Bad argument: no phone number'};
    }
    const user = await admin.auth().getUserByPhoneNumber(phoneNumber);
    const pass = data.password;
    try {
        await firebase.auth().signInWithEmailAndPassword(user.email, pass);
    } catch (e) {
        return {'s':400,'m':'Wrong password'};
    }
    const token = await admin.auth().createCustomToken(user.uid, {'devClaim':true}); //developer claims, optional param
    return {'s':200,'t':token};
});

On client side call this function, and if it returns object with "s"==200 use token with signInWithCustomToken (Calling a Cloud Function from Android through Firebase)

like image 92
Dima Rostopira Avatar answered Oct 03 '22 06:10

Dima Rostopira