fix: close permission review gaps

This commit is contained in:
2026-07-23 12:23:33 +08:00
parent c98d37307e
commit f39136d9ce
10 changed files with 116 additions and 92 deletions

View File

@@ -54,14 +54,12 @@ describe('permission state', () => {
expect(container?.textContent).toContain('编辑学生');
});
it('fails closed after profile refresh failure', async () => {
it('stays fail-closed while profile verification is retried after a failure', async () => {
writePermissions(['student:edit']);
beginPermissionVerification();
clearPermissions('ready');
expect(readPermissionState()).toEqual({ permissions: [], status: 'ready' });
expect(readPermissionState()).toEqual({ permissions: [], status: 'loading' });
await renderPermissionButton();
expect(container?.textContent).not.toContain('编辑学生');
expect(localStorage.getItem('permissions')).toBeNull();
});
});

View File

@@ -1401,9 +1401,12 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
onClose,
}) => {
const { hasPermission, hasAnyPermission } = usePermission();
const canViewOrganizations = hasPermission('organization:view');
const canChooseOrganization =
canViewOrganizations && hasAnyPermission('student:create', 'student:edit');
const canLoadOrganizations = hasAnyPermission(
'organization:view',
'student:create',
'student:edit',
);
const canChooseOrganization = hasAnyPermission('student:create', 'student:edit');
const [aggregateData, setAggregateData] = useState<StudentProfileAggregate | null>(null);
const [organizations, setOrganizations] = useState<Array<{ id: number; name: string }>>([]);
const [loading, setLoading] = useState(false);
@@ -1426,7 +1429,7 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
}, [fetchData]);
useEffect(() => {
if (!canViewOrganizations) {
if (!canLoadOrganizations) {
setOrganizations([]);
return;
}
@@ -1436,7 +1439,7 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
setOrganizations(res as Array<{ id: number; name: string }>);
})
.catch(() => {});
}, [canViewOrganizations]);
}, [canLoadOrganizations]);
const handlePreviewReport = useCallback(async () => {
try {

View File

@@ -86,25 +86,57 @@ const MainLayout: React.FC = () => {
useEffect(() => {
let cancelled = false;
beginPermissionVerification();
api
.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>(
'/auth/profile',
)
.then((profile) => {
if (cancelled) return;
writePermissions(profile.permissions || []);
const cachedUser = JSON.parse(localStorage.getItem('user') || '{}');
const nextUser = { ...cachedUser, ...profile };
localStorage.setItem('user', JSON.stringify(nextUser));
setUser(nextUser);
})
.catch(() => {
if (!cancelled) clearPermissions('ready');
// The API interceptor handles expired/invalid sessions.
});
let retryTimer: number | undefined;
let verificationInFlight = false;
const verifyPermissions = () => {
if (cancelled || verificationInFlight || !localStorage.getItem('token')) return;
if (retryTimer !== undefined) {
window.clearTimeout(retryTimer);
retryTimer = undefined;
}
verificationInFlight = true;
beginPermissionVerification();
api
.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>(
'/auth/profile',
)
.then((profile) => {
if (cancelled) return;
verificationInFlight = false;
writePermissions(profile.permissions || []);
const cachedUser = JSON.parse(localStorage.getItem('user') || '{}');
const nextUser = { ...cachedUser, ...profile };
localStorage.setItem('user', JSON.stringify(nextUser));
setUser(nextUser);
})
.catch(() => {
verificationInFlight = false;
if (cancelled || !localStorage.getItem('token')) return;
retryTimer = window.setTimeout(verifyPermissions, 5_000);
});
};
const handleStorage = (event: StorageEvent) => {
if (event.key !== 'token' && event.key !== 'permissions') return;
beginPermissionVerification();
window.location.reload();
};
const handleOnline = () => verifyPermissions();
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') verifyPermissions();
};
verifyPermissions();
window.addEventListener('storage', handleStorage);
window.addEventListener('online', handleOnline);
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
cancelled = true;
if (retryTimer !== undefined) window.clearTimeout(retryTimer);
window.removeEventListener('storage', handleStorage);
window.removeEventListener('online', handleOnline);
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);

View File

@@ -1146,9 +1146,9 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
value={studentSearch}
onChange={(event) => setStudentSearch(event.target.value)}
/>
<Button icon={<ExportOutlined />} onClick={handleExport}>
<PermissionButton permission="attendance:export" icon={<ExportOutlined />} onClick={handleExport}>
</Button>
</PermissionButton>
</div>
</header>
<div className="student-legend">

View File

@@ -85,10 +85,15 @@ interface StudentFilterLookups {
const StudentsPage: React.FC = () => {
const { modal } = App.useApp();
const { hasPermission, hasAnyPermission } = usePermission();
const { hasPermission, hasAnyPermission, hasAllPermissions } = usePermission();
const canViewOrganizations = hasPermission('organization:view');
const canChooseOrganization =
canViewOrganizations && hasAnyPermission('student:create', 'student:edit');
const canLoadOrganizations = hasAnyPermission(
'organization:view',
'student:create',
'student:edit',
);
const canChooseOrganization = hasAnyPermission('student:create', 'student:edit');
const canSyncJinshuju = hasAllPermissions('sync:read', 'sync:trigger');
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
@@ -194,7 +199,7 @@ const StudentsPage: React.FC = () => {
}, [fetchData]);
useEffect(() => {
if (canViewOrganizations) {
if (canLoadOrganizations) {
api
.get('/organizations', { params: { includeArchived: 'false' } })
.then((res: unknown) => {
@@ -212,7 +217,7 @@ const StudentsPage: React.FC = () => {
setTeacherOptions(res.teachers || []);
})
.catch(() => {});
}, [canViewOrganizations]);
}, [canLoadOrganizations]);
const handleSave = async () => {
const values = await form.validateFields();
setSaving(true);
@@ -814,13 +819,11 @@ const StudentsPage: React.FC = () => {
</Upload>
</>
) : null}
<PermissionButton
permission="sync:read"
icon={<CloudUploadOutlined />}
onClick={() => setJinshujuOpen(true)}
>
</PermissionButton>
{canSyncJinshuju ? (
<Button icon={<CloudUploadOutlined />} onClick={() => setJinshujuOpen(true)}>
</Button>
) : null}
<PermissionButton
permission="student:view"
icon={<DownloadOutlined />}
@@ -1007,7 +1010,7 @@ const StudentsPage: React.FC = () => {
</Form>
</Modal>
{hasPermission('sync:read') ? (
{canSyncJinshuju ? (
<JinshujuMatchModal
open={jinshujuOpen}
onClose={() => setJinshujuOpen(false)}

View File

@@ -0,0 +1,19 @@
import 'reflect-metadata';
import { PERMISSION_KEY } from '../auth/decorators/permission.decorator';
import { OrganizationsController } from './organizations.controller';
describe('OrganizationsController permissions', () => {
it('allows student editors to list organization options', () => {
expect(Reflect.getMetadata(PERMISSION_KEY, OrganizationsController.prototype.findAll)).toEqual([
'organization:view',
'student:create',
'student:edit',
]);
});
it('keeps organization detail restricted to organization viewers', () => {
expect(Reflect.getMetadata(PERMISSION_KEY, OrganizationsController.prototype.findOne)).toEqual([
'organization:view',
]);
});
});

View File

@@ -26,7 +26,7 @@ export class OrganizationsController {
) {}
@Get()
@RequirePermission('organization:view')
@RequirePermission('organization:view', 'student:create', 'student:edit')
findAll(
@Query('includeArchived') includeArchived?: string,
@Query('scope') scope?: 'all' | 'host' | 'external',

View File

@@ -33,9 +33,8 @@ export class CreateStudentDto {
@IsString()
emergencyPhone?: string;
@IsOptional()
@IsInt()
organizationId?: number;
organizationId: number;
@IsOptional()
@IsString()

View File

@@ -43,21 +43,6 @@ describe('StudentsService — archive lifecycle boundaries', () => {
expect(repo.save).not.toHaveBeenCalled();
});
it('defaults a new student to the active host organization when none is supplied', async () => {
const repo = {
create: jest.fn((value) => value),
save: jest.fn(async (value) => ({ ...value, id: 1 })),
};
const organizationRepo = {
findOne: jest.fn().mockResolvedValue({ id: 7, isHost: true, status: 'active' }),
};
await expect(createService(repo, organizationRepo).create({ name: '张三' })).resolves.toEqual(
expect.objectContaining({ organizationId: 7 }),
);
expect(repo.create).toHaveBeenCalledWith(expect.objectContaining({ organizationId: 7 }));
});
it('returns not found for a missing student', async () => {
const repo = { findOne: jest.fn().mockResolvedValue(null) };
await expect(createService(repo).findOne(404)).rejects.toBeInstanceOf(NotFoundException);
@@ -65,13 +50,11 @@ describe('StudentsService — archive lifecycle boundaries', () => {
it('builds export archive maps from profile and result rows', async () => {
const profileRepo = {
find: jest.fn().mockResolvedValue([
{
studentId: 1,
targetCollege: '北京大学',
collegeSchool: '北京职业技术学院',
},
]),
find: jest.fn().mockResolvedValue([{
studentId: 1,
targetCollege: '北京大学',
collegeSchool: '北京职业技术学院',
}]),
};
const resultRepo = {
find: jest.fn().mockResolvedValue([{ studentId: 1, admissionStatus: 'pending' }]),

View File

@@ -164,9 +164,8 @@ export class StudentsService {
}
async create(dto: CreateStudentDto) {
const organizationId = dto.organizationId || (await this.getHostOrganizationId());
await this.assertActiveOrganization(organizationId);
return this.repo.save(this.repo.create({ ...dto, organizationId }));
await this.assertActiveOrganization(dto.organizationId);
return this.repo.save(this.repo.create(dto));
}
async update(id: number, dto: UpdateStudentDto) {
@@ -315,9 +314,7 @@ export class StudentsService {
};
}
private normalizeImportData(
importData: StudentWorkbookImport | StudentImportRow[],
): StudentWorkbookImport {
private normalizeImportData(importData: StudentWorkbookImport | StudentImportRow[]): StudentWorkbookImport {
if (Array.isArray(importData)) {
return { students: importData, enrollments: [], examScores: [], learningRecords: [] };
}
@@ -373,24 +370,18 @@ export class StudentsService {
if (!phone) return imported;
const enrollmentByClassName = new Map<string, StudentEnrollment>();
for (const enrollmentRow of data.enrollments.filter(
(item) => this.normalizePhone(item.phone) === phone,
)) {
for (const enrollmentRow of data.enrollments.filter((item) => this.normalizePhone(item.phone) === phone)) {
const enrollment = await this.upsertEnrollmentFromImport(studentId, enrollmentRow);
if (!enrollment) continue;
if (enrollment.className) enrollmentByClassName.set(enrollment.className, enrollment);
imported++;
}
for (const examRow of data.examScores.filter(
(item) => this.normalizePhone(item.phone) === phone,
)) {
for (const examRow of data.examScores.filter((item) => this.normalizePhone(item.phone) === phone)) {
if (await this.upsertExamScoreFromImport(studentId, examRow, enrollmentByClassName)) {
imported++;
}
}
for (const learningRow of data.learningRecords.filter(
(item) => this.normalizePhone(item.phone) === phone,
)) {
for (const learningRow of data.learningRecords.filter((item) => this.normalizePhone(item.phone) === phone)) {
if (await this.upsertLearningRecordFromImport(studentId, learningRow)) {
imported++;
}
@@ -399,9 +390,7 @@ export class StudentsService {
}
private async upsertProfileFromImport(studentId: number, row: StudentImportRow) {
const entity =
(await this.profileRepo.findOne({ where: { studentId } })) ||
this.profileRepo.create({ studentId });
const entity = (await this.profileRepo.findOne({ where: { studentId } })) || this.profileRepo.create({ studentId });
if (row.targetCollege?.trim()) entity.targetCollege = row.targetCollege.trim();
if (row.targetMajor?.trim()) entity.targetMajor = row.targetMajor.trim();
if (row.collegeSchool?.trim()) entity.collegeSchool = row.collegeSchool.trim();
@@ -414,12 +403,9 @@ export class StudentsService {
}
private async upsertResultFromImport(studentId: number, row: StudentImportRow) {
const entity =
(await this.resultRepo.findOne({ where: { studentId } })) ||
this.resultRepo.create({ studentId });
const entity = (await this.resultRepo.findOne({ where: { studentId } })) || this.resultRepo.create({ studentId });
if (row.cultureFinalScore !== undefined) entity.cultureFinalScore = row.cultureFinalScore;
if (row.professionalFinalScore !== undefined)
entity.professionalFinalScore = row.professionalFinalScore;
if (row.professionalFinalScore !== undefined) entity.professionalFinalScore = row.professionalFinalScore;
if (row.admissionStatus?.trim()) entity.admissionStatus = row.admissionStatus.trim();
if (row.admittedCollege?.trim()) entity.admittedCollege = row.admittedCollege.trim();
if (row.admittedMajor?.trim()) entity.admittedMajor = row.admittedMajor.trim();
@@ -637,9 +623,10 @@ export class StudentsService {
// ---- Filters ----
if (query?.keyword) {
qb.andWhere('(student.name LIKE :keyword OR student.studentNo LIKE :keyword)', {
keyword: `%${query.keyword}%`,
});
qb.andWhere(
'(student.name LIKE :keyword OR student.studentNo LIKE :keyword)',
{ keyword: `%${query.keyword}%` },
);
}
if (query?.organizationId) {
qb.andWhere('student.organizationId = :orgId', { orgId: query.organizationId });