Firebase Auth пароль неверный после входа по электронной почте - PullRequest
0 голосов
/ 04 сентября 2018

Я создаю приложение Angular и использую проверку подлинности электронной почты Firebase.
Это работало отлично, пока я не начал использовать ссылку электронной почты для подтверждения учетной записи.

После регистрации я создаю пользователя и затем отправляю ему ссылку для входа на его почту.
Я попробовал это, я зарегистрировался, получил ссылку, нажал на нее, и он вошел в систему все в порядке.

Однако, как только я выйду из системы, это не даст мне войти в систему с моим паролем, сказав The password is invalid or the user does not have a password.
Мне нужно сбросить пароль и только тогда он работает.

Это мой код:

signup(email: string, password: string, firstname: string, lastname, nickname: string, address: string) {
this.firebaseAuth
  .auth
  .createUserWithEmailAndPassword(email, password)
  .then(value => {
    this.u = value.user;
    this.u.updateProfile({ displayName: nickname, photoURL: null });
    this.firebaseAuth.auth.updateCurrentUser(this.u);
    var actionCodeSettings = {
      // URL you want to redirect back to. The domain (www.example.com) for this
      // URL must be whitelisted in the Firebase Console.
      //url: 'http://localhost:4200/finishSignUp',
      url: 'https://mybay-990af.firebaseapp.com/finishSignUp',
      // This must be true.
      handleCodeInApp: true,
    };

    this.firebaseAuth.auth.sendSignInLinkToEmail(email, actionCodeSettings)
      .then(function () {
        // The link was successfully sent. Inform the user.
        // Save the email locally so you don't need to ask the user for it again
        // if they open the link on the same device.
        window.localStorage.setItem('emailForSignIn', email);
      })
      .catch(function (error) {
        // Some error occurred, you can inspect the code: error.code
      });
    console.log('Success!', value);
  })
  .catch(err => {
    console.log('Something went wrong:', err.message);
  });
 }

loginWithEmailLink() {
// Confirm the link is a sign-in with email link.
if (this.firebaseAuth
  .auth.isSignInWithEmailLink(window.location.href)) {
  // Additional state parameters can also be passed via URL.
  // This can be used to continue the user's intended action before triggering
  // the sign-in operation.
  // Get the email if available. This should be available if the user completes
  // the flow on the same device where they started it.

  var email = window.localStorage.getItem('emailForSignIn');
  if (!email) {
    // User opened the link on a different device. To prevent session fixation
    // attacks, ask the user to provide the associated email again. For example:
    email = window.prompt('Please provide your email for confirmation');
  }
  // The client SDK will parse the code from the link for you.
  this.firebaseAuth
    .auth.signInWithEmailLink(email, window.location.href)
    .then((result) => {
      // Clear email from storage.
      window.localStorage.removeItem('emailForSignIn');
      // You can access the new user via result.user
      // Additional user info profile not available via:
      // result.additionalUserInfo.profile == null
      // You can check if the user is new or existing:
      // result.additionalUserInfo.isNewUser
      this.u = result.user;
      this.sendPaymentMethod(email).then(sent => {
        this.router.navigate(['/store'])
      });

    })
    .catch(function (error) {
      console.log(error);
      // Some error occurred, you can inspect the code: error.code
      // Common errors could be invalid email and invalid or expired OTPs.
    });
}
}

login(email: string, password: string) {
var signed = this.firebaseAuth
  .auth
  .signInWithEmailAndPassword(email, password)
  .then(value => {

    return true;

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

return signed;
}

Есть идеи, что не так?

Ответы [ 3 ]

0 голосов
/ 07 сентября 2018

Ожидается, что учетная запись не сможет войти с паролем. Когда пользователь входит по электронной почте, пароль не связан с учетной записью пользователя. И это главное преимущество входа по электронной почте - пользователям не нужно создавать или запоминать еще один пароль.

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

0 голосов
/ 11 сентября 2018

Похоже, вы запутались с аутентификацией ссылки электронной почты и подтверждением адреса электронной почты. Оба метода отправляют электронное письмо вашему пользователю. В первом случае вы отправите ссылку своему пользователю для входа в свое приложение, подумайте об этом как о входе в Google или Facebook, у вас нет пароля в этом сценарии, но вместо того, чтобы отправлять запрос этим провайдерам, вы будете отправлять свежую пишите каждый раз. Во втором случае (вы пытаетесь сделать это) вам нужно создать пользователя с паролем электронной почты (что вы уже сделали, но вместо отправки подтверждающего электронного письма вы отправляете ссылку для входа в систему). В настройках действий продолжайте ссылаться на ваше приложение. И, наконец, когда вы вернетесь, примените код oob (вы получили его в качестве параметра url).

Я изменил ваш код, чтобы у вас был пример, что делать:

signup(email: string, password: string, firstname: string, lastname, 
    nickname: string, address: string) {
 this.firebaseAuth
  .auth
  .createUserWithEmailAndPassword(email, password)
  .then(value => {
    this.u = value.user;
    this.u.updateProfile({ displayName: nickname, photoURL: null });
    this.firebaseAuth.auth.updateCurrentUser(this.u);
    var actionCodeSettings = {
      url: 'https://www.example.com/?email=' + this.u.email,
      handleCodeInApp: true,
    };
    this.u.sendEmailVerification(actionCodeSettings);

    console.log('Success!', value);
  })
  .catch(err => {
    console.log('Something went wrong:', err.message);
  });
 }

emailVerfication() {
  this.firebaseAuth.auth.applyActionCode(this.route.snapshot.queryParams.oobCode)
     .then(() => console.log('BINGO!'));
}

Войти с помощью электронной почты / пароля, документов для проверки электронной почты:

https://firebase.google.com/docs/auth/web/password-auth https://firebase.google.com/docs/auth/web/passing-state-in-email-actions#passing_statecontinue_url_in_email_actions

0 голосов
/ 04 сентября 2018

Вы должны получить внеполосный или oobCode, а затем предложить пользователю ввести пароль. Наконец, вы передаете это .confirmPasswordReset.

firebase.auth().createUserWithEmailAndPassword(email, password).then(function () {
    firebase.auth().currentUser.sendEmailVerification();
})

function verifyPassword(oobCode, newPassword, email) {
    firebase.auth().confirmPasswordReset(oobCode, newPassword).then(function (resp) {
        // Password reset has been confirmed and new password updated.
        // TODO: Display a link back to the app, or sign-in the user directly
        // if the page belongs to the same domain as the app:
        firebase.auth().signInWithEmailAndPassword(email, newPassword);
        toast('Password Changed');
    }).catch(function (error) {
        // Error occurred during confirmation. The code might have expired or the
        // password is too weak.
        toast(error.message);
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...