-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
238 lines (223 loc) · 7.22 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
const http = require("http");
const url = require("url");
const mysql = require("mysql2/promise"); // 使用promise版本
const crypto = require("crypto");
const dbConfig = require("./.env.local.js");
const jwt = require("jsonwebtoken");
const handleWrite = require("./user/write");
const { sendJsonResponse } = require("./user/commonConfig");
const getPostList = require("./user/postList.js");
const handlePostDetail = require("./user/postDetail");
const handleDeletePost = require("./user/deletePost");
// 创建MySQL连接池,并禁用SSL验证
const pool = mysql.createPool({
...dbConfig,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
ssl: {
rejectUnauthorized: false, // 禁用SSL证书验证
},
});
// 生成随机盐
function generateSalt() {
return crypto.randomBytes(32).toString("hex");
}
// 哈希密码
async function hashPassword(password, salt) {
const iterations = 10000; // 迭代次数
const keylen = 64; // 密钥长度
return new Promise((resolve, reject) => {
crypto.pbkdf2(
password,
salt,
iterations,
keylen,
"sha256",
(err, derivedKey) => {
if (err) reject(err);
else resolve(derivedKey.toString("hex"));
}
);
});
}
// 验证密码
async function verifyPassword(hashedPassword, password, salt) {
const iterations = 10000; // 迭代次数
const keylen = 64; // 密钥长度
const derivedKey = await new Promise((resolve, reject) => {
crypto.pbkdf2(
password,
salt,
iterations,
keylen,
"sha256",
(err, derivedKey) => {
if (err) reject(err);
else resolve(derivedKey.toString("hex"));
}
);
});
return hashedPassword === derivedKey;
}
// JWT 密钥
const JWT_SECRET = "#Gao_2024-better";
// 创建HTTP服务器
const server = http.createServer(async (req, res) => {
// 设置CORS头以允许跨域
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
// 处理预检请求token
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
// 解析URL
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
// 收集请求体
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", async () => {
try {
const postData = JSON.parse(body); // 解析JSON格式的请求体
switch (pathname) {
case "/user/login":
if (req.method === "POST") {
const { username, password } = postData;
// 确保 username 和 password 都不为 undefined
if (!username || !password) {
return sendJsonResponse(res, 400, {
message: "Username and password are required",
});
}
// 查询数据库
const [rows] = await pool.execute(
"SELECT * FROM users WHERE username = ?",
[username]
);
if (rows.length > 0) {
const user = rows[0];
const isPasswordValid = await verifyPassword(
user.password,
password,
user.salt
);
if (isPasswordValid) {
// 生成 JWT
const token = jwt.sign(
{ id: user.id, username: user.username },
JWT_SECRET,
{ expiresIn: "1h" }
);
sendJsonResponse(res, 200, {
username,
message: "Login successful",
token,
});
} else {
sendJsonResponse(res, 401, { message: "账号密码不一致" });
}
} else {
sendJsonResponse(res, 401, { message: "用户不存在" });
}
} else {
res.writeHead(405, { Allow: "POST" });
res.end("Method Not Allowed");
}
break;
case "/user/register":
if (req.method === "POST") {
const { username, email, password } = postData;
// 确保 username、email 和 password 都不为 undefined
if (!username || !email || !password) {
return sendJsonResponse(res, 400, {
message: "Username, email, and password are required",
});
}
// 生成盐
const salt = generateSalt();
// 生成哈希密码
const hashedPassword = await hashPassword(password, salt);
// 插入到数据库
try {
const [result] = await pool.execute(
"INSERT INTO users (username, email, password, salt) VALUES (?, ?, ?, ?)",
[username, email, hashedPassword, salt]
);
if (result.affectedRows > 0) {
sendJsonResponse(res, 201, {
message: "User registered successfully",
});
} else {
sendJsonResponse(res, 500, {
message: "Internal Server Error",
});
}
} catch (err) {
if (err.code === "ER_DUP_ENTRY") {
sendJsonResponse(res, 409, { message: "User already exists" });
} else {
console.error(err);
sendJsonResponse(res, 500, {
message: "Internal Server Error",
});
}
}
} else {
res.writeHead(405, { Allow: "POST" });
res.end("Method Not Allowed");
}
break;
case "/user/write":
if (req.method === "POST") {
await handleWrite(req, res, postData); // 传递postData给handleWrite
} else {
res.writeHead(405, { Allow: "POST" });
res.end("Method Not Allowed");
}
break;
case "/user/postDetail":
if (req.method === "POST") {
await handlePostDetail(req, res, postData); // 传递postData给handlePost
} else {
res.writeHead(405, { Allow: "POST" });
res.end("Method Not Allowed");
}
break;
case "/user/posts":
if (req.method === "POST") {
await getPostList(req, res, postData); // 传递postData给handlePost
} else {
res.writeHead(405, { Allow: "POST" });
res.end("Method Not Allowed");
}
break;
// 删除文章
case "/user/deletePost":
if (req.method === "POST") {
await handleDeletePost(req, res, postData); // 传递postData给handlePost
} else {
res.writeHead(405, { Allow: "POST" });
res.end("Method Not Allowed");
}
break;
// end
default:
res.writeHead(404);
res.end("Not Found");
}
} catch (err) {
console.error(err);
sendJsonResponse(res, 500, { message: "Internal Server Error" });
}
});
});
// 监听所有网络接口上的3000端口
server.listen(3000, "0.0.0.0", () => {
console.log("Server is listening on port 3000...");
});