Compare commits
3 Commits
5d36226b02
...
628a6fee80
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
628a6fee80 | ||
|
|
448acfc26a | ||
|
|
b895f8f247 |
@@ -1,5 +1,6 @@
|
||||
// api/example.js
|
||||
module.exports = (ctx) => {
|
||||
|
||||
|
||||
ctx.body = {
|
||||
message: 'Example POST API',
|
||||
data: ctx.request.body
|
||||
11
app.js
11
app.js
@@ -18,7 +18,7 @@ const loadAPIRoutes = () => {
|
||||
|
||||
files.forEach((file) => {
|
||||
if (file.endsWith(".js") && file !== "index.js") {
|
||||
const routePath = `/${file.replace(".js", "")}`;
|
||||
const routePath = `/api/${file.replace(".js", "")}`;
|
||||
const handler = require(path.join(apiDir, file));
|
||||
|
||||
router.post(routePath, async (ctx) => {
|
||||
@@ -33,13 +33,6 @@ router.get("/public", (ctx) => {
|
||||
ctx.body = "Public content";
|
||||
});
|
||||
|
||||
// 登录路由
|
||||
router.post("/login", (ctx) => {
|
||||
const user = { id: 1, username: "admin" };
|
||||
const token = jwt.sign(user, process.env.JWT_SECRET, { expiresIn: "1h" });
|
||||
ctx.body = { token };
|
||||
});
|
||||
|
||||
// 自定义中间件:解析并验证第三方Token
|
||||
app.use(async (ctx, next) => {
|
||||
const authHeader = ctx.headers.authorization;
|
||||
@@ -49,7 +42,7 @@ app.use(async (ctx, next) => {
|
||||
// 这里假设第三方Token可以通过某种方式验证并转换为JWT Token
|
||||
const decoded = verifyThirdPartyToken(thirdPartyToken); // 假设有一个验证函数
|
||||
const jwtToken = jwt.sign(decoded, process.env.JWT_SECRET, { expiresIn: "1h" });
|
||||
ctx.state.user = user; // 将用户信息存储在ctx.state中
|
||||
ctx.state.user = decoded; // 将用户信息存储在ctx.state中
|
||||
ctx.headers.authorization = `Bearer ${jwtToken}`; // 替换为JWT Token
|
||||
} catch (err) {
|
||||
ctx.throw(401, 'Invalid third-party token');
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
module.exports = token=>{
|
||||
return {token}
|
||||
}
|
||||
module.exports = (token) => {
|
||||
return { token, username: token };
|
||||
};
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
"description": "",
|
||||
"main": "app.js",
|
||||
"scripts": {
|
||||
"start": "node app.js"
|
||||
"start": "node app.js",
|
||||
"dev": "nodemon app.js"
|
||||
},
|
||||
"author": "kubbo",
|
||||
"license": "ISC",
|
||||
@@ -14,6 +15,7 @@
|
||||
"koa": "^2.15.4",
|
||||
"koa-bodyparser": "^4.4.1",
|
||||
"koa-jwt": "^4.0.4",
|
||||
"koa-router": "^13.0.1"
|
||||
"koa-router": "^13.0.1",
|
||||
"nodemon": "^3.0.2"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user