【问题标题】:How to sign out user in firebase after creating user with email?使用电子邮件创建用户后如何在firebase中注销用户?
【发布时间】:2021-09-12 06:34:00
【问题描述】:

在我的应用程序中,我想在使用电子邮件创建用户后注销用户,以便验证他的电子邮件。我尝试了不同的方法,但它们不起作用。这是我的代码:

try {
          await app
            .auth()
            .createUserWithEmailAndPassword(email.value, password.value)
            .then((userCredential)=>{
              // send verification mail.
              userCredential.user.sendEmailVerification();
              alert("Email sent");
            })
            .catch(alert);
            //history.push("/");
        } catch (error) {
          alert(error);
        }

我从另一个组件导入了 firebase 初始化器:

import firebase from "firebase/app";
import "firebase/auth";

const app = firebase.initializeApp({
  apiKey: process.env.REACT_APP_FIREBASE_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASE,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
});

export default app;

这是我的 authcontext:

useEffect(() => {
    app.auth().onAuthStateChanged((user) => {
      setCurrentUser(user);
      setPending(false);
    });
  }, []);

  if (pending) {
    return <>Loading...</>;
  }

  return (
    <AuthContext.Provider
      value={{
        currentUser,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

对此有什么想法吗?

【问题讨论】:

    标签: reactjs firebase authentication firebase-authentication email-verification


    【解决方案1】:

    您可以尝试使用signOut 方法将用户注销:

    // unsubscribe Auth listener here
    return app.auth()
             .createUserWithEmailAndPassword(email.value, password.value)
             .then(async (userCredential)=>{
               // send verification mail.
               await userCredential.user.sendEmailVerification();
               await app.auth().signOut();
               alert("Email sent");
             })
    

    虽然如果用户的电子邮件未经过验证,您不需要注销用户(取决于您希望应用程序如何工作,但只是一个注释)。 您可以简单地检查电子邮件是否经过验证,如果没有,则提示用户进行验证,否则不允许他们使用该应用程序。

    User 对象有一个属性 emailVerified 可以这样做:

    if (!app.auth().currentUser.emailVerified) {
      alert("Please verify the email")
    }
    

    您还可以检查电子邮件是否在安全规则中验证:

    match /{document=**} {
          allow read, write: if request.auth != null && request.auth.token.email_verified;
    }
    

    【讨论】:

    • 我之前尝试过您的第一个解决方案,但它不起作用。
    • @axfg 请尝试更新答案。我错过了承诺。请按照所述添加异步和等待。
    • 它工作正常。太感谢了。但在将用户踢出之前,它会显示私人路线一秒钟。如何克服?
    • @axfg 请分享您处理更改路线的代码。我怀疑你偶然有一个 onAuthStateChanged 监听器?如果原始问题得到解决,请随时接受答案:) What should I do when someone answers my question?
    • 我使用 authcontext ,在里面我有 onauthstatechanged。如何处理?
    猜你喜欢
    • 2019-08-12
    • 2021-10-21
    • 2019-12-13
    • 2021-01-07
    • 2018-03-12
    • 1970-01-01
    • 2016-11-18
    • 2023-03-21
    • 2019-07-26
    相关资源
    最近更新 更多