mirror of
https://github.com/linux-odyssey/linux-odyssey.git
synced 2026-11-05 19:20:12 +08:00
feat(auth): add LoginAttempt schema and record login attempts with failure rate limit
- Added `LoginAttempt` Mongoose schema to store login history - Integrated login attempt recording into login flow (success/failure) - Created `rateLimitByAccount` middleware to block login if 10 failed attempts in 10 minutes
This commit is contained in:
1 parent
13fb8737a3
commit
af2f1ef707
7 files changed
+123
-11
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import { Router, Request, Response } from 'express'
|
||||
import passport from 'passport'
|
||||
|
||||
import { recordLogin } from '../../middleware/recordLogin.js'
|
||||
import enabledMethods from '../../auth/passport.js'
|
||||
|
||||
import {
|
||||
@@ -18,16 +18,41 @@ import {
|
||||
registerValidators,
|
||||
} from '../validators/authValidator.js'
|
||||
import { authenticateRateLimit } from '../../middleware/rateLimiter.js'
|
||||
|
||||
import { NextFunction } from 'express-serve-static-core'
|
||||
import { rateLimitByAccount } from '../../middleware/rateLimiter.js'
|
||||
const router = Router()
|
||||
|
||||
router.post(
|
||||
'/login',
|
||||
rateLimitByAccount,
|
||||
authenticateRateLimit,
|
||||
loginValidators,
|
||||
passport.authenticate('local', { failureMessage: true }),
|
||||
(req: Request, res: Response) => {
|
||||
res.json({ message: 'success' })
|
||||
(req: Request, res: Response, next: NextFunction): void => {
|
||||
passport.authenticate(
|
||||
'local',
|
||||
async (err: unknown, user: Express.User | false, info: any) => {
|
||||
if (err) {
|
||||
await recordLogin(req, false, 'passport error')
|
||||
return next(err)
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
const msg = info?.message || 'invalid credentials'
|
||||
await recordLogin(req, false, msg)
|
||||
return res.status(401).json({ message: msg })
|
||||
}
|
||||
|
||||
req.logIn(user, async (err: unknown) => {
|
||||
if (err) {
|
||||
await recordLogin(req, false, 'login session failed')
|
||||
return next(err)
|
||||
}
|
||||
|
||||
await recordLogin(req, true, 'login success')
|
||||
return res.json({ message: 'success' })
|
||||
})
|
||||
}
|
||||
)(req, res, next)
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -85,6 +85,7 @@ async function main() {
|
||||
server.listen(config.port, '0.0.0.0', () => {
|
||||
logger.info(`Server listening at ${config.baseUrl}`)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
main().catch((err) => logger.error(err))
|
||||
@@ -2,6 +2,8 @@ import rateLimit from 'express-rate-limit'
|
||||
import type { Options } from 'express-rate-limit'
|
||||
import type { Request, Response, NextFunction } from 'express'
|
||||
import config from '../config.js'
|
||||
import { recordLogin } from './recordLogin.js'
|
||||
import { LoginAttempt } from '@linux-odyssey/models'
|
||||
|
||||
function createRateLimiter(options: Partial<Options>) {
|
||||
if (config.testing.enabled) {
|
||||
@@ -11,14 +13,21 @@ function createRateLimiter(options: Partial<Options>) {
|
||||
}
|
||||
|
||||
export const globalRateLimit = createRateLimiter({
|
||||
windowMs: 60 * 1000, // 1 minute
|
||||
windowMs: 60 * 1000,
|
||||
max: 100,
|
||||
})
|
||||
|
||||
export const authenticateRateLimit = createRateLimiter({
|
||||
windowMs: 2 * 60 * 1000,
|
||||
max: 5,
|
||||
})
|
||||
export const authenticateRateLimit = config.testing.enabled
|
||||
? (req: Request, res: Response, next: NextFunction) => next()
|
||||
: rateLimit({
|
||||
windowMs: 1 * 1000,
|
||||
max: 5,
|
||||
handler: async (req: Request, res: Response, _next: NextFunction) => {
|
||||
recordLogin(req, false, 'rate limit')
|
||||
res.status(429).json({
|
||||
error: 'Too many login attempts. Please try again later.',
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const sessionRateLimit = createRateLimiter({
|
||||
windowMs: 10 * 1000,
|
||||
@@ -27,3 +36,30 @@ export const sessionRateLimit = createRateLimiter({
|
||||
return req.user ? (req.user as any)._id : req.ip || ''
|
||||
},
|
||||
})
|
||||
|
||||
export async function rateLimitByAccount(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const username = req.body.username?.trim()
|
||||
if (!username) {
|
||||
return next()
|
||||
}
|
||||
|
||||
const since = new Date(Date.now() - 10 * 60 * 1000)
|
||||
|
||||
const recentFailedCount = await LoginAttempt.countDocuments({
|
||||
username,
|
||||
success: false,
|
||||
time: { $gte: since },
|
||||
})
|
||||
|
||||
if (recentFailedCount >= 10) {
|
||||
return res.status(429).json({
|
||||
error: 'Too many failed login attempts. Please try again later.',
|
||||
})
|
||||
}
|
||||
|
||||
return next()
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Request, Response, NextFunction } from 'express'
|
||||
import { LoginAttempt } from '../../../packages/models'
|
||||
|
||||
export 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,
|
||||
})
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { validationResult } from 'express-validator'
|
||||
import type { Request, Response, NextFunction } from 'express'
|
||||
import { recordLogin } from './recordLogin.js'
|
||||
|
||||
|
||||
export function noError(req: Request, res: Response, next: NextFunction) {
|
||||
const result = validationResult(req)
|
||||
@@ -7,6 +9,7 @@ export function noError(req: Request, res: Response, next: NextFunction) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
recordLogin(req, false, 'valid error');
|
||||
res.status(400).json({
|
||||
message: 'Validation failed',
|
||||
errors: result.array(),
|
||||
|
||||
Reference in new issue
Block a user