fix(authz): 禁止教师通过新建课程自授任课关系

This commit is contained in:
LoveChengke committed 2026-11-07 02:02:01 +08:00
1 parent 71cc8eb605
commit e49dd0bc39
8 files changed
+36 -14

No files matched your search

+7 -1
View File
@@ -697,11 +697,17 @@ async function main() {
const createdCourse = await api('/courses', { const createdCourse = await api('/courses', {
method: 'POST', method: 'POST',
token: teacherToken, token: adminToken,
body: { name: `联调验证课程 ${Date.now()}`, classId }, body: { name: `联调验证课程 ${Date.now()}`, classId },
}); });
const createdCourseId = createdCourse.payload?.data?.id; const createdCourseId = createdCourse.payload?.data?.id;
record('新增课程 POST /courses', createdCourse.status === 201, `status=${createdCourse.status}`); record('新增课程 POST /courses', createdCourse.status === 201, `status=${createdCourse.status}`);
const deniedCourse = await api('/courses', {
method: 'POST',
token: teacherToken,
body: { name: `禁止自授权课程 ${Date.now()}`, classId },
});
record('教师不能通过建课建立任课关系', deniedCourse.status === 403, `status=${deniedCourse.status}`);
if (createdCourseId) { if (createdCourseId) {
const removedCourse = await api(`/courses/${createdCourseId}`, { method: 'DELETE', token: teacherToken }); const removedCourse = await api(`/courses/${createdCourseId}`, { method: 'DELETE', token: teacherToken });
record('删除课程 DELETE /courses/:id', removedCourse.status === 200, `status=${removedCourse.status}`); record('删除课程 DELETE /courses/:id', removedCourse.status === 200, `status=${removedCourse.status}`);
@@ -1,6 +1,11 @@
import { refreshClassSubscriptions } from '../../realtime/bus.js'; import { refreshClassSubscriptions } from '../../realtime/bus.js';
import type { CourseDto } from '@classhelper/shared'; import type { CourseDto } from '@classhelper/shared';
import { assertCanManageSchedule, classScopeWhere, resolveClassScope } from '../../lib/access.js'; import {
assertCanAssignTeachers,
assertCanManageSchedule,
classScopeWhere,
resolveClassScope,
} from '../../lib/access.js';
import { prisma } from '../../lib/db.js'; import { prisma } from '../../lib/db.js';
import { ApiError } from '../../lib/http.js'; import { ApiError } from '../../lib/http.js';
import type { TokenPayload } from '../../lib/jwt.js'; import type { TokenPayload } from '../../lib/jwt.js';
@@ -21,6 +26,9 @@ export async function listCourses(user: TokenPayload, classId?: string): Promise
export async function createCourse(user: TokenPayload, input: CreateCourseInput): Promise<CourseDto> { export async function createCourse(user: TokenPayload, input: CreateCourseInput): Promise<CourseDto> {
await assertCanManageSchedule(user, input.classId); await assertCanManageSchedule(user, input.classId);
// 建课同时建立任课关系,只能由管理员执行,不能凭课表维护范围自授权。
if (user.role !== 'ADMIN') throw ApiError.forbidden('新建科目会建立任课关系,请联系管理员配置');
await assertCanAssignTeachers(user, input.classId);
/* /*
* 同名去重(一个班级里科目名唯一)。 * 同名去重(一个班级里科目名唯一)。
+2 -2
View File
@@ -325,7 +325,7 @@ async function removeStudent(row: StudentDto): Promise<void> {
const courseForm = reactive({ name: '' }); const courseForm = reactive({ name: '' });
async function addCourse(): Promise<void> { async function addCourse(): Promise<void> {
if (!canManageDetailCourses.value) return; if (!auth.isAdmin || !canManageDetailCourses.value) return;
if (!detail.value || !courseForm.name.trim()) { if (!detail.value || !courseForm.name.trim()) {
ElMessage.warning('请输入课程名称'); ElMessage.warning('请输入课程名称');
return; return;
@@ -771,7 +771,7 @@ async function saveSettings() {
</el-table-column> </el-table-column>
</el-table> </el-table>
<el-input <el-input
v-if="canManageDetailCourses" v-if="auth.isAdmin && canManageDetailCourses"
v-model="courseForm.name" v-model="courseForm.name"
placeholder="输入课程名称后回车快速添加" placeholder="输入课程名称后回车快速添加"
class="mt-12" class="mt-12"
+2 -1
View File
@@ -187,6 +187,7 @@ async function onClassChange(): Promise<void> {
const SUBJECT_PREFIX = 'subject:'; const SUBJECT_PREFIX = 'subject:';
const subjectOptions = computed(() => { const subjectOptions = computed(() => {
if (!auth.isAdmin) return [];
const existing = new Set(courses.value.map((item) => item.name)); const existing = new Set(courses.value.map((item) => item.name));
return SUBJECT_CATALOG.filter((name) => !existing.has(name)); return SUBJECT_CATALOG.filter((name) => !existing.has(name));
}); });
@@ -221,7 +222,7 @@ const ownCourses = computed(() =>
); );
/** 能不能在该班新建科目(与课表管理同权限:管理员或本班班主任) */ /** 能不能在该班新建科目(与课表管理同权限:管理员或本班班主任) */
const canCreateCourse = computed(() => auth.canManageClass('schedule:write', filter.classId)); const canCreateCourse = computed(() => auth.isAdmin);
/** 录入弹窗的默认科目:优先沿用页面筛选,但筛的是别人的科目时退回"我的科目"第一条 */ /** 录入弹窗的默认科目:优先沿用页面筛选,但筛的是别人的科目时退回"我的科目"第一条 */
function defaultFormCourseId(): string { function defaultFormCourseId(): string {
@@ -222,6 +222,7 @@ const formCoursesLoading = ref(false);
/** 该班还没有的科目(来自 shared 的 SUBJECT_CATALOG) */ /** 该班还没有的科目(来自 shared 的 SUBJECT_CATALOG) */
const newSubjectOptions = computed(() => { const newSubjectOptions = computed(() => {
if (!auth.isAdmin) return [];
const existing = new Set(formCourses.value.map((item) => item.name)); const existing = new Set(formCourses.value.map((item) => item.name));
return SUBJECT_CATALOG.filter((name) => !existing.has(name)); return SUBJECT_CATALOG.filter((name) => !existing.has(name));
}); });
@@ -237,8 +238,8 @@ const ownFormCourses = computed(() =>
auth.isAdmin ? formCourses.value : formCourses.value.filter((item) => item.teacherId === auth.user?.id), auth.isAdmin ? formCourses.value : formCourses.value.filter((item) => item.teacherId === auth.user?.id),
); );
/** 该班里能不能新建科目:与课表管理同权限(管理员或本班班主任) */ /** 新建科目会建立任课关系,仅管理员可操作。 */
const canCreateCourse = computed(() => auth.canManageClass('schedule:write', form.classId)); const canCreateCourse = computed(() => auth.isAdmin);
async function loadFormCourses(): Promise<void> { async function loadFormCourses(): Promise<void> {
const classId = form.classId; const classId = form.classId;
@@ -325,10 +326,10 @@ async function resolveCourseId(): Promise<string | null> {
await loadFormCourses(); await loadFormCourses();
return reusedId; return reusedId;
} }
// 新建课程需要"管理员或本班班主任"权限(与课表管理一致),科任老师会被 403 拦截 // 新建课程会建立任课关系,统一交给管理员配置。
ElMessage.error( ElMessage.error(
`新建科目「${name}」失败:${ `新建科目「${name}」失败:${
error instanceof Error ? error.message : '仅班主任/管理员可以在班级下新建课程' error instanceof Error ? error.message : '请联系管理员建立科目及任课关系'
},可改用已有课程或直接留空发布`, },可改用已有课程或直接留空发布`,
); );
throw error; throw error;
@@ -622,7 +623,7 @@ function canEditContent(row: HomeworkDto): boolean {
? '正在加载该班课程…' ? '正在加载该班课程…'
: canCreateCourse : canCreateCourse
? '只列你任教的科目;该班还没有的科目在「其他科目(新建)」里,选中后自动建课再发布' ? '只列你任教的科目;该班还没有的科目在「其他科目(新建)」里,选中后自动建课再发布'
: '只列你任教的科目;需要别的科目请先由班主任/管理员在课表管理里建好并分配任课老师' : '只列你任教的科目;需要别的科目请联系管理员建立科目并分配任课老师'
}} }}
</div> </div>
</el-form-item> </el-form-item>
@@ -504,10 +504,10 @@ watch(tab, () => {
selectedLayout.value = plan.value.timeLayoutId; selectedLayout.value = plan.value.timeLayoutId;
}); });
const missingSubjects = computed(() => const missingSubjects = computed(() =>
SUBJECT_CATALOG.filter((name) => !courses.value.some((c) => c.name === name)), auth.isAdmin ? SUBJECT_CATALOG.filter((name) => !courses.value.some((c) => c.name === name)) : [],
); );
async function addSubject(name: string) { async function addSubject(name: string) {
if (!canWrite.value) return; if (!canWrite.value || !auth.isAdmin) return;
try { try {
const created = await courseApi.create({ classId: classId.value, name }); const created = await courseApi.create({ classId: classId.value, name });
courses.value.push(created); courses.value.push(created);
@@ -107,6 +107,7 @@ async function loadCourses(): Promise<void> {
const SUBJECT_PREFIX = 'subject:'; const SUBJECT_PREFIX = 'subject:';
const subjectOptions = computed(() => { const subjectOptions = computed(() => {
if (!auth.isAdmin) return [];
const existing = new Set(courses.value.map((item) => item.name)); const existing = new Set(courses.value.map((item) => item.name));
return SUBJECT_CATALOG.filter((name) => !existing.has(name)); return SUBJECT_CATALOG.filter((name) => !existing.has(name));
}); });
+7 -2
View File
@@ -107,10 +107,15 @@ async function checkClassRelations(win, options, record) {
return { studentWrite: Array.from(drawer.querySelectorAll('#pane-students button')).some(button => button.textContent.trim() === '添加学生'), courseCreate: Boolean(drawer.querySelector('#pane-courses input')), gradeQueryEnabled: !drawer.querySelector('#pane-settings .el-switch')?.classList.contains('is-disabled') }; return { studentWrite: Array.from(drawer.querySelectorAll('#pane-students button')).some(button => button.textContent.trim() === '添加学生'), courseCreate: Boolean(drawer.querySelector('#pane-courses input')), gradeQueryEnabled: !drawer.querySelector('#pane-settings .el-switch')?.classList.contains('is-disabled') };
})()`); })()`);
record( record(
'班主任本人班级仍可维护名单、课程和成绩查询开关', '班主任可维护本班名单和成绩查询开关,但不能通过建课取得任课关系',
owner.studentWrite && owner.courseCreate && owner.gradeQueryEnabled, owner.studentWrite && !owner.courseCreate && owner.gradeQueryEnabled,
JSON.stringify(owner), JSON.stringify(owner),
); );
const created = await request('/courses', admin.token, 'POST', {
classId: other.id,
name: '管理员建课验证',
});
record('管理员仍可建立课程与任课关系', created.status === 201, `status=${created.status}`);
const members = await data('/permissions/users', admin.token); const members = await data('/permissions/users', admin.token);
const previous = members.find((member) => member.id === teacher.user.id).assignments; const previous = members.find((member) => member.id === teacher.user.id).assignments;
const groups = []; const groups = [];