Skip to content

Commit 78be5e5

Browse files
committed
chore: Disable security for a specific controller method in NestJS Swagger
1 parent a9a6aad commit 78be5e5

File tree

6 files changed

+82
-55
lines changed

6 files changed

+82
-55
lines changed

src/core/backends/_dto/execute-job.dto.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ export class ExecuteJobDto {
99
public action: ActionType;
1010

1111
@IsMongoId()
12+
@IsOptional()
1213
@ApiProperty({ example: 'paul.bismuth', description: 'User object id', type: String })
13-
public id: string;
14+
public id?: string;
1415

1516
@IsOptional()
1617
@IsObject()

src/core/backends/_interfaces/execute-job-options.interface.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { Types } from 'mongoose';
44
export interface ExecuteJobOptions {
55
job?: JobsOptions;
66
async?: boolean;
7+
disableLogs?: boolean;
78
syncTimeout?: number;
89
timeoutDiscard?: boolean;
910
comment?: string;

src/core/backends/backends.controller.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ export class BackendsController {
7171
@Body() body: ExecuteJobDto,
7272
@Query('async') asyncQuery: string,
7373
@Query('timeoutDiscard') timeoutDiscardQuery: string,
74+
@Query('disableLogs') disableLogsQuery: string,
7475
@Query(
7576
'syncTimeout',
7677
new ParseIntPipe({
@@ -82,14 +83,16 @@ export class BackendsController {
8283
): Promise<Response> {
8384
const async = /true|on|yes|1/i.test(asyncQuery);
8485
const timeoutDiscard = /true|on|yes|1/i.test(timeoutDiscardQuery);
86+
const disableLogs = /true|on|yes|1/i.test(disableLogsQuery);
8587
const [job, response] = await this.backendsService.executeJob(
8688
body.action,
87-
new Types.ObjectId(body.id),
89+
body.id ? new Types.ObjectId(body.id) : null,
8890
body.payload,
8991
{
9092
async,
9193
syncTimeout,
9294
timeoutDiscard,
95+
disableLogs,
9396
},
9497
);
9598
return res.status(HttpStatus.ACCEPTED).json({ async, job, response });

src/core/backends/backends.service.ts

Lines changed: 69 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,22 @@ import {
33
HttpException,
44
HttpStatus,
55
Injectable,
6+
NotFoundException,
67
UnprocessableEntityException,
78
} from '@nestjs/common';
89
import { ModuleRef } from '@nestjs/core';
9-
import { Types } from 'mongoose';
10+
import { Document, ModifyResult, Query, Types } from 'mongoose';
1011
import { AbstractQueueProcessor } from '~/_common/abstracts/abstract.queue.processor';
1112
import { IdentityState } from '~/management/identities/_enums/states.enum';
1213
import { Identities } from '~/management/identities/_schemas/identities.schema';
1314
import { IdentitiesService } from '~/management/identities/identities.service';
1415
import { JobState } from '../jobs/_enums/state.enum';
1516
import { Jobs } from '../jobs/_schemas/jobs.schema';
1617
import { JobsService } from '../jobs/jobs.service';
18+
import { Tasks } from '../tasks/_schemas/tasks.schema';
1719
import { TasksService } from '../tasks/tasks.service';
1820
import { ActionType } from './_enum/action-type.enum';
1921
import { ExecuteJobOptions } from './_interfaces/execute-job-options.interface';
20-
import { Tasks } from '../tasks/_schemas/tasks.schema';
2122

2223
const DEFAULT_SYNC_TIMEOUT = 30_000;
2324

@@ -115,7 +116,7 @@ export class BackendsService extends AbstractQueueProcessor {
115116
},
116117
{ upsert: true, new: true },
117118
);
118-
console.log('completedJob', completedJob);
119+
119120
await this.identitiesService.model.findByIdAndUpdate(completedJob?.concernedTo?.id, {
120121
$set: {
121122
state: IdentityState.SYNCED,
@@ -205,7 +206,7 @@ export class BackendsService extends AbstractQueueProcessor {
205206

206207
public async executeJob(
207208
actionType: ActionType,
208-
concernedTo: Types.ObjectId,
209+
concernedTo?: Types.ObjectId,
209210
// eslint-disable-next-line @typescript-eslint/no-unused-vars
210211
payload?: Record<string | number, any>,
211212
options?: ExecuteJobOptions,
@@ -223,63 +224,82 @@ export class BackendsService extends AbstractQueueProcessor {
223224
optionals['processedAt'] = new Date();
224225
optionals['state'] = JobState.IN_PROGRESS;
225226
}
226-
const identity = await this.identitiesService.findById<Identities>(concernedTo);
227-
const jobStore = await this.jobsService.create<Jobs>({
228-
jobId: job.id,
229-
action: actionType,
230-
params: payload,
231-
concernedTo: {
232-
$ref: 'identities',
233-
id: concernedTo,
234-
name: [identity.inetOrgPerson?.cn, identity.inetOrgPerson?.givenName].join(' '),
235-
},
236-
comment: options?.comment,
237-
task: options?.task,
238-
state: JobState.CREATED,
239-
...optionals,
240-
});
241-
await this.identitiesService.model.findByIdAndUpdate(concernedTo, {
242-
$set: {
243-
state: IdentityState.PROCESSING,
244-
},
245-
});
227+
228+
let jobStore: Document<Jobs> = null;
229+
if (!options?.disableLogs) {
230+
const identity = concernedTo ? await this.identitiesService.findById<Identities>(concernedTo) : null;
231+
jobStore = await this.jobsService.create<Jobs>({
232+
jobId: job.id,
233+
action: actionType,
234+
params: payload,
235+
concernedTo: identity ? {
236+
$ref: 'identities',
237+
id: concernedTo,
238+
name: [identity?.inetOrgPerson?.cn, identity?.inetOrgPerson?.givenName].join(' '),
239+
} : null,
240+
comment: options?.comment,
241+
task: options?.task,
242+
state: JobState.CREATED,
243+
...optionals,
244+
});
245+
}
246+
247+
if (concernedTo) {
248+
await this.identitiesService.model.findByIdAndUpdate(concernedTo, {
249+
$set: {
250+
state: IdentityState.PROCESSING,
251+
},
252+
});
253+
}
254+
246255
if (!options?.async) {
247256
let error: Error;
248257
try {
249258
const response = await job.waitUntilFinished(this.queueEvents, options.syncTimeout || DEFAULT_SYNC_TIMEOUT);
250-
const jobStoreUpdated = await this.jobsService.update<Jobs>(jobStore._id, {
259+
let jobStoreUpdated: ModifyResult<Query<Jobs, Jobs>> = null;
260+
if (!options?.disableLogs) {
261+
jobStoreUpdated = await this.jobsService.update<Jobs>(jobStore._id, {
262+
$set: {
263+
state: JobState.COMPLETED,
264+
processedAt: new Date(),
265+
finishedAt: new Date(),
266+
result: response,
267+
},
268+
});
269+
}
270+
if (concernedTo) {
271+
await this.identitiesService.model.findByIdAndUpdate(concernedTo, {
272+
$set: {
273+
state: IdentityState.SYNCED,
274+
},
275+
});
276+
}
277+
return [jobStoreUpdated as unknown as Jobs, response];
278+
} catch (err) {
279+
error = err;
280+
}
281+
282+
let jobFailed: ModifyResult<Query<Jobs, Jobs>> = null;
283+
if (!options?.disableLogs) {
284+
jobFailed = await this.jobsService.update<Jobs>(jobStore._id, {
251285
$set: {
252-
state: JobState.COMPLETED,
253-
processedAt: new Date(),
286+
state: JobState.FAILED,
254287
finishedAt: new Date(),
255-
result: response,
288+
result: {
289+
error: {
290+
message: error.message,
291+
},
292+
},
256293
},
257294
});
295+
}
296+
if (concernedTo) {
258297
await this.identitiesService.model.findByIdAndUpdate(concernedTo, {
259298
$set: {
260-
state: IdentityState.SYNCED,
299+
state: IdentityState.ON_ERROR,
261300
},
262301
});
263-
return [jobStoreUpdated as unknown as Jobs, response];
264-
} catch (err) {
265-
error = err;
266302
}
267-
const jobFailed = await this.jobsService.update<Jobs>(jobStore._id, {
268-
$set: {
269-
state: JobState.FAILED,
270-
finishedAt: new Date(),
271-
result: {
272-
error: {
273-
message: error.message,
274-
},
275-
},
276-
},
277-
});
278-
await this.identitiesService.model.findByIdAndUpdate(concernedTo, {
279-
$set: {
280-
state: IdentityState.ON_ERROR,
281-
},
282-
});
283303
if (options?.timeoutDiscard !== false) {
284304
job.discard();
285305
throw new BadRequestException({
@@ -296,6 +316,6 @@ export class BackendsService extends AbstractQueueProcessor {
296316
job: jobFailed as unknown as Jobs,
297317
});
298318
}
299-
return [jobStore.toObject(), null];
319+
return [jobStore?.toObject() || null, null];
300320
}
301321
}

src/core/jobs/_schemas/jobs.schema.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ export class Jobs extends AbstractSchema {
2222

2323
@Prop({
2424
type: ConcernedToPartSchema,
25-
required: true,
2625
})
2726
public concernedTo?: ConcernedToPart;
2827

src/core/jobs/jobs.controller.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { Controller, Get, HttpStatus, Param, Res } from '@nestjs/common';
1+
import { Controller, Get, HttpStatus, Param, Req, Res } from '@nestjs/common';
22
import { ApiParam, ApiTags } from '@nestjs/swagger';
33
import { FilterOptions, FilterSchema, SearchFilterOptions, SearchFilterSchema } from '@streamkits/nestjs_module_scrud';
4-
import { Response } from 'express';
4+
import { Request, Response } from 'express';
55
import { Types } from 'mongoose';
66
import { AbstractController } from '~/_common/abstracts/abstract.controller';
77
import { ApiPaginatedDecorator } from '~/_common/decorators/api-paginated.decorator';
@@ -12,7 +12,7 @@ import { PartialProjectionType } from '~/_common/types/partial-projection.type';
1212
import { JobsDto } from './_dto/jobs.dto';
1313
import { JobsService } from './jobs.service';
1414

15-
@ApiTags('core')
15+
@ApiTags('core/jobs')
1616
@Controller('jobs')
1717
export class JobsController extends AbstractController {
1818
protected static readonly projection: PartialProjectionType<JobsDto & { metadata: any }> = {
@@ -32,9 +32,12 @@ export class JobsController extends AbstractController {
3232
@ApiPaginatedDecorator(PickProjectionHelper(JobsDto, JobsController.projection))
3333
public async search(
3434
@Res() res: Response,
35+
@Req() req: Request,
3536
@SearchFilterSchema({ unsafe: true }) searchFilterSchema: FilterSchema,
3637
@SearchFilterOptions() searchFilterOptions: FilterOptions,
3738
): Promise<Response> {
39+
console.log('req', req.query)
40+
3841
//TODO: search tree by parentId
3942
const [data, total] = await this._service.findAndCount(
4043
searchFilterSchema,

0 commit comments

Comments
 (0)