add limit

This commit is contained in:
b1ek 2023-03-04 15:00:53 +10:00
parent debf79e6fc
commit daee21ab4d
Signed by: blek
GPG Key ID: 14546221E3595D0C
6 changed files with 54 additions and 4 deletions

View File

@ -1,4 +1,5 @@
APP_PORT=8080
APP_DEBUG=false
MAXLEN=5120
MAXLEN=5120
MAXFILES=128

View File

@ -1,26 +1,56 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const glob = require('glob');
const root = path.join(process.cwd(), '/usercontent');
const { MAXFILES } = process.env;
console.log(root);
let initalized = false;
let submitted = 0;
async function init() {
if (initalized) return;
glob(root + '/**', undefined, (err, files) => {
if (err) {
console.error(err);
return;
}
files.filter(file => {
return !file.startsWith('.');
}).forEach(file => {
submitted++;
});
initalized = true;
});
}
function submitted() {return submitted;}
const make_id = () => {
return crypto.randomBytes(8).toString('hex');
};
async function get(id) {
init();
return fs.readFileSync(path.join(root, id)).toString();
}
async function write(fname, data) {
init();
submitted++;
return fs.writeFile(path.join(root, fname), data, () => {});
}
async function create(data) {
if (submitted >= MAXFILES) return "NA";
const id = make_id();
await write(id, data);
return id;
}
module.exports = { get, write, create, make_id };
module.exports = { get, write, create, make_id, submitted };

View File

@ -15,6 +15,7 @@
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-async-handler": "^1.2.0",
"glob": "^9.2.1",
"pug": "^3.0.2"
}
}

View File

@ -1,9 +1,13 @@
const express = require('express');
const router = express.Router();
const handler = require('express-async-handler');
const content = require('../helpers/content');
async function index(req, res) {
res.render('main', {maxlen: process.env.MAXLEN});
res.render('main', {
maxlen: process.env.MAXLEN,
exceeded: content.submitted() >= process.env.MAXFILES
});
}
router.get('/', handler(index));

View File

@ -3,7 +3,15 @@ const router = express.Router();
const handler = require('express-async-handler');
const content = require('../helpers/content');
const { MAXFILES } = process.env;
async function upload(req, res) {
if (content.submitted() >= MAXFILES) {
res.status(405).send('Not allowed');
return;
}
const data = req.body.text;
const id = await content.create(data);
res.redirect(

View File

@ -5,4 +5,10 @@ block content
p(align='center')
textarea(name='text' class='data' placeholder='Put your text in here!' + (maxlen ? ` (Max length is ${maxlen} bytes)` : ''))
br
input(type='submit' value='Upload!')
if (!exceeded)
input(type='submit' value='Upload!')
if (exceeded)
p(style='color:darkred;font-weight:bold;font-size:9pt')
| Max uploads limit exceeded. No more uploads would be accepted.
br
| Contact site administrator so they would increase the limit or delete some uploads.