Обновление Flutter Firebase_Auth прерывает авторизацию телефона OTP на iOS (все версии) - PullRequest
0 голосов
/ 26 февраля 2020

Хорошо, поэтому я создаю приложение iOS во флаттере, используя firebase_auth, и у меня возникла небольшая ошибка.

Обычно с firebase_auth, если вы уже авторизовались на устройстве, оно должно просто пройти через firebase_auth и в остальную часть программы. Моя программа не делала этого. Он будет запрашивать проверку текстовых сообщений каждый раз, независимо от того.

Так что мой первый инстинкт относительно того, как решить эту проблему, состоял в том, чтобы проверить, была ли у меня последняя версия firebase_auth и другие зависимости. Проверено, что есть некоторые, которые устарели, и поэтому их обновили. (Переход от 15.3 до 15.4 firebase_auth; наряду с firebase_core 4.3 + 1 - 4.4; и несколько других, которые не влияют на это)

ЕДИНСТВЕННЫЕ изменения были в моем pubspe c .yaml и всех внезапно, ни один из моего кода больше не работает. Firebase никогда не отправляет текст. Просто на самом деле завершение авторизации в фоновом режиме, я добавил еще несколько операторов печати, чтобы знать, где в коде что-то происходит, но ни одно из этих сообщений не распечатывается.

Я пытался проверить это на и iphone 11 pro max, работающий ios 13.4, и iphone 5e, работающий 13.3.1, и одна и та же проблема возникает на обоих.

Так как это произошло из-за обновлений pubspe c .yaml, я попытался отменить эти изменения, (спасибо GitHub), но это не повлияло на код, и firebase по-прежнему больше не отправляет текст на телефон, без сообщения об ошибке или сообщения печати на экран отладки. , А идеи?

Код следующий:

class LoginPage extends StatelessWidget { // Base Scaffold for Login Page
  @override
  Widget build(BuildContext context) {
    return new CupertinoPageScaffold(
      navigationBar: CupertinoNavigationBar(
        middle: Text('Verification'),
      ),
      child: new _PhoneLoginSection(),
    );
  }
}

class _PhoneLoginSection extends StatefulWidget{

  @override
  State<StatefulWidget> createState() => _PhoneLoginSectionState();
}

class _PhoneLoginSectionState extends State<_PhoneLoginSection>{

  final TextEditingController _phoneNumberController = TextEditingController();
  final FirebaseAuth _auth = FirebaseAuth.instance;

//  Firebase Authorization request
  Future<void> verifyPhone(context) async {
    try {
      final credential = PhoneAuthProvider.getCredential(
        verificationId: this.verificationId, 
        smsCode: this.smsCode, 
      );
      print('Already Authorized.');
      final FirebaseUser user = (await _auth.signInWithCredential(credential)).user;
      final FirebaseUser currentUser = await _auth.currentUser();
      assert(user.uid == currentUser.uid);
      IdTokenResult firebaseIdToken = await user.getIdToken(); 
      setInfo(this.phoneNumber, firebaseIdToken);  
      toMap(context);
    } catch (e) {
        print(e);
        catchError(e, context);
    }
  } // End of Authorization request


