Объедините аутентификацию электронной почты и телефона в Firebase с Angular 7 - PullRequest
0 голосов
/ 03 июля 2019

Я хочу объединить идентификаторы пользователей в один для идентификации пользователя по электронной почте и аутентификации по телефону в firebase.Оба метода работают, и телефон связывается с пользователем, когда регистрируется через базу данных Firebase.Я знаю, что существует метод SignInWithCredential (), который решает эту проблему с помощью идентификаторов верификации, но я не могу представить решение в своем коде с помощью Angular.Вот несколько скриншотов моего кода, спасибо.

Пользователи Firebase: firebase users

Методы SigIn на auth.service.ts

  loginUser(email: string, password: string): Promise<any> {
    return firebase.auth().signInWithEmailAndPassword(email, password);
  }

  verifySMS(phoneNumberString: string, appVerifier: firebase.auth.RecaptchaVerifier): Promise<any> {
    return firebase.auth().signInWithPhoneNumber(phoneNumberString, appVerifier);
  };

  signupUser(usuario: user): Promise<any> {
    return firebase
      .auth()
      .createUserWithEmailAndPassword(usuario.email, usuario.password)
      .then(newUser => {

        newUser.sendEmailVerification()

        if (usuario.email = 'admin@mail.com') {
          this.afDB.database.ref('userProfile/' + newUser.uid).set({
            'name' : usuario.fullName,
            'phone' : usuario.phone,
            'profile' : this.adminProfile,
            'userSettings' : this.userSettings
          });
        } else {
          this.afDB.database.ref('userProfile/' + newUser.uid).set({
            'name' : usuario.fullName,
            'phone' : usuario.phone,
            'profile' : this.defaultProfile,
            'userSettings' : this.userSettings
          });
        } 

      })
      .catch(error => {
        console.error(error);
        throw new Error(error);
      });
  }

Окончательный метод входа Электронная почта, пароль, телефон

sendVerifySMS() {

    var appVerifier = this.windowRef.recaptchaVerifier;

    this._profile.getUserProfile().on('value', profile => {

      this.phone = profile.val().phone;

      firebase.auth().signInWithPhoneNumber(this.phone, appVerifier).then(res => {

        console.log('mensaje enviado');

        this.windowRef.confirmationResult = res;
        console.log(this.windowRef.confirmationResult);
        this.verificationID = res.verificationId;

    })
    .catch( error => console.log(error) );

    })

 }

  logInPhone(phoneCodeForm : FormGroup) {

    let SMScode : string = phoneCodeForm.value.code;

    //this._auth.verifyCodeSMS(SMScode);

    this.windowRef.confirmationResult.confirm(SMScode).then(result => {

      console.log(result);

      const signInCredential = firebase.auth.PhoneAuthProvider.credential(this.verificationID, SMScode)

        var prevUser = this._profile.currentUser;
        // Sign in user with another account
        firebase.auth().signInWithCredential(signInCredential).then(function(user) {
          console.log("Sign In Success", user);
          var currentUser = user;
          // Merge prevUser and currentUser data stored in Firebase.
          // Note: How you handle this is specific to your application

          // After data is migrated delete the duplicate user
          return user.delete().then(function() {
            // Link the OAuth Credential to original account
            return prevUser.linkWithCredential(signInCredential);

          }).then(function() {
            // Sign in with the newly linked credential
            return firebase.auth().signInWithCredential(signInCredential);
          });

        }).catch(function(error) {
          console.log("Sign In Error", error);

          this._snackBar.open(error.message, 'OK', {
            duration: 3000,
          });

        });

      this._auth.afDB.database.ref('userProfile/' + this._profile.currentUser.uid).update({
        'lastLogin' : new Date()
      });

      this._router.navigateByUrl('apps/dashboards/analytics');

    })
      .catch( error => this._snackBar.open(error.message, 'OK', {
          duration: 3000,
        })
      );
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...