61 lines
1.9 KiB
JavaScript
61 lines
1.9 KiB
JavaScript
const User = require('../models/User');
|
||
const Student = require('../models/Student');
|
||
|
||
class AuthService {
|
||
static async login(id, password, role) {
|
||
const user = await User.findByIdAndRole(id, role);
|
||
if (!user) {
|
||
throw new Error('用户名或密码错误');
|
||
}
|
||
|
||
const isValid = await User.verifyPassword(password, user.password);
|
||
if (!isValid) {
|
||
throw new Error('用户名或密码错误');
|
||
}
|
||
|
||
const sessionUser = {
|
||
id: user.id,
|
||
name: user.name,
|
||
role: user.role,
|
||
class: user.class
|
||
};
|
||
|
||
if (user.role === 'student') {
|
||
const studentInfo = await Student.findById(user.id); // 这里的 id 既是 users.id 也是 students.id
|
||
if (studentInfo) {
|
||
sessionUser.studentInfo = studentInfo;
|
||
}
|
||
}
|
||
|
||
return sessionUser;
|
||
}
|
||
|
||
static async register(userData) {
|
||
const { id, role, class: userClass } = userData;
|
||
|
||
// 检查是否存在
|
||
const existingUser = await User.findById(id);
|
||
if (existingUser) {
|
||
throw new Error('用户ID已存在');
|
||
}
|
||
|
||
// 创建用户
|
||
const newUser = await User.create(userData);
|
||
|
||
// 如果是学生,需要同步创建 students 表记录
|
||
// 注意:目前的逻辑好像混淆了 users.id 和 students.id,根据之前的 SQL,students.id 是主键且外键关联 users.id
|
||
// 我们假设 users.id 就是学号
|
||
if (role === 'student') {
|
||
// 需要确保 students 表结构匹配
|
||
await db.query(
|
||
'INSERT INTO students (id, name, class) VALUES (?, ?, ?)',
|
||
[id, userData.name, userClass]
|
||
);
|
||
}
|
||
|
||
return newUser;
|
||
}
|
||
}
|
||
|
||
const db = require('../config/database'); // 补充引用
|
||
module.exports = AuthService; |