【问题标题】:javascript - Firestore checking if username already exists [duplicate]javascript - Firestore 检查用户名是否已存在 [重复]
【发布时间】:2021-04-27 15:51:30
【问题描述】:

我需要一点关于 Firestore 的帮助。我有一个用户数据收集,每个用户信息的用户 ID 文档。我想检查用户名是否已经存在; // “那个用户名已经存在”。我该怎么做?

const signUpForm = document.querySelector('#signup-form'); 
signUpForm.addEventListener('submit', (evt) =>{       
evt.preventDefault();                               
//get user email, password
const email= signUpForm['signup-email'].value;     
const password = signUpForm['signup-password'].value;
const repassword = signUpForm['signup-re-password'].value;

if(password != repassword)
{
    alert("Passwords don't match \nPlease try again");
}
else{  
   if(//check username exist?)
   {
    alert('This username already exist !');
    }
    else { //sign up the user
     auth.createUserWithEmailAndPassword(email, password)
    .then(cred => {
        return db.collection('users').doc(cred.user.uid).set({
            neptun: signUpForm['signup-neptun'].value,
            nickName: signUpForm['signup-nickName'].value
        });                     
      });
   }

});

更新! 一个可行的解决方案:

const username = signUpForm['signup-username'].value; 
db.collection("users").where("username", "==", username).get().then((doc) => {
        if(!doc.empty) {
            alert("This  username is already taken!");
        }
        else{
            //sign up the user               
    });     

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    直截了当,您可以尝试以下代码:

    const username = ""
    const userNameDoc = await firebase.firestore().collection("users").where("username", "==", username).get()
    if(!userNameDoc.empty) {
        console.log("This username is already taken!");
    }
    

    但是由于这都是前端,所以如果有人愿意,可以绕过它。所有这一切都要求您让所有用户访问整个用户集合,这并不理想。因此,您最好使用云功能或您自己的服务器环境以获得更好的安全性。

    例如,您可以使用安全规则阻止对 Firestore 集合的所有直接请求,并使用云函数中的 Admin SDK 创建用户。

    您可以在云函数中使用以下代码通过检查用户名是否仍然有效来创建新用户。

    
    exports.createNewUser = functions.https.onCall(async (data, context) => {
      const userEmail = data.email
      const userName = data.name
      const userPass = data.password
      const userNameDoc = await admin.firestore().collection("users").where("username", "==", username).get()
      if(!userNameDoc.empty) {
        console.log("This username is already taken!");
        return {result: "Username is already taken!"}
      } 
      return admin
      .auth()
      .createUser({
        email: 'user@example.com',
        password: userPassword,
        displayName: userName,
      })
      .then((userRecord) => {
        // See the UserRecord reference doc for the contents of userRecord.
        console.log('Successfully created new user:', userRecord.uid);
        return {result: "User Created!"}
      })
      .catch((error) => {
        console.log('Error creating new user:', error);
        return {result: error}
      });
    });
    

    对于您的 Firestore 数据库,第二种方法比第一种方法更安全。

    【讨论】:

    • 如果我在代码 Firestore 功能上留下“等待”,则不起作用。
    • @FedFAr 你在函数中添加了async 关键字吗? functions.https.onCall(async (data, context) => {...}
    • 但是我删除总是出现在控制台上:“这个用户名已经被占用了!”
    • @FedFAr 确保您已根据 .where("username", "==", username)中的 Firestore 替换了 fieldName
    • @FedFAr 如果这不起作用,请告诉我。如果是这样,您可以单击勾号图标,以便其他人知道问题已解决。
    【解决方案2】:

    Firebase 会自动检查电子邮件是否已在使用中。 当用户尝试使用已在使用的电子邮件地址注册时,createUserWithEmailAndPassword 函数会引发错误。 捕获错误,然后检查“auth/email-already-in-use”错误代码:

    .catch(function(error){
      if(error.code=="auth/email-already-in-use"){//do something}
    })
    

    有关更多详细信息,请参阅 firebase 身份验证参考 https://firebase.google.com/docs/reference/js/firebase.auth.Auth?authuser=1#createuserwithemailandpassword

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 2019-01-31
      • 2018-11-27
      • 2012-01-26
      • 1970-01-01
      相关资源
      最近更新 更多