From 2ab91e363f9b9ecf17c96436ab2685854f7c32f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Tue, 7 May 2024 21:06:04 +0800 Subject: [PATCH] feat: auth api router --- src/webui/index.ts | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/src/webui/index.ts b/src/webui/index.ts index 0720b479..926c3709 100644 --- a/src/webui/index.ts +++ b/src/webui/index.ts @@ -1,6 +1,9 @@ import express from 'express'; +import { NextFunction, Request, Response } from 'express'; +import { AuthHelper } from './src/helper/SignToken'; import { resolve } from 'node:path'; import { APIRouter } from './src/router'; +import { WebUIConfig } from './src/helper/config'; const app = express(); /** * 初始化并启动WebUI服务。 @@ -9,7 +12,9 @@ const app = express(); * @returns {Promise} 无返回值。 */ export async function InitWebUi() { + let config = await WebUIConfig(); app.use(express.json()); + app.use(AuthApi); // 初始服务 app.all('/', (_req, res) => { res.json({ @@ -20,8 +25,37 @@ export async function InitWebUi() { app.use('/webui', express.static(resolve(__dirname, './static'))); //挂载API接口 app.all('/api', APIRouter); - app.listen(6099, async () => { - //console.log(`WebUi is running at IP:6099`); + app.listen(config.port, async () => { + console.log(`[NapCat] [WebUi] Current WebUi is running at IP:6099`); }) } +export async function AuthApi(req: Request, res: Response, next: NextFunction) { + //判断当前url是否为/api/login 如果是跳过鉴权 + try { + if (req.url == '/api/login') { + next(); + return; + } + if (req.headers?.authorization) { + let token = req.headers?.authorization.split(' ')[1]; + let Credential = JSON.parse(Buffer.from(token, 'base64').toString('utf-8')); + let credentialJson = await AuthHelper.checkCredential(Credential); + if (credentialJson) { + next(); + } + res.json({ + code: -1, + msg: 'Unauthorized', + }); + return; + } + } catch (e: any) { + res.json({ + code: -1, + msg: 'Server Error', + }); + return; + } + return; +} \ No newline at end of file