commit 4f6d44ec497c1384d4ab25d845fd18939fe4ea8b Author: aixianling Date: Mon Feb 24 17:41:40 2025 +0800 feat: 初始化项目并添加 JWT 认证 - 创建 .gitignore 文件,排除环境变量和节点模块 - 新增 app.js 文件,实现基本的 Koa 应用和 JWT 认证逻辑 - 添加 package.json 文件,定义项目依赖和启动脚本 安装依赖: - dotenv:用于加载环境变量 - jsonwebtoken:用于生成和验证 JWT 令牌 - koa:Koa 应用框架 - koa-jwt:Koa 的 JWT 中间件 - koa-router:Koa 的路由中间件 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" + } +}