如何保护一个端点,以防止同一用户多次调用它?

huangapple go评论60阅读模式
英文:

How can I protect an endpoint so that the same user cannot call it more than once?

问题

我有一个端点,在NestJS服务器上创建文档。但是如果用户同时多次调用它,将会创建多个文档。但我有一个限制,每个用户只能创建2个文档。如果服务器同时收到两个请求访问同一个端点,限制检查不起作用,因为它在数据库中检查文档数量,如果>=2,它会抛出错误。但是这个检查几乎同时运行,脚本只能看到数据库中的一个文档,如果用户尝试以某种方式同时发起多个请求,服务器将创建2个文档。在NestJS中处理这种情况的最佳方法是什么?我不想允许创建超过2个文档,并处理同时发起的多个请求。

英文:

I have an endpoint which creates a document on a NestJS server.
But if a user call it multiple time at the same time, multiple documents will be created.
But I have a limit, every user can create only 2 documents.
The limit checking does not work if the server gets two requests to the same endpoint at the same time, because it checks the documents number in the database and if it is >=2, it throws an error. But this check run at the ~same time and the script can see only one document in the database and the server creates 2 documents if the user tries to make multiple requests at the same time somehow.
What is the best way in NestJS to handle this situation?
I don't want to allow to create more than 2 documents and handle the multiple requests at the same time.

答案1

得分: 1

在您的巢状应用程序中创建一个数据结构或内存映射,用于跟踪已经启动文档创建过程的用户ID。

在创建文档之前,检查用户ID是否已存在于数据结构或映射中。如果存在,您可以取消请求或返回适当的错误响应,指示该用户ID已经在创建文档的过程中。

一旦开始文档创建,将用户ID添加到数据结构或映射中,以指示该过程正在进行。

重要提示:此解决方案假定您的服务器应用程序在单个实例中运行!如果您有多个实例(例如,在无服务器环境中),这两个请求可能会命中不同的实例。

在这种情况下,您可以将信息存储在数据库中,而不是保存在内存中!

英文:

Create a data structure or an in-memory map in your nest-application to keep track of user IDs that have already initiated the document creation process.

Before creating a document, check if the user ID already exists in the data structure or map. If it does, you can cancel the request or return an appropriate error response indicating that a document creation is already in progress for that user ID.

Once you start the document creation, add the user ID to the data structure or map to indicate that the process is in progress.

Important: This solution assumes that your server application runs in a single instance! If you have multiple instances (e.g. in a serverless environment), the two requests could hit separate instances.

In that case you could store the information in the database instead of holding it in-memory!

huangapple
  • 本文由 发表于 2023年6月5日 15:23:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76404263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定