How to create blockUserTime correctly?

Viewed 9

I have security.controller, security.service and VerificationEntity.

So, in security.controller I have checkVerificationCode method in which I am trying to block the user if he has exceeded the allowed number of inputs of the wrong code and create the timestamp of the last failed attempt, and then in security.service I'm saving this blockedTime into the blockedTime column in VerificationEntity.

Problem is, when I'm trying to check code again during this block time, blockedTime is updating again. How can I prevent it and make blockedTime static, in order to further compare it with the current timestamp.

security.controller:

public checkVerificationCode = async (req: Request, res: Response) => {
    try {
      const { mobilePhone, verificationCode, id } = req.body;
      const dataToCheck = await this.securityService.checkCode(mobilePhone);

      if (verificationCode !== dataToCheck.verificationCode || id !== dataToCheck.id) {
        const newTries = dataToCheck.tries + 1;
        const triesLeft = +process.env.MAX_CODE_TRIES - +newTries;

        if (triesLeft <= 0) {
          const blockedTime = await this.securityService.updateBlockTime(mobilePhone, id);

          if (timeDiffInMinutes(blockedTime) <= +process.env.USER_BLOCK_EXPIRATION) {
            return res.status(StatusCodes.BAD_REQUEST).json({ blockSeconds: `You still blocked` });
          }

          return res
            .status(StatusCodes.BAD_REQUEST)
            .json({ blockSeconds: `You was blocked, you can try again after 10 minutes.` });
        }

        return res.status(StatusCodes.BAD_REQUEST).json({ msg: 'Verification code is invalid' });
      }

      if (timeDiffInMinutes(dataToCheck.updatedAt) >= +process.env.CODE_EXPIRATION_TIME) {
        return res.status(StatusCodes.BAD_REQUEST).json({ msg: 'Verification code expired!' });
      }

      await this.securityService.resetTries(mobilePhone, id);

      return res.status(StatusCodes.OK).json({ msg: 'Success!' });
    } catch (error) {
      return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ msg: error.message });
    }
  };

security.service:

public async updateBlockTime(mobilePhone: string, id: string) {
    const { blockedTime } = await getRepository(VerificationEntity).findOne({ mobilePhone: mobilePhone as string, id });
    const timestamp = Date.now();
    const blockedTimestamp = new Date(timestamp);

    await getRepository(VerificationEntity)
      .createQueryBuilder()
      .update(VerificationEntity)
      .set({ blockedTime: blockedTimestamp })
      .where({ mobilePhone: mobilePhone as string, id: id as string })
      .execute();

    return blockedTime;
  }
0 Answers
Related