refactor: middleware

This commit is contained in:
Tianpao
2025-11-01 04:19:17 +08:00
parent dd39c3e63c
commit ed5e962370
3 changed files with 74 additions and 61 deletions

View File

@@ -11,7 +11,7 @@
"type": "module", "type": "module",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"test":"" "test":"",
"build-server": "tsc ." "build-server": "tsc ."
}, },
"devDependencies": { "devDependencies": {

View File

@@ -11,50 +11,22 @@ import process from "node:process"
import chalk from "chalk" import chalk from "chalk"
import child_process from "node:child_process" import child_process from "node:child_process"
import FileManager from "./data/FileManager.ts" import FileManager from "./data/FileManager.ts"
import TokenManager from "./api/TokenManager.ts"
import UserChatLinker from "./data/UserChatLinker.ts"
import path from "node:path" import path from "node:path"
import cookieParser from 'cookie-parser' import cookieParser from 'cookie-parser'
import fs from 'node:fs/promises' import fs from 'node:fs/promises'
// @ts-types="npm:@types/express-fileupload" // @ts-types="npm:@types/express-fileupload"
import fileUpload from 'express-fileupload' import fileUpload from 'express-fileupload'
import { Middleware } from "./middleware.ts"
const app = express() const app = express()
app.use('/', express.static(config.data_path + '/page_compiled')) app.use('/', express.static(config.data_path + '/page_compiled'))
app.use(cookieParser()) app.use(cookieParser())
app.get('/uploaded_files/:hash', (req, res) => { app.get('/uploaded_files/:hash',Middleware.Get_uploaded_files, (req, res) => {
const hash = req.params.hash as string const file = FileManager.findByHash(req.params.hash as string)
if (hash == null) {
res.status(404).send({
msg: "404 Not Found",
})
return
}
const file = FileManager.findByHash(hash)
if (file == null) { if (file == null) {
res.status(404).send({ return;
msg: "404 Not Found",
})
return
} }
if (file.getChatId() != null) {
const userToken = TokenManager.decode(req.headers.token || req.cookies.token)
if (!TokenManager.checkToken(userToken, req.headers['device-id'] || req.cookies.device_id)) {
res.status(401).send({
msg: "401 UnAuthorized",
})
return
}
if (!UserChatLinker.checkUserIsLinkedToChat(userToken.author, file.getChatId() as string)) {
res.status(403).send({
msg: "403 Forbidden",
})
return
}
}
const fileName = encodeURIComponent(file!.getName()?.replaceAll('"', '')) const fileName = encodeURIComponent(file!.getName()?.replaceAll('"', ''))
res.setHeader('Content-Disposition', `inline; filename="${fileName}"`) res.setHeader('Content-Disposition', `inline; filename="${fileName}"`)
res.setHeader('Content-Type', file!.getMime()) res.setHeader('Content-Type', file!.getMime())
@@ -69,35 +41,8 @@ app.use(fileUpload({
tempFileDir: config.data_path + '/upload_cache', tempFileDir: config.data_path + '/upload_cache',
abortOnLimit: true, abortOnLimit: true,
})) }))
app.post('/upload_file', async (req, res) => { app.post('/upload_file',Middleware.Post_upload_file, async (req, res) => {
const userToken = TokenManager.decode(req.headers.token || req.cookies.token)
if (!TokenManager.checkToken(userToken, req.headers['device-id'] || req.cookies.device_id)) {
res.status(401).send({
msg: "401 UnAuthorized",
})
return
}
if (req.body.chat_id && !UserChatLinker.checkUserIsLinkedToChat(userToken.author, req.body.chat_id)) {
res.status(403).send({
msg: "403 Forbidden",
})
return
}
const file = req.files?.file as fileUpload.UploadedFile const file = req.files?.file as fileUpload.UploadedFile
if (file?.data == null) {
res.status(400).send({
msg: "No file was found or multiple files were uploaded",
})
return
}
if (req.body.file_name == null) {
res.status(400).send({
msg: "Filename is required",
})
return
}
const hash = (await FileManager.uploadFile(req.body.file_name, await fs.readFile(file.tempFilePath), req.body.chat_id)).getHash() const hash = (await FileManager.uploadFile(req.body.file_name, await fs.readFile(file.tempFilePath), req.body.chat_id)).getHash()
res.status(200).send({ res.status(200).send({

68
server/middleware.ts Normal file
View File

@@ -0,0 +1,68 @@
import { Request, Response, NextFunction } from "express";
import FileManager from "./data/FileManager.ts";
import TokenManager from "./api/TokenManager.ts";
import UserChatLinker from "./data/UserChatLinker.ts";
import fileUpload from "express-fileupload";
export class Middleware {
static Authroize(req: Request, res: Response, chat_id: string | undefined) {
const userToken = TokenManager.decode(req.headers.token || req.cookies.token);
if (!TokenManager.checkToken(userToken, req.headers["device-id"] || req.cookies.device_id)) {
res.status(401).send({
msg: "401 UnAuthorized",
});
return false;
}
if (chat_id && !UserChatLinker.checkUserIsLinkedToChat(userToken.author, chat_id)) {
res.status(403).send({
msg: "403 Forbidden",
});
return false;
}
return true;
}
static Get_uploaded_files(req: Request, res: Response, next: NextFunction) {
const hash = req.params.hash as string;
if (hash == null) {
res.status(404).send({
msg: "404 Not Found",
});
return;
}
const file = FileManager.findByHash(hash);
if (file == null) {
res.status(404).send({
msg: "404 Not Found",
});
return;
}
if (file.getChatId() != null) {
if (!Middleware.Authroize(req, res, file.getChatId() as string)) {
return;
}
}
next();
}
static Post_upload_file(req: Request, res: Response, next: NextFunction) {
if (!Middleware.Authroize(req, res, req.body.chat_id)) {
return;
}
const file = req.files?.file as fileUpload.UploadedFile;
if (file?.data == null) {
res.status(400).send({
msg: "No file was found or multiple files were uploaded",
});
return;
}
if (req.body.file_name == null) {
res.status(400).send({
msg: "Filename is required",
});
return;
}
}
}