refactor: middlewares

This commit is contained in:
wancat committed 2024-02-19 19:08:34 +08:00
1 parent 7c1d83ccd3
commit 5e8df7ae01
8 files changed
+53 -39

No files matched your search

+10 -12
View File
@@ -7,12 +7,6 @@ import googleStrategy from './googleStrategy.js'
import githubStrategy from './githubStrategy.js' import githubStrategy from './githubStrategy.js'
import logger from '../utils/logger.js' import logger from '../utils/logger.js'
interface SerializedUser extends Express.User {
_id: string
username: string
email: string
}
passport.use(passwordStrategy) passport.use(passwordStrategy)
passport.use(jwtStrategy) passport.use(jwtStrategy)
@@ -32,21 +26,25 @@ if (githubStrategy !== null) {
passport.use(githubStrategy) passport.use(githubStrategy)
} }
passport.serializeUser((user: Express.User, done: any) => { passport.serializeUser((user: Express.User, done) => {
process.nextTick(async () => { process.nextTick(async () => {
try { try {
const serializedUser = user as SerializedUser const id = (user as any)._id
if (!(await UserProfile.exists({ user: serializedUser._id }))) { if (!id) {
await UserProfile.create({ user: serializedUser._id }) done(new Error('User has no _id'))
return
} }
done(null, serializedUser) if (!(await UserProfile.exists({ user: id }))) {
await UserProfile.create({ user: id })
}
done(null, user)
} catch (err) { } catch (err) {
done(err) done(err)
} }
}) })
}) })
passport.deserializeUser((user: SerializedUser, done) => { passport.deserializeUser((user: Express.User, done) => {
process.nextTick(() => { process.nextTick(() => {
done(null, user) done(null, user)
}) })
-9
View File
@@ -1,9 +0,0 @@
export default function authRequired(req, res, next) {
if (req.isAuthenticated() && !req.session.newUser) {
next()
return
}
res.status(401).json({
message: 'not authenticated',
})
}
+15
View File
@@ -0,0 +1,15 @@
import type { Request, Response, NextFunction } from 'express'
export default function authRequired(
req: Request,
res: Response,
next: NextFunction
) {
if (req.isAuthenticated() && !('newUser' in req.session)) {
next()
return
}
res.status(401).json({
message: 'not authenticated',
})
}
-13
View File
@@ -1,13 +0,0 @@
import logger from '../utils/logger.js'
export function asyncHandler(fn) {
return (req, res, next) => {
fn(req, res, next).catch(next)
}
}
// eslint-disable-next-line no-unused-vars
export default function errorHandler(err, req, res, next) {
logger.error(err) // Log error stack trace to the console
res.status(500).send({ message: 'Something broke!' }) // Send error response
}
+20
View File
@@ -0,0 +1,20 @@
import type { Request, Response, NextFunction } from 'express'
import logger from '../utils/logger.js'
export function asyncHandler(fn: any) {
return (req: Request, res: Response, next: NextFunction) => {
fn(req, res, next).catch(next)
}
}
// eslint-disable-next-line no-unused-vars
export default function errorHandler(
err: any,
req: Request,
res: Response,
// eslint-disable-next-line no-unused-vars
next: NextFunction
) {
logger.error(err) // Log error stack trace to the console
res.status(500).send({ message: 'Something broke!' }) // Send error response
}
@@ -1,9 +1,11 @@
import rateLimit from 'express-rate-limit' 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 config from '../config.js'
function createRateLimiter(options) { function createRateLimiter(options: Partial<Options>) {
if (config.testing.enabled) { if (config.testing.enabled) {
return (req, res, next) => next() return (req: Request, res: Response, next: NextFunction) => next()
} }
return rateLimit(options) return rateLimit(options)
} }
@@ -21,7 +23,7 @@ export const authenticateRateLimit = createRateLimiter({
export const sessionRateLimit = createRateLimiter({ export const sessionRateLimit = createRateLimiter({
windowMs: 10 * 1000, windowMs: 10 * 1000,
max: 1, max: 1,
keyGenerator: (req) => { keyGenerator: (req: Request) => {
return req.user ? req.user._id : req.ip return req.user ? (req.user as any)._id : req.ip || ''
}, },
}) })
File renamed without changes.
@@ -1,6 +1,7 @@
import { validationResult } from 'express-validator' import { validationResult } from 'express-validator'
import type { Request, Response, NextFunction } from 'express'
export function noError(req, res, next) { export function noError(req: Request, res: Response, next: NextFunction) {
const result = validationResult(req) const result = validationResult(req)
if (result.isEmpty()) { if (result.isEmpty()) {
next() next()