From 4f6d44ec497c1384d4ab25d845fd18939fe4ea8b Mon Sep 17 00:00:00 2001 From: aixianling Date: Mon, 24 Feb 2025 17:41:40 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=88=9D=E5=A7=8B=E5=8C=96=E9=A1=B9?= =?UTF-8?q?=E7=9B=AE=E5=B9=B6=E6=B7=BB=E5=8A=A0=20JWT=20=E8=AE=A4=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 创建 .gitignore 文件,排除环境变量和节点模块 - 新增 app.js 文件,实现基本的 Koa 应用和 JWT 认证逻辑 - 添加 package.json 文件,定义项目依赖和启动脚本 安装依赖: - dotenv:用于加载环境变量 - jsonwebtoken:用于生成和验证 JWT 令牌 - koa:Koa 应用框架 - koa-jwt:Koa 的 JWT 中间件 - koa-router:Koa 的路由中间件 --- .gitignore | 3 +++ app.js | 40 ++++++++++++++++++++++++++++++++++++++++ package.json | 18 ++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 .gitignore create mode 100644 app.js create mode 100644 package.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bbe148e --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +# 环境变量文件 +.env +node_modules/ \ No newline at end of file diff --git a/app.js b/app.js new file mode 100644 index 0000000..67f1f37 --- /dev/null +++ b/app.js @@ -0,0 +1,40 @@ +require('dotenv').config(); // 在文件最顶部加载环境变量 + +const Koa = require('koa'); +const Router = require('koa-router'); +const jwt = require('jsonwebtoken'); +const koaJwt = require('koa-jwt'); + +const app = new Koa(); +const router = new Router(); + +// 公开路由 +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 }; +}); + +// JWT中间件 +app.use(koaJwt({ + secret: process.env.JWT_SECRET +}).unless({ + path: [/^\/public/] +})); + +// 受保护路由 +router.get('/protected', ctx => { + ctx.body = `Protected content for ${ctx.state.user.username}`; +}); + +app.use(router.routes()); +app.use(router.allowedMethods()); + +app.listen(process.env.PORT || 3000, () => { + console.log(`Server running on http://localhost:${process.env.PORT || 3000}`); +}); \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..50f9650 --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "name": "vless-api", + "version": "1.0.0", + "description": "", + "main": "app.js", + "scripts": { + "start": "node app.js" + }, + "author": "kubbo", + "license": "ISC", + "dependencies": { + "dotenv": "^16.4.7", + "jsonwebtoken": "^9.0.2", + "koa": "^2.15.4", + "koa-jwt": "^4.0.4", + "koa-router": "^13.0.1" + } +}