- 新增成绩分析页面,包含GPA趋势图、成绩分布图和学分进度 - 实现学生密码修改功能,包括前端表单和后端验证逻辑 - 添加课程类别分析功能,展示不同类别课程的GPA表现 - 优化学生仪表板和课程页面导航链接 - 增加数据加载状态提示和错误处理
76 lines
2.3 KiB
JavaScript
76 lines
2.3 KiB
JavaScript
const User = require('../models/User');
|
||
const Student = require('../models/Student');
|
||
const db = require('../config/database');
|
||
|
||
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;
|
||
}
|
||
|
||
static async updatePassword(userId, oldPassword, newPassword) {
|
||
const user = await User.findById(userId);
|
||
if (!user) {
|
||
throw new Error('用户不存在');
|
||
}
|
||
|
||
const isValid = await User.verifyPassword(oldPassword, user.password);
|
||
if (!isValid) {
|
||
throw new Error('原密码错误');
|
||
}
|
||
|
||
return await User.updatePassword(userId, newPassword);
|
||
}
|
||
}
|
||
|
||
module.exports = AuthService;
|