Files
WebWork/backend/services/authService.js
祀梦 b9a975004b feat: 实现成绩管理系统核心功能
添加响应工具、错误处理中间件和数据库模型
创建用户、学生、课程和成绩相关服务
实现管理员、教师和学生控制器的基本功能
重构路由处理并优化数据库查询
2025-12-21 22:10:48 +08:00

61 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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根据之前的 SQLstudents.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;