implement an entire base refacotr and alot of styling overhauls and remakes.
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
export function requireLogin(req, res, next) {
|
||||
if (!req.session.user) {
|
||||
return res.status(403).json({error: "Not logged in"});
|
||||
}
|
||||
return next();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
function pruneBucket(bucket, windowMs, now) {
|
||||
const cutoff = now - windowMs;
|
||||
while (bucket.length && bucket[0] <= cutoff) {
|
||||
bucket.shift();
|
||||
}
|
||||
}
|
||||
|
||||
export function createRateLimiter({windowMs, max, keyGenerator, message}) {
|
||||
const hits = new Map();
|
||||
|
||||
return (req, res, next) => {
|
||||
const key = keyGenerator(req);
|
||||
if (!key) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const bucket = hits.get(key) || [];
|
||||
pruneBucket(bucket, windowMs, now);
|
||||
if (bucket.length >= max) {
|
||||
return res.status(429).json({error: message});
|
||||
}
|
||||
|
||||
bucket.push(now);
|
||||
hits.set(key, bucket);
|
||||
return next();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export function validateBody(validator) {
|
||||
return (req, res, next) => {
|
||||
const result = validator(req.body || {}, req);
|
||||
if (result?.error) {
|
||||
return res.status(400).json({error: result.error});
|
||||
}
|
||||
req.validatedBody = result?.value ?? req.body ?? {};
|
||||
return next();
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user