How to Input Phone Number from User Using Google Signin (SignInWithPopUp) of firebase?

 

import React from 'react';
import { FcGoogle } from 'react-icons/fc';
import useAuthContext from '../../Hooks/useAuthContext';
import useAxiosPublic from '../../Hooks/useAxiosPublic';
import Swal from 'sweetalert2';
import { useNavigate } from 'react-router-dom';

const SignInWithGoogle = () => {

    const navigate = useNavigate();
    const { signInWithGoogle, setLoading, logoutUser } = useAuthContext();
    const axiosPublic = useAxiosPublic();

    const handleGoogleSignIn = () => {
        // write your further code;
        signInWithGoogle()
            .then((result) => {
                const user = result.user;

                // Extract user details
                const userData = {
                    displayName: user?.displayName,
                    email: user?.email,
                    role: 'user',
                    date: new Date().toLocaleString("en-US", { timeZone: "Asia/Dhaka" }),
                    phone: user?.phoneNumber || "", // Google does not provide phone by default
                };

                // Check if the user already has a phone number in your database (MongoDB or Firestore)
                axiosPublic.get(`/check-user-phone?email=${user.email}`)
                    .then(res => {
                        const existingUser = res.data;


                        if (!existingUser || !existingUser.phone) {
                            // Ask the user to enter their phone number
                            Swal.fire({
                                title: "Enter Your Phone Number",
                                input: "text",
                                inputPlaceholder: "Your phone number",
                                showCancelButton: true,
                                confirmButtonText: "Save",
                                preConfirm: (phone) => {
                                    // Check if phone is a number and matches the required pattern
                                    const phonePattern = /^(019|017|013|014|015|018)\d{8}$/;

                                    if (!phone.match(/^\d+$/)) {
                                        Swal.showValidationMessage("Phone number must contain only numbers.");
                                        return false;
                                    }

                                    if (!phone.match(phonePattern)) {
                                        Swal.showValidationMessage(
                                            "Invalid phone number! It must start with 019, 017, 013, 014, 015, or 018 and be 11 digits long."
                                        );
                                        return false;
                                    }

                                    return phone;
                                }
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    userData.phone = result.value;

                                    // Save user data to MongoDB or Firestore
                                    axiosPublic.post('/users', userData)
                                        .then(res => {
                                            if (res.data.insertedId) {
                                                Swal.fire({
                                                    position: "top-end",
                                                    icon: "success",
                                                    title: "Logged in Successfully",
                                                    showConfirmButton: false,
                                                    timer: 1500
                                                });
                                                navigate('/')

                                            }
                                        }).catch(err => {
                                            console.log(err);
                                        })


                                } else {
                                    logoutUser();


                                }
                            });
                        } else {
                            Swal.fire({
                                position: "top-end",
                                icon: "success",
                                title: "Logged in Successfully",
                                showConfirmButton: false,
                                timer: 1500
                            });
                            navigate('/')
                        }



                    })


            }).catch(err => {
                console.log(err);
            })
    }
    return (
        <div>
            <div className='m-3'>
                <button className="google-signin-btn m-auto" onClick={handleGoogleSignIn}>
                    <FcGoogle size={24} className="google-icon" />
                    <span className="google-signin-text">Sign in with Google</span>
                </button>
            </div>
        </div>
    );
};

export default SignInWithGoogle;

Post a Comment

Previous Post Next Post