代码在 catch 语句捕获和错误后运行,并在 react native firebase 中返回 usernameTaken 应该返回一个布尔值安全地声明和释放用户名以原子方式更新您的数据库用户名不区分大小写结果

如何解决代码在 catch 语句捕获和错误后运行,并在 react native firebase 中返回 usernameTaken 应该返回一个布尔值安全地声明和释放用户名以原子方式更新您的数据库用户名不区分大小写结果

每当我在 catch 块仍然运行后通过代码捕获错误并从函数返回时,我都会遇到问题。这是我使用的两个函数:

    usernameTaken: async (username) => {
        const user = await firebase.firestore().collection("uniqueUsers").doc(username).get();
        if (user.exists) {
            alert("Username is taken. Try again with another username.");
            throw new Error('Username is taken. Try again with another username.');
        }
    },changeUsername: async (currentUsername,newUsername) => {
      try {
          var user = Firebase.getCurrentUser();
          Firebase.usernameTaken(newUsername);
      } catch (err) {
          alert(err.message);
          return;
      }
      await db.collection('uniqueUsers').doc(currentUsername).delete();
      await db.collection("users").doc(user.uid).update({username: newUsername});
      await db.collection("uniqueUsers").doc(newUsername).set({username: newUsername});
      alert("Congratulations! You have successfully updated your username.");
    }

我非常感谢您对此问题的任何帮助,因为我已经为此苦苦挣扎了 2 天多,似乎找不到解决方案。

解决方法

试试这个检查你的值是否为空或未定义在 try 块中抛出一些错误,例如

cosnt user = Firebase.getCurrentUser();
const name = Firebase.usernameTaken(newUsername); 
// throwing error 
if(name == "") throw "is empty"; 
await db.collection('uniqueUsers').doc(currentUsername).delete();
,

在您的原始代码中,usernameTaken() 承诺是浮动的,因为您没有使用 await。因为它是浮动的,所以您的 catch() 处理程序永远不会捕捉到它的错误。

changeUsername: async (currentUsername,newUsername) => {
  try {
      const user = Firebase.getCurrentUser();
      /* here -> */ await Firebase.usernameTaken(newUsername);
  } catch (err) {
      alert(err.message);
      return;
  }
  /* ... other stuff ... */
}

加分

usernameTaken 应该返回一个布尔值

您应该更改 usernameTaken 以返回一个布尔值。这可以说比使用 alert()(阻止代码执行)或抛出错误更好。

usernameTaken: async (username) => {
  const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username).get();
  return usernameDoc.exists; // return a boolean whether the doc exists
}

安全地声明和释放用户名

根据您当前的代码,您无法保护任何人出现,而只是删除您数据库中的任何用户名或声明在您上次检查其可用性和您致电 set() 之间使用的用户名新用户名。您应该保护您的数据库,以便用户只能写入他们拥有的用户名。

将所有者的 ID 添加到文档中:

"/uniqueUsers/{username}": {
  username: "username",uid: "someUserId"
}

这样您就可以将编辑/删除锁定给拥有该用户名的用户。

service cloud.firestore {
  match /databases/{database}/documents {
    
    match /uniqueUsers/{username} {
      // new docs must have { username: username,uid: currentUser.uid }
      allow create: if request.auth != null
                    && request.resource.data.username == username
                    && request.resource.data.uid == request.auth.uid
                    && request.resource.data.keys().hasOnly(["uid","username"]);

      // any logged in user can get this doc
      allow read: if request.auth != null;

      // only the linked user can delete this doc
      allow delete: if request.auth != null
                    && request.auth.uid == resource.data.uid;

      // only the linked user can edit this doc,as long as username and uid are the same
      allow update: if request.auth != null
                    && request.auth.uid == resource.data.uid
                    && request.resource.data.diff(resource.data).unchangedKeys().hasAll(["uid","username"]) // make sure username and uid are unchanged
                    && request.resource.data.diff(resource.data).changedKeys().size() == 0; // make sure no other data is added
    }
  }
}

以原子方式更新您的数据库

您正在以可能损坏数据库的方式修改数据库。您可以删除旧用户名,然后无法更新当前用户名,这意味着您永远不会链接新用户名。要解决此问题,您应该使用 batched write 将所有这些更改一起应用。如果任何一个失败,什么都不会改变。

await db.collection("uniqueUsers").doc(currentUsername).delete();
await db.collection("users").doc(user.uid).update({username: newUsername});
await db.collection("uniqueUsers").doc(newUsername).set({username: newUsername});

变成

const db = firebase.firestore();
const batch = db.batch();

batch.delete(db.collection("uniqueUsers").doc(currentUsername));
batch.update(db.collection("users").doc(user.uid),{ username: newUsername });
batch.set(db.collection("uniqueUsers").doc(newUsername),{ username: newUsername });

await batch.commit();

用户名不区分大小写

您当前的用户名区分大小写,如果您希望您的用户输入/写出其个人资料的 URL,则不建议这样做。考虑一下 "example.com/MYUSERNAME""example.com/myUsername""example.com/myusername" 如何成为不同的用户。如果有人在一张纸上潦草地写下他们的用户名,您会希望所有这些都转到同一个用户的个人资料。

usernameTaken: async (username) => {
  const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username.toLowerCase()).get();
  return usernameDoc.exists; // return a boolean whether the doc exists
},changeUsername: async (currentUsername,newUsername) => {
  const lowerCurrentUsername = currentUsername.toLowerCase();
  const lowerNewUsername = newUsername.toLowerCase();

  /* ... */

  return lowerNewUsername; // return the new username to show success
}

结果

将所有这些结合在一起,给出:

usernameTaken: async (username) => {
  const usernameDoc = await firebase.firestore().collection("uniqueUsers").doc(username).get();
  return usernameDoc.exists; // return a boolean
},newUsername) => {
  const user = Firebase.getCurrentUser();
  if (user === null) {
    throw new Error("You must be signed in first!");
  }

  const taken = await Firebase.usernameTaken(newUsername);
  if (taken) {
    throw new Error("Sorry,that username is taken.");
  }

  const lowerCurrentUsername = currentUsername.toLowerCase();
  const lowerNewUsername = newUsername.toLowerCase();
  const db = firebase.firestore();
  const batch = db.batch();
  
  batch.delete(db.collection("uniqueUsers").doc(lowerCurrentUsername));
  batch.update(db.collection("users").doc(user.uid),{
    username: lowerNewUsername
  });
  batch.set(db.collection("uniqueUsers").doc(lowerNewUsername),{
    username: lowerNewUsername,uid: user.uid
  });

  await batch.commit();

  return lowerNewUsername;
}
// elsewhere in your code
changeUsername("olduser","newuser")
  .then(
    (username) => {
      alert("Your username was successfully changed to @" + username + "!");
    },(error) => {
      console.error(error);
      alert("We couldn't update your username!");
    }
  );

注意:如果您使用上述所有建议(如安全规则),batch.commit() 将失败的预期方式之一是有人在当前用户之前使用用户名。如果您收到权限错误,请假设有人在您之前使用了用户名。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-