   // SMS Verification Screen Widget
    Future<bool> smsCodeDialog(BuildContext context) {    
        return showCupertinoDialog(    
            context: context,    
            builder: (BuildContext context) {    
                return new AlertDialog(    
                backgroundColor: currentTheme.primaryColor,  
                title: Text('Enter SMS Code', style: TextStyle(color: currentTheme.textTheme.textStyle.color),),    
                content: Column(mainAxisAlignment: MainAxisAlignment.end, children: [
                  Divider(),    
                  CupertinoTextField(    
                      placeholder: '123456',
                      autofocus: true,                           
                      maxLength: 6,
                      maxLengthEnforced: true,
                      textInputAction: TextInputAction.done,
                      keyboardType: TextInputType.number,
                      inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
                      onSubmitted: (value) {
                        verifySms(context, value); 
                      },  
                      controller: _phoneNumberController, 
                    ), 
                  Divider(),
                  (errorMessage != ''    
                      ? Text(    
                          errorMessage,    
                          style: TextStyle(color: Colors.red),    
                          )    
                      : Container())    
                ]),   
                contentPadding: EdgeInsets.all(16),    
                actions: <Widget>[    
                    FlatButton(    
                    child: Text('Submit', 
                      style: TextStyle(color: currentTheme.textTheme.textStyle.color), ),    
                    onPressed: () {   
                        verifySms(context, _phoneNumberController.text); 
                    },    
                    )    
                ],    
                );    
        });    
    }
    // END of SMS Verification Screen Widget


// Method to call validation of phone number and credentials.
  void openCodePage(context) async {
    if (!debugging) {
      setState((){codeSent = true;});
      final PhoneCodeSent smsCodeSent = (verID, [int forceResendingToken]) async {
        this.verificationId = verID;
        smsCodeDialog(context).then((value) {});
      };

    // Complete Phone Authorization, and generate ID Token
      final PhoneVerificationCompleted verificationComplete = (AuthCredential credential) async {
      validationComplete = true;
      print('Authorized only through SMS.');
      _auth.signInWithCredential(credential);
      FirebaseUser user = await _auth.currentUser();
      IdTokenResult firebaseIdToken = await user.getIdToken(); 
      setInfo(this.phoneNumber, firebaseIdToken);  
      toMap(context);
    };

    // Error handling.  Method required for Firebase Phone Auth.
    final PhoneVerificationFailed verificationFailed = (AuthException exception) {
      print('Phone Auth Verification Failed: ${exception.message}');
      setState((){
        codeSent = false;
      });
    };
    // End of Error Handling

  // Automatically Sign-In after timeout.  Method required for Firebase Phone Auth.
  final PhoneCodeAutoRetrievalTimeout timeout = (String verID) {
    setState((){
    });
  print('Code Auto Retreival Timed Out: ${this.verificationId}');
  };

  // Actual Authorization request.  Method required for Firebase Phone Auth.
  try {
      await _auth.verifyPhoneNumber(
        phoneNumber: this.phoneNumber, 
        timeout: const Duration(seconds: 20),
        codeAutoRetrievalTimeout: timeout,
        verificationCompleted: verificationComplete,
        verificationFailed: verificationFailed,
        codeSent: smsCodeSent,
      );
  } catch(e) {
    print('Verify Phone Number Error: $e');
  } 
    }
    else {
      toMap(context);
    }
  } // END openCodePage Function



// Error Handling Function for validation errors.  
  catchError(PlatformException error, context) {
    print(error);
    switch (error.code) {
      case 'ERROR_INVALID_VERIFICATION_CODE':
      FocusScope.of(context).requestFocus(new FocusNode());
      setState(() {
        errorMessage = 'Invalid Code';
      });
      Navigator.of(context).pop();
      smsCodeDialog(context).then((value) {

      });
      break;
      default:
      setState(() {
        errorMessage = error.message;
      });
      break;
    }
  }
  //End Error Handling Function

// User Phone Number Input Cleaning
void validatePhone(phoneNum){
  if (phoneNum.length < 10){
    return;
  } else if (phoneNum.length == 11) {
    this.phoneNumber = '+' + phoneNum;
    setNumber(phoneNum.substring(1));
  } else {
    this.phoneNumber = '+1' + phoneNum;
    setNumber(phoneNum);
  }
  _phoneNumberController.text = '';
}
// End User Phone Number Input Cleaning


// User SMS Input Cleaning
void verifySms(context, code) async {
  if (code.length < 6){
    return;
  }
  this.smsCode = code;
  verifyPhone(context);
}
// End SMS Input Cleaning


// Actual Transition Code.  Go to Map
void toMap(context){
  setHistoryList();
  Navigator.of(context).pushAndRemoveUntil(
      CupertinoPageRoute(
        maintainState: false,
        fullscreenDialog: false,
        builder: (context) =>
          MainAppPage()),
        (Route<dynamic> route) => false
    );

  }  // End of Transition Code

// Build base context widget, and accept user input.
  @override
  Widget build(BuildContext context){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          child: const Text('Enter your phone number:', 
            style: TextStyle(color: null), ),
          padding: const EdgeInsets.all(16),

        ),
        CupertinoTextField(
              placeholder: '(555) 555-5555',
              autofocus: true,                            // DO NOT REMOVE, uncomment out in production environment
              clearButtonMode: OverlayVisibilityMode.editing,
              maxLength: 11,
              maxLengthEnforced: true,
              textInputAction: TextInputAction.done,
              keyboardType: TextInputType.number,
              inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
              onSubmitted: (phoneNum){
                validatePhone(phoneNum);
                if (this.phoneNumber != null) {
                  openCodePage(context);
                }
              },
              controller: _phoneNumberController,
            ),
        Container(
          child: CupertinoButton(
            color: currentTheme.primaryContrastingColor,
            pressedOpacity: 0.7,
            child: Text('Get Code', style: TextStyle(color: currentTheme.textTheme.textStyle.color),
            ),
            onPressed: (){
              validatePhone(_phoneNumberController.text);
              if (this.phoneNumber != null) {
                openCodePage(context);
              }
            },
          ),
          alignment: Alignment.bottomLeft,
          padding: const EdgeInsets.all(16),
        ),
      ],
    );
  }
}
...