Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

javascript - How to Use Firebase Phone Authentication without recaptcha in React Native

I want to use firebase phone verification without recaptcha in react native. Below is my code. The code is working properly. But I Don't want to use recaptcha. I try deleting it but it gives error. I am new to react native. Please give proper solution of the following problem. My code is given Below Check It and give solution. Thank You

import * as React from 'react';
import { Text, View, StyleSheet, TextInput,Image,TouchableOpacity,ActivityIndicator,Alert } from 'react-native';
import * as FirebaseRecaptcha from "expo-firebase-recaptcha";
import * as firebase from "firebase";

// PROVIDE VALID FIREBASE CONFIG HERE
// https://firebase.google.com/docs/web/setup
const FIREBASE_CONFIG: any = {
  
};

try {
  if (FIREBASE_CONFIG.apiKey) {
    firebase.initializeApp(FIREBASE_CONFIG);
  }
} catch (err) {
  // ignore app already initialized error on snack
}

export default function App() {
  const recaptchaVerifier = React.useRef(null);
  const verificationCodeTextInput = React.useRef(null);
  const [phoneNumber, setPhoneNumber] = React.useState("");
  const [verificationId, setVerificationId] = React.useState("");
  const [verifyError, setVerifyError] = React.useState<Error>();
  const [verifyInProgress, setVerifyInProgress] = React.useState(false);
  const [verificationCode, setVerificationCode] = React.useState("");
  const [confirmError, setConfirmError] = React.useState<Error>();
  const [confirmInProgress, setConfirmInProgress] = React.useState(false);
  const isConfigValid = !!FIREBASE_CONFIG.apiKey;
  return (
    <View style={styles.container}>
         <FirebaseRecaptcha.FirebaseRecaptchaVerifierModal
          ref={recaptchaVerifier}
          firebaseConfig={FIREBASE_CONFIG}
        />
      <View style={styles.first}>
        <Text style={{color:'white',fontSize:25,fontWeight:'bold'}}>Welcome</Text>
      </View>
      <View style={styles.second}>
        <Text style={{paddingVertical:5}}>Phone No</Text>
        <View style={styles.fileds}>
            <Image style={styles.logo} source={require('./assets/user.png')} />
            <TextInput style={styles.input}
             autoFocus={isConfigValid}
             autoCompleteType="tel"
             keyboardType="phone-pad"
             textContentType="telephoneNumber"
             editable={!verificationId}
             onChangeText={(phoneNumber: string) => setPhoneNumber(phoneNumber)}
            />
        </View>
        <TouchableOpacity style={styles.button} 
        disabled={!phoneNumber}
        onPress={async () => {
          const phoneProvider = new firebase.auth.PhoneAuthProvider();
          try {
            setVerifyError(undefined);
            setVerifyInProgress(true);
            setVerificationId("");
            const verificationId = await phoneProvider.verifyPhoneNumber(
              phoneNumber,
              recaptchaVerifier.current
            );
            setVerifyInProgress(false);
            setVerificationId(verificationId);
            verificationCodeTextInput.current?.focus();
          } catch (err) {
            setVerifyError(err);
            setVerifyInProgress(false);
          }
        }}
        >
          <Text style={{alignSelf:'center',color:'white'}}>{`${verificationId ? "Resend" : "Send"} OTP`}</Text>
        </TouchableOpacity>
        {verifyError && (
          <Text style={styles.error}>{`Error: ${verifyError.message}`}</Text>
        )}
        {verifyInProgress && <ActivityIndicator style={styles.loader} />}
        {verificationId ? (
          <Text style={styles.success}>
            A verification code has been sent to your phone
          </Text>
        ) : undefined}
        <Text style={{paddingTop:25,paddingBottom:5}}>OTP</Text>
        <View style={styles.fileds}>
          <Image style={styles.logo} source={require('./assets/password.png')} />
          <TextInput
          ref={verificationCodeTextInput}
          style={styles.input}
          editable={!!verificationId}
          placeholder="123456"
          onChangeText={(verificationCode: string) =>
            setVerificationCode(verificationCode)
          }
        />
        </View>
        <TouchableOpacity style={styles.button} 
          disabled={!verificationCode}
          onPress={async () => {
            try {
              setConfirmError(undefined);
              setConfirmInProgress(true);
              const credential = firebase.auth.PhoneAuthProvider.credential(
                verificationId,
                verificationCode
              );
              const authResult = await firebase
                .auth()
                .signInWithCredential(credential);
              setConfirmInProgress(false);
              setVerificationId("");
              setVerificationCode("");
              verificationCodeTextInput.current?.clear();
              Alert.alert("Phone authentication successful!");
            } catch (err) {
              setConfirmError(err);
              setConfirmInProgress(false);
            }
          }}>
          <Text style={{alignSelf:'center',color:'white'}}>Confirm OTP</Text>
        </TouchableOpacity>
        {confirmError && (
          <Text style={styles.error}>{`Error: ${confirmError.message}`}</Text>
        )}
        {confirmInProgress && <ActivityIndicator style={styles.loader} />}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  first: {
    height:'30%',
    width:'100%',
    backgroundColor:'rgb(26, 47, 94)',
    justifyContent:'center',
    padding:20
  },
  second:{
    paddingVertical:30,
    paddingHorizontal:20,
    borderTopLeftRadius:15,
    borderTopRightRadius:15,
    marginTop:-10,
    backgroundColor:'white'
  },
  fileds:{
    flexDirection:'row',
    borderBottomColor:'grey',
    borderBottomWidth:1,
    padding:5,
  },
  logo:{
    height:20,
    width:20
  },
  button:{
    backgroundColor:'rgb(72, 126, 241)',
    padding:10,
    borderRadius:10,
    marginVertical:15
  },
  buttontwo:{
    borderColor:'rgb(72, 126, 241)',
    borderWidth:1,
    padding:10,
    borderRadius:10,
    marginVertical:15
  },
  input:{
    width:'80%'
  },
  error: {
    marginTop: 10,
    fontWeight: "bold",
    color: "red",
  },
  success: {
    marginTop: 10,
    fontWeight: "bold",
    color: "blue",
  },
  loader: {
    marginTop: 10,
  },
});

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...