feat(rate-limiting): implement rate limiting for login attempts and enhance configuration

- Added environment variables for `RATE_LIMIT_MAX_FAILED_ATTEMPTS` and `RATE_LIMIT_LOCKOUT_TIME`
- Integrated rate limiting into the login process with a maximum of 5 failed attempts
- Refactored login attempt recording into the `authRouter`
- Removed deprecated `recordLogin` middleware and adjusted related logic
This commit is contained in:
Justin Lin committed 2025-04-27 16:29:03 +08:00
1 parent bda68ad293
commit ccbc4ff4b0
9 files changed
+49 -51

No files matched your search

+24 -9
View File
@@ -1,6 +1,7 @@
import { Router, Request, Response } from 'express'
import { Router, Request, Response, Express } from 'express'
import passport from 'passport'
import { recordLogin } from '../../middleware/recordLogin.js'
import { NextFunction } from 'express-serve-static-core'
import { LoginAttempt } from '../../../../packages/models'
import enabledMethods from '../../auth/passport.js'
import {
@@ -17,15 +18,17 @@ import {
registerFromSessionValidators,
registerValidators,
} from '../validators/authValidator.js'
import { authenticateRateLimit } from '../../middleware/rateLimiter.js'
import { NextFunction } from 'express-serve-static-core'
import { rateLimitByAccount } from '../../middleware/rateLimiter.js'
import {
authenticateRateLimit,
rateLimitByAccount,
} from '../../middleware/rateLimiter.js'
const router = Router()
router.post(
'/login',
rateLimitByAccount,
authenticateRateLimit,
rateLimitByAccount,
loginValidators,
(req: Request, res: Response, next: NextFunction): void => {
passport.authenticate(
@@ -42,20 +45,32 @@ router.post(
return res.status(401).json({ message: msg })
}
req.logIn(user, async (err: unknown) => {
if (err) {
req.logIn(user, async (loginErr: unknown) => {
if (loginErr) {
await recordLogin(req, false, 'login session failed')
return next(err)
return next(loginErr)
}
await recordLogin(req, true, 'login success')
return res.json({ message: 'success' })
})
return null
}
)(req, res, next)
}
)
async function recordLogin(req: Request, success: boolean, message: string) {
await LoginAttempt.create({
ip: req.ip,
userAgent: req.headers['user-agent'] || '',
success,
time: new Date(),
username: req.body.username,
message,
})
}
router.post('/register', authenticateRateLimit, registerValidators, register)
router.post('/register-guest', authenticateRateLimit, registerGuest)