Провайдер Facebook не аутентифицирует пользователей в моем приложении ioni c - использует angularfire - PullRequest
0 голосов
/ 03 апреля 2020

Я пытаюсь ввести (социальный и электронный адрес) логин в моем приложении ioni c.

Это работало хорошо для email-пропуска. Когда я попытался добавить Google и Facebook, я столкнулся с множеством проблем, а затем очень грязный код. Теперь мой код работает для googleauthentication, но для facebook приложение перенаправляет, но возвращает результат {user: null}, и ничего не меняется.

В чем ошибка? Почему аутентификация facebook не меняет this.afAuth.authState?

Функциональность реализована в моем файле auth.service.ts.

Функция для входа в Facebook выглядит так:

  loginWithFacebook() {
    this.store.dispatch(new UIActions.StartLoading());
    alert('facebook login');
    try {
      let provider = new auth.FacebookAuthProvider();
      console.log(provider);
      const credential = this.afAuth.auth.signInWithRedirect(provider);
      console.log('accomplished sign in with redirect');
    } catch (error) {
        console.log(error);
        alert(error);
    }
  }

LoginWithGoogle (работает, как и ожидалось):

webGoogleLogin() {
  try {
      const provider = new firebase.auth.GoogleAuthProvider();
      console.log(provider);
      const credential = this.afAuth.auth.signInWithRedirect(provider);
      console.log('accomplished sign in with redirect');
  } catch (error) {
    console.log(error);
    alert(error);
  }
}

Я слушаю изменения аутентификации в initAthListener (), который запускается при инициализации приложения (это работало, как и ожидалось, при входе по электронной почте - выход из системы):

initAuthListener() {
    // this.store.dispatch(new UIActions.StartLoading());

    this.afAuth.authState.subscribe(user => {
      // if( user && !user.emailVerified) {
      //   this.store.dispatch(new UIActions.StopLoading());
      //   this.alertService.presentToast(this.translateService.instant("Auth.PLEASE_VALIDATE_YOUR_EMAIL_ADDRESS"), 3000);
      // }
      console.log(user);
      alert(user);
      if (user) {
        if(user.emailVerified) {
        this.isAuthenticated = true;
        this.store.dispatch(new AuthActions.SetAuthenticated());
        this.afStore.collection('profiles').doc<FullUserProfile>(user.uid).valueChanges().pipe(take(1)).subscribe(
          (profile: FullUserProfile) => {
            if (profile != null) {
                this.store.dispatch(new AuthActions.SetUserProfile(profile));
                // this.functionsGeneralDataService.initialize(profile);
                this.generalDataService.initialize(profile);
                this.store.dispatch(new UIActions.StopLoading());
                // this.router.navigate(['/groups']);
                this.goToMainPage();
            } else {
              return;
            }
          }
        );
      }
     } else {
        this.isAuthenticated = false;
        this.generalDataService.unsubscribeFromAll();
        this.store.dispatch(new AuthActions.SetUnauthenticated());
        this.store.dispatch(new AuthActions.RemoveUserProfile());
        this.store.dispatch(new GroupsActions.ClearState());

        // this.router.navigate(['/login']);
      }
      this.store.dispatch(new UIActions.StopLoading());
    });
    // this.listenToRedirectResults();
  }

Я попытался добавить следующие функции в конце inmitAuthListener (), но без решения проблемы:

  listenToRedirectResults() {
    firebase.auth().getRedirectResult().then((result) => {
        console.log(result);
        console.log(firebase.auth().currentUser);
        alert("THIS IS RESULT");
          this.store.dispatch(new UIActions.StartLoading());
          if (result.credential) {
            alert('result.credentials is not null');
            var token = result.user.getIdToken();
            var user = result.user;
    // if(result == null || result.user == null) {
    //   alert('result or user null');
    //   this.isAuthenticated = false;
    //   this.generalDataService.unsubscribeFromAll();
    //   this.store.dispatch(new AuthActions.SetUnauthenticated());
    //   this.store.dispatch(new AuthActions.RemoveUserProfile());
    //   this.store.dispatch(new GroupsActions.ClearState());
    // }
            alert('will get data');
            this.store.dispatch(new AuthActions.SetAuthenticated());
            this.afStore.collection('profiles').doc(user.uid).valueChanges().pipe(take(1)).subscribe(
              (profile: FullUserProfile) => {
                this.store.dispatch(new UIActions.StartLoading());
                this.isAuthenticated = true;
                if (profile != null) {
                    this.store.dispatch(new AuthActions.SetUserProfile(profile));
                    // this.functionsGeneralDataService.initialize(profile);
                    this.generalDataService.initialize(profile);
                    this.store.dispatch(new UIActions.StopLoading());
                    this.goToMainPage();
                } else {
                  let profile = {} as FullUserProfile;
                  profile.id = user.uid;
                  profile.email = user.email;
                  profile.name = user.displayName;
                  profile.image = { name: '', url: user.photoURL}
                  profile.type = 0;
                  profile.numberOfGroupsAllowed = 2;
                  this.afStore.collection('profiles').doc(user.uid).set(profile);
                  this.store.dispatch(new AuthActions.SetUserProfile(profile));
                    // this.functionsGeneralDataService.initialize(profile);
                    this.generalDataService.initialize(profile);
                    this.store.dispatch(new UIActions.StopLoading());
                    this.goToMainPage();
                    // this.router.navigate(['/groups']);
                }
              }
            );
            // this.router.navigate(['groups'])
          } else {
            alert('no creadential');
          }
        })
        .catch(function(error) {
          console.log(error.message);
          this.store.dispatch(new UIActions.StopLoading());
          this.alertService.presentToast(error.message);
        });
  }

Примечание: если пользователь удален из пользователи консоли firebase, и попытались войти через Facebook, затем туда добавили пользователя, но без изменений в моем приложении.

Извините за мой грязный код, я много чистил, прежде чем задать вопрос .. Вчера , перед добавлением аутентификации google, аутентификация facebook работала, но выход не был.

Извините, но я новичок в ioni c framework.

1 Ответ

0 голосов
/ 03 апреля 2020

Ошибка: я проверяю, подтвержден ли адрес электронной почты для учетной записи Facebook, где адрес электронной почты не подтвержден. Я реструктурировал свой код.

...