Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/plus #13

Merged
merged 3 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,19 @@ const filesRouter = require("./routers/files");
const usersRouter = require("./routers/users");
const redisClient = require("./redis");
const authenticateToken = require("./middleware/authenticateToken");
const cors = require("@koa/cors");

require("dotenv").config({ path: ".env.local" });

const app = new Koa();

app.use(
cors({
origin: "http://localhost:5173/", // 允许的来源
allowMethods: ["GET", "POST"], // 允许的方法
})
);

app.use(require("koa-static")(path.join(__dirname, "public")));

const createDirectories = () => {
Expand Down
22 changes: 20 additions & 2 deletions middleware/authenticateToken.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,40 @@ require("dotenv").config({ path: ".env.local" });
const redisClient = require("../redis");
const jwt = require("jsonwebtoken");
const { promisify } = require("util");
const { match } = require("path-to-regexp");

// 白名单配置 URL: Method
const whiteList = {
"/login": "POST", // 登录
"/register": "POST", // 注册
"/files/:id/preview": "GET", // 文件预览
};

// 路径匹配函数
const isWhitelisted = (url, method) => {
for (const path in whiteList) {
const matcher = match(path, { decode: decodeURIComponent });
if (matcher(url) && whiteList[path] === method) {
return true;
}
}
return false;
};

const authenticateToken = async (ctx, next) => {
const isWhite = whiteList[ctx.url];
if (isWhite === ctx.method) {
if (isWhitelisted(ctx.path, ctx.method)) {
await next();
return;
}

try {
const token = ctx.headers["authorization"]?.replace("Bearer ", "");
if (!token) {
ctx.status = 403;
ctx.body = { message: "Not Logged In" };
return;
}

const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);

if (!decoded.id) {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"koa2-cors": "^2.0.6",
"mysql2": "^3.10.1",
"nodemon": "^3.1.4",
"path-to-regexp": "^7.0.0",
"pm2": "^5.4.0",
"redis": "^4.6.13",
"sequelize": "^6.37.3",
Expand Down
Empty file added routers/dashboard.js
Empty file.
Loading