Skip to content

Commit

Permalink
Merge pull request #13 from diskcloud/feat/plus
Browse files Browse the repository at this point in the history
Feat/plus
  • Loading branch information
CrazyMrYan authored Jul 1, 2024
2 parents a817597 + e28c47b commit afec33a
Show file tree
Hide file tree
Showing 6 changed files with 272 additions and 202 deletions.
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

0 comments on commit afec33a

Please sign in to comment.