Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CrudRequest } from '@dataui/crud';
import { ADMIN_FILTER, NO_DATA_FILTER } from '@shared/auth/crud-auth.filter';
import { ADMIN_FILTER, CrudAuthFilter } from '@shared/auth/crud-auth.filter';
import { AttendanceCleanupRule } from 'src/db/entities/AttendanceCleanupRule.entity';
import attendanceCleanupRuleConfig from '../attendance-cleanup-rule.config';

Expand All @@ -16,24 +16,21 @@ describe('AttendanceCleanupRuleConfig', () => {
});

describe('crudAuth', () => {
it('grants access to a user with the attendanceCleanupRules permission', () => {
const user = { permissions: { attendanceCleanupRules: true } };
expect(attendanceCleanupRuleConfig.crudAuth.filter(user)).toEqual(ADMIN_FILTER);
// Same as most entities: admin sees everything, everyone else sees only their own
// rows. The attendanceCleanupRules permission gates client-side visibility only - it
// must not grant one user's data to another.
it('uses the standard CrudAuthFilter (admin sees all, others see only their own rows)', () => {
expect(attendanceCleanupRuleConfig.crudAuth).toBe(CrudAuthFilter);
});

it('grants access to an admin regardless of the dedicated permission', () => {
it('grants an admin full visibility', () => {
const user = { permissions: { admin: true } };
expect(attendanceCleanupRuleConfig.crudAuth.filter(user)).toEqual(ADMIN_FILTER);
});

it('denies a user lacking the permission (no rows, not a 403)', () => {
const user = { permissions: {} };
expect(attendanceCleanupRuleConfig.crudAuth.filter(user)).toEqual(NO_DATA_FILTER);
});

it('denies a user with no permissions object at all', () => {
const user = {};
expect(attendanceCleanupRuleConfig.crudAuth.filter(user)).toEqual(NO_DATA_FILTER);
it('scopes a non-admin to their own rows', () => {
const user = { id: 38, permissions: {} };
expect(attendanceCleanupRuleConfig.crudAuth.filter(user)).toEqual({ userId: 38 });
});
});

Expand All @@ -54,19 +51,60 @@ describe('AttendanceCleanupRuleConfig', () => {
return { service, jobService };
}

it('enqueues an attendance-cleanup-sweep job scoped to the selected rule ids', async () => {
const { service, jobService } = makeService();
function makeReq(ids: string, rules: Partial<AttendanceCleanupRule>[]) {
// getManyByIds is what actually applies crudAuth's filter (via createBuilder) - it's
// mocked here rather than re-testing that plumbing, which base-entity.service.spec.ts
// already covers directly.
const req = {
auth: { id: 7 },
parsed: { extra: { action: 'runNow', ids: '1,2' } },
auth: { id: -1, permissions: { admin: true } },
parsed: { extra: { action: 'runNow', ids } },
options: {},
} as unknown as CrudRequest;
return req;
}

it("enqueues a job scoped to the resolved rules' own userId", async () => {
const { service, jobService } = makeService();
jest.spyOn(service, 'getManyByIds').mockResolvedValue([
{ id: 1, userId: 38 },
{ id: 2, userId: 38 },
] as any);
const req = makeReq('1,2', []);

const message = await service.doAction(req, {});

expect(jobService.enqueue).toHaveBeenCalledWith(7, 'attendance-cleanup-sweep', { ruleIds: [1, 2] });
expect(service.getManyByIds).toHaveBeenCalledWith(req, [1, 2]);
expect(jobService.enqueue).toHaveBeenCalledTimes(1);
expect(jobService.enqueue).toHaveBeenCalledWith(38, 'attendance-cleanup-sweep', { ruleIds: [1, 2] });
expect(message).toContain('42');
});

it('enqueues nothing when none of the selected ids resolve for this caller', async () => {
const { service, jobService } = makeService();
jest.spyOn(service, 'getManyByIds').mockResolvedValue([]);
const req = makeReq('99', []); // e.g. owned by someone else, filtered out by crudAuth

const message = await service.doAction(req, {});

expect(jobService.enqueue).not.toHaveBeenCalled();
expect(message).toContain('0');
});

it('enqueues one job per distinct owner when the resolved rules span multiple users', async () => {
const { service, jobService } = makeService();
jest.spyOn(service, 'getManyByIds').mockResolvedValue([
{ id: 1, userId: 38 },
{ id: 2, userId: 39 },
] as any);
const req = makeReq('1,2', []);

await service.doAction(req, {});

expect(jobService.enqueue).toHaveBeenCalledTimes(2);
expect(jobService.enqueue).toHaveBeenCalledWith(38, 'attendance-cleanup-sweep', { ruleIds: [1] });
expect(jobService.enqueue).toHaveBeenCalledWith(39, 'attendance-cleanup-sweep', { ruleIds: [2] });
});

it('falls through to the base doAction for unknown actions', async () => {
const { service } = makeService();
const req = {
Expand Down
26 changes: 20 additions & 6 deletions server/src/entity-modules/attendance-cleanup-rule.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { CrudRequest } from '@dataui/crud';
import { Repository } from 'typeorm';
import { getUserIdFromUser } from '@shared/auth/auth.util';
import { CrudAuthWithPermissionsFilter } from '@shared/auth/crud-auth.filter';
import { CrudAuthFilter } from '@shared/auth/crud-auth.filter';
import { BaseEntityService } from '@shared/base-entity/base-entity.service';
import { BaseEntityModuleOptions, Entity, InjectEntityRepository } from '@shared/base-entity/interface';
import { MailSendService } from '@shared/utils/mail/mail-send.service';
Expand All @@ -22,10 +21,22 @@ class AttendanceCleanupRuleService<T extends Entity | AttendanceCleanupRule> ext
const extra = req.parsed.extra as any;
switch (extra.action) {
case 'runNow': {
const userId = getUserIdFromUser(req.auth);
const ruleIds = getAsNumberArray(extra.ids) ?? [];
const job = await this.jobService.enqueue(userId, 'attendance-cleanup-sweep', { ruleIds });
return `נוצרה משימת ניקוי נוכחות (מזהה ${job.id})`;
// getManyByIds applies crudAuth's filter (already merged into req.parsed.search
// by CrudRequestInterceptor) - a non-owned id in the selection simply doesn't
// come back, instead of being trusted from the request.
const rules = (await this.getManyByIds(req, ruleIds)) as unknown as AttendanceCleanupRule[];
// Admin sees everyone, so a selection can still span multiple owners - scope
// each enqueued job to its own rule subset.
const userIds = [...new Set(rules.map((rule) => rule.userId))];
const jobs = await Promise.all(
userIds.map((userId) =>
this.jobService.enqueue(userId, 'attendance-cleanup-sweep', {
ruleIds: rules.filter((rule) => rule.userId === userId).map((rule) => rule.id),
}),
),
);
return `נוצרו ${jobs.length} משימות ניקוי נוכחות (מזהים: ${jobs.map((job) => job.id).join(', ')})`;
}
}
return super.doAction(req, body);
Expand All @@ -35,7 +46,10 @@ class AttendanceCleanupRuleService<T extends Entity | AttendanceCleanupRule> ext
function getConfig(): BaseEntityModuleOptions {
return {
entity: AttendanceCleanupRule,
crudAuth: CrudAuthWithPermissionsFilter(permissions => permissions?.attendanceCleanupRules),
// Same auth as most entities: admin sees everything, everyone else sees only their
// own rows. The attendanceCleanupRules permission only controls whether the client
// shows the resource - it must not grant cross-tenant data visibility.
crudAuth: CrudAuthFilter,
query: {
join: {
lesson: { eager: false },
Expand Down
Loading