Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.9 kB
2
Indexable
Never
export const mfa = async (req: Request, res: Response) => {
  const { userId } = req.body
  if (userId) {
    try {
      const user = await prisma.user.findFirst({
        where: {
          id: Number(userId),
        },
      })
      if (!user) {
        throw new Error('Invalid account')
      }
      const multiFactor = await prisma.multiFactorAuth.findFirst({
        where: {
          userId: Number(userId),
          type: 'test',
          used: false,
          expiredAt: {
            gte: new Date(),
          },
        },
      })
      const code = Math.floor(100000 + Math.random() * 900000)
      const successMessage = `Email was sent to ${user.email}, please check before it expires.`
      const sendEmailParams = { to: user.email, code: String(code) }
      const authEmail = new AuthEmail()
      if (!multiFactor) {
        authEmail.sendMFA(sendEmailParams)
        await prisma.multiFactorAuth.create({
          data: {
            userId: Number(userId),
            code: String(code),
            type: 'test',
            expiredAt: dayjs().add(3, 'minutes').format(),
          },
        })
        res.json({
          error: false,
          message: successMessage,
        })
      } else {
        authEmail.sendMFA(sendEmailParams)
        res.json({
          error: false,
          message: successMessage,
        })
      }
    } catch (err: any) {
      res.json({
        error: true,
        message: err.message,
      })
    }
  } else {
    res.json({
      error: true,
      message: REQUIRED_VALUE_EMPTY,
    })
  }
}

export const mfaVerify = async (req: Request, res: Response) => {
  const { userId, code } = req.body
  if (userId && code) {
    try {
      const user = await prisma.user.findFirst({
        where: {
          id: Number(userId),
        },
      })
      if (!user) {
        throw new Error('Invalid account')
      }
      const multiFactor = await prisma.multiFactorAuth.findFirst({
        where: {
          userId: Number(userId),
          code: String(code),
          type: 'test',
          used: false,
          expiredAt: {
            gte: new Date(),
          },
        },
      })
      if (multiFactor) {
        await prisma.multiFactorAuth.update({
          where: {
            id: multiFactor.id,
          },
          data: {
            used: true,
          },
        })
        res.json({
          error: false,
          item: {},
          message: 'User verified',
        })
      } else {
        res.json({
          error: true,
          message: 'Invalid or expired token',
        })
      }
    } catch (err: any) {
      res.json({
        error: true,
        message: err.message,
      })
    }
  } else {
    res.json({
      error: true,
      message: REQUIRED_VALUE_EMPTY,
    })
  }
}
Leave a Comment