Skip to content

Commit

Permalink
fix: applied rate limit to otp generation and verification
Browse files Browse the repository at this point in the history
  • Loading branch information
oxiang committed Sep 16, 2020
1 parent 38cc771 commit 41bcb6d
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/server/api/login/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import Express from 'express'
import rateLimit from 'express-rate-limit'
import { createValidator } from 'express-joi-validation'
import getIp from '../../util/request'
import { otpGenerationSchema, otpVerificationSchema } from './validators'
import { container } from '../../util/inversify'
import { LoginControllerInterface } from '../../controllers/interfaces/LoginControllerInterface'
import { DependencyIds } from '../../constants'
import { logger } from '../../config'

const router: Express.Router = Express.Router()

Expand All @@ -13,6 +16,32 @@ const loginController = container.get<LoginControllerInterface>(
DependencyIds.loginController,
)

/**
* Rate limiter for API generating OTP.
*/
const apiOtpGeneratorLimiter = rateLimit({
keyGenerator: (req) => getIp(req) as string,
onLimitReached: (req) =>
logger.warn(
`Rate limit (generating OTP) reached for IP Address: ${getIp(req)}`,
),
windowMs: 60000, // 1 minute
max: 5,
})

/**
* Rate limiter for API verifying OTP.
*/
const apiOtpVerificationLimiter = rateLimit({
keyGenerator: (req) => getIp(req) as string,
onLimitReached: (req) =>
logger.warn(
`Rate limit (verifying OTP) reached for IP Address: ${getIp(req)}`,
),
windowMs: 60000, // 1 minute
max: 5,
})

/**
* For the Login message banner.
*/
Expand All @@ -25,6 +54,7 @@ router.get('/emaildomains', loginController.getEmailDomains)
*/
router.post(
'/otp',
apiOtpGeneratorLimiter,
authValidator.body(otpGenerationSchema),
loginController.generateOtp,
)
Expand All @@ -34,6 +64,7 @@ router.post(
*/
router.post(
'/verify',
apiOtpVerificationLimiter,
authValidator.body(otpVerificationSchema),
loginController.verifyOtp,
)
Expand Down

0 comments on commit 41bcb6d

Please sign in to comment.