forked from xiaoze26/openmd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
96 lines (81 loc) · 2.23 KB
/
auth.js
File metadata and controls
96 lines (81 loc) · 2.23 KB
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
const bcrypt = require('bcryptjs');
const { executeQuery, executeUpdate } = require('./database');
// 注册用户
async function registerUser(username, email, password) {
try {
// 如果没有提供邮箱,使用默认邮箱
const finalEmail = email || `${username}@ai-agent.local`;
// 哈希密码
const hash = await bcrypt.hash(password, 10);
// 插入用户
const result = await executeUpdate(
'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
[username, finalEmail, hash]
);
// MySQL 返回格式:{ insertId: xxx, affectedRows: xxx }
return {
id: result.insertId,
username,
email: finalEmail
};
} catch (error) {
// 处理唯一约束错误
if (error.code === 'ER_DUP_ENTRY' || error.errno === 1062) {
throw new Error('用户名已存在');
}
throw error;
}
}
// 用户登录
async function loginUser(username, password) {
try {
// 查询用户
const rows = await executeQuery(
'SELECT * FROM users WHERE username = ? OR email = ?',
[username, username]
);
if (!rows || rows.length === 0) {
throw new Error('用户不存在');
}
const user = rows[0];
// 验证密码
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
throw new Error('密码错误');
}
// 更新最后登录时间
await executeUpdate(
'UPDATE users SET last_login = NOW() WHERE id = ?',
[user.id]
);
// 返回用户信息(不含密码)
const { password: _, ...userInfo } = user;
return userInfo;
} catch (error) {
if (error.message === '用户不存在' || error.message === '密码错误') {
throw error;
}
throw new Error('登录失败:' + error.message);
}
}
// 根据ID获取用户
async function getUserById(userId) {
try {
const rows = await executeQuery(
'SELECT id, username, email, created_at, last_login FROM users WHERE id = ?',
[userId]
);
if (!rows || rows.length === 0) {
return null;
}
return rows[0];
} catch (error) {
console.error('Error getting user by ID:', error);
return null;
}
}
module.exports = {
registerUser,
loginUser,
getUserById
};