To add Firebase OTP sign-in to the existing login function, you can use the Firebase Authentication SDK for PHP. Here's an example implementation:
use Kreait\Firebase\Factory;
use Kreait\Firebase\Auth;
public function login(Request $request)
{
$user_id = $request['phone'];
$validator = Validator::make($request->all(), [
'phone' => 'required',
'password' => 'required|min:6'
]);
if ($validator->fails()) {
return response()->json(['errors' => Helpers::error_processor($validator)], 403);
}
// Initialize Firebase Authentication
$factory = (new Factory)->withServiceAccount('/path/to/serviceAccountKey.json');
$auth = $factory->createAuth();
// Send OTP to user's phone number
$verificationId = $auth->verifyPhoneNumber($user_id)->verificationId;
// Save verification ID to user's record
$user = Leader::where(['phone' => $user_id])->first();
$user->verification_id = $verificationId;
$user->save();
return response()->json(['verification_id' => $verificationId], 200);
}
This code sends an OTP to the user's phone number using Firebase Authentication SDK's verifyPhoneNumber method, and saves the verification ID to the user's record in the database. You can then use this verification ID to verify the OTP entered by the user.
To verify the OTP, you can add another function that takes the verification ID and OTP as input, and returns a JWT token if the OTP is valid. Here's an example implementation:
public function verifyOtp(Request $request)
{
$validator = Validator::make($request->all(), [
'verification_id' => 'required',
'otp' => 'required'
]);
if ($validator->fails()) {
return response()->json(['errors' => Helpers::error_processor($validator)], 403);
}
// Initialize Firebase Authentication
$factory = (new Factory)->withServiceAccount('/path/to/serviceAccountKey.json');
$auth = $factory->createAuth();
// Verify OTP
$verificationId = $request->verification_id;
$otp = $request->otp;
$credential = $auth->credential($verificationId, $otp);
$user = $auth->signInWithCredential($credential);
// Get user record from database
$user_id = $user->phoneNumber;
$user = Leader::where(['phone' => $user_id])->first();
// Generate JWT token
$user->temporary_token = Str::random(40);
$user->save();
$token = $user->createToken('userAuth')->accessToken;
return response()->json(['token' => $token], 200);
}
This code verifies the OTP entered by the user using Firebase Authentication SDK's credential method, and signs in the user using signInWithCredential method. It then retrieves the user's record from the database using the phone number, generates a JWT token, and returns it to the client.
Note that you need to install the Firebase Authentication SDK for PHP using Composer, and provide the path to your Firebase service account key file in the withServiceAccount method.