From aa3e8f2bb6beceba8ac0034dde77aa21451f8f66 Mon Sep 17 00:00:00 2001 From: xion Date: Thu, 21 Nov 2024 02:09:05 +0800 Subject: [PATCH] =?UTF-8?q?perf=EF=BC=9A=E4=BC=98=E5=8C=96=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 4 +++- src/index.ts | 2 +- src/routes-simple/middleware/auth.ts | 24 ++++++++++++++++++++++++ src/{lib => routes-simple}/upload.ts | 1 + 4 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 src/routes-simple/middleware/auth.ts rename src/{lib => routes-simple}/upload.ts (99%) diff --git a/package.json b/package.json index 28d93fa..b1bc8c4 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,9 @@ "keywords": [], "types": "types/index.d.ts", "files": [ - "types" + "types", + "dist", + "src" ], "license": "UNLICENSED", "dependencies": { diff --git a/src/index.ts b/src/index.ts index 4a60057..5142ac5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,7 +3,7 @@ import { app } from './app.ts'; import './route.ts'; const config = useConfig(); // import { app as aiApp } from '@kevisual/ai-lang/src/index.ts'; -import { uploadMiddleware } from './lib/upload.ts'; +import { uploadMiddleware } from './routes-simple/upload.ts'; import { loadApps } from './load-apps.ts'; // export { aiApp }; export { app }; diff --git a/src/routes-simple/middleware/auth.ts b/src/routes-simple/middleware/auth.ts new file mode 100644 index 0000000..812643c --- /dev/null +++ b/src/routes-simple/middleware/auth.ts @@ -0,0 +1,24 @@ +import { User } from '@/models/user.ts'; +import http from 'http'; + +export const error = (msg: string, code = 500) => { + return JSON.stringify({ code, message: msg }); +}; +export const checkAuth = async (req: http.IncomingMessage, res: http.ServerResponse) => { + const authroization = req.headers?.['authorization'] as string; + if (!authroization) { + res.statusCode = 401; + res.end(error('Invalid authorization')); + return { tokenUser: null, token: null }; + } + const token = authroization.split(' ')[1]; + let tokenUser; + try { + tokenUser = await User.verifyToken(token); + } catch (e) { + res.statusCode = 401; + res.end(error('Invalid token')); + return { tokenUser: null, token: null }; + } + return { tokenUser, token }; +}; diff --git a/src/lib/upload.ts b/src/routes-simple/upload.ts similarity index 99% rename from src/lib/upload.ts rename to src/routes-simple/upload.ts index 479eea7..c6314f7 100644 --- a/src/lib/upload.ts +++ b/src/routes-simple/upload.ts @@ -21,6 +21,7 @@ const cacheFilePath = useFileStore('cache-file', { needExists: true }); let clients = []; const router = new SimpleRouter(); + const error = (msg: string, code = 500) => { return JSON.stringify({ code, message: msg }); };