feat: refactoring casl permission checks for recursive nested operations (#778)

* feat: nested casl abilities

* fix: remove unused packages

* Fixes

* Fix createMany broken

* Fix lint

* Fix lint

* Fix lint

* Fix lint

* Fixes

* Fix CommentThread

* Fix bugs

* Fix lint

* Fix bugs

* Fixed auto routing

* Fixed app path

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
This commit is contained in:
Jérémy M
2023-07-26 01:37:22 +02:00
committed by GitHub
parent 92b9e987a5
commit 51cfc0d82c
69 changed files with 1192 additions and 883 deletions

View File

@ -16,6 +16,7 @@ import {
PipelineStage,
PipelineProgress,
Attachment,
UserSettings,
} from '@prisma/client';
import { AbilityAction } from './ability.action';
@ -34,6 +35,7 @@ type SubjectsAbility = Subjects<{
PipelineStage: PipelineStage;
PipelineProgress: PipelineProgress;
Attachment: Attachment;
UserSettings: UserSettings;
}>;
export type AppAbility = PureAbility<
@ -58,8 +60,9 @@ export class AbilityFactory {
cannot(AbilityAction.Delete, 'User');
// Workspace
can(AbilityAction.Read, 'Workspace', { id: workspace.id });
can(AbilityAction.Update, 'Workspace', { id: workspace.id });
can(AbilityAction.Read, 'Workspace');
can(AbilityAction.Update, 'Workspace');
can(AbilityAction.Delete, 'Workspace');
// Workspace Member
can(AbilityAction.Read, 'WorkspaceMember', { workspaceId: workspace.id });
@ -101,6 +104,7 @@ export class AbilityFactory {
// CommentThreadTarget
can(AbilityAction.Read, 'CommentThreadTarget');
can(AbilityAction.Create, 'CommentThreadTarget');
// Attachment
can(AbilityAction.Read, 'Attachment', { workspaceId: workspace.id });

View File

@ -0,0 +1,207 @@
import { Prisma, PrismaClient } from '@prisma/client';
import { subject } from '@casl/ability';
import { camelCase } from 'src/utils/camel-case';
import { AppAbility } from './ability.factory';
import { AbilityAction } from './ability.action';
type OperationType =
| 'create'
| 'connectOrCreate'
| 'upsert'
| 'createMany'
| 'set'
| 'disconnect'
| 'delete'
| 'connect'
| 'update'
| 'updateMany'
| 'deleteMany';
// in most case unique identifier is the id, but it can be something else...
type OperationAbilityChecker = (
modelName: Prisma.ModelName,
ability: AppAbility,
prisma: PrismaClient,
data: any,
) => Promise<boolean>;
const createAbilityCheck: OperationAbilityChecker = async (
modelName,
ability,
prisma,
data,
) => {
// Handle all operations cases
const items = data?.data
? !Array.isArray(data.data)
? [data.data]
: data.data
: !Array.isArray(data)
? [data]
: data;
// Check if user try to create an element that is not allowed to create
for (const {} of items) {
if (!ability.can(AbilityAction.Create, modelName)) {
return false;
}
}
return true;
};
const simpleAbilityCheck: OperationAbilityChecker = async (
modelName,
ability,
prisma,
data,
) => {
// Extract entity name from model name
const entity = camelCase(modelName);
// Handle all operations cases
const operations = !Array.isArray(data) ? [data] : data;
// Handle where case
const normalizedOperations = operations.map((op) =>
op.where ? op.where : op,
);
// Force entity type because of Prisma typing
const items = await prisma[entity as string].findMany({
where: {
OR: normalizedOperations,
},
});
// Check if user try to connect an element that is not allowed to read
for (const item of items) {
// TODO: Replace user by workspaceMember and remove this check
if (
modelName === 'User' ||
modelName === 'UserSettings' ||
modelName === 'Workspace'
) {
return true;
}
if (!ability.can(AbilityAction.Read, subject(modelName, item))) {
return false;
}
}
return true;
};
const operationAbilityCheckers: Record<OperationType, OperationAbilityChecker> =
{
create: createAbilityCheck,
createMany: createAbilityCheck,
upsert: simpleAbilityCheck,
update: simpleAbilityCheck,
updateMany: simpleAbilityCheck,
delete: simpleAbilityCheck,
deleteMany: simpleAbilityCheck,
connectOrCreate: simpleAbilityCheck,
connect: simpleAbilityCheck,
disconnect: simpleAbilityCheck,
set: simpleAbilityCheck,
};
// Check relation nested abilities
export async function relationAbilityChecker(
modelName: Prisma.ModelName,
ability: AppAbility,
prisma: PrismaClient,
args: any,
) {
// Extract models from Prisma
const models = Prisma.dmmf.datamodel.models;
// Find main model from options
const mainModel = models.find((item) => item.name === modelName);
if (!mainModel) {
throw new Error('Main model not found');
}
// Loop over fields
for (const field of mainModel.fields) {
// Check if field is a relation
if (field.relationName) {
// Check if field is in args
const operation = args.data?.[field.name] ?? args?.[field.name];
if (operation) {
// Extract operation name and value
const operationType = Object.keys(operation)[0] as OperationType;
const operationValue = operation[operationType];
// Get operation checker for the operation type
const operationChecker = operationAbilityCheckers[operationType];
if (!operationChecker) {
throw new Error('Operation not found');
}
// Check if operation is allowed
const allowed = await operationChecker(
field.type as Prisma.ModelName,
ability,
prisma,
operationValue,
);
if (!allowed) {
return false;
}
// For the 'create', 'connectOrCreate', 'upsert', 'update', and 'updateMany' operations,
// we should also check the nested operations.
if (
[
'create',
'connectOrCreate',
'upsert',
'update',
'updateMany',
].includes(operationType)
) {
// Handle nested operations all cases
const operationValues = !Array.isArray(operationValue)
? [operationValue]
: operationValue;
// Loop over nested args
for (const nestedArgs of operationValues) {
const nestedCreateAllowed = await relationAbilityChecker(
field.type as Prisma.ModelName,
ability,
prisma,
nestedArgs.create ?? nestedArgs.data ?? nestedArgs,
);
if (!nestedCreateAllowed) {
return false;
}
if (nestedArgs.update) {
const nestedUpdateAllowed = await relationAbilityChecker(
field.type as Prisma.ModelName,
ability,
prisma,
nestedArgs.update,
);
if (!nestedUpdateAllowed) {
return false;
}
}
}
}
}
}
}
return true;
}

View File

@ -42,7 +42,7 @@ export class CreateAttachmentAbilityHandler implements IAbilityHandler {
const args = gqlContext.getArgs<AttachmentArgs>();
assert(args.activityId, '', ForbiddenException);
const activity = await this.prismaService.commentThread.findUnique({
const activity = await this.prismaService.client.commentThread.findUnique({
where: { id: args.activityId },
include: { workspace: true },
});

View File

@ -13,10 +13,12 @@ import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { CommentThreadTargetWhereInput } from 'src/core/@generated/comment-thread-target/comment-thread-target-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
class CommentThreadTargetArgs {
where?: CommentThreadTargetWhereInput;
[key: string]: any;
}
@Injectable()
@ -39,7 +41,23 @@ export class ReadCommentThreadTargetAbilityHandler implements IAbilityHandler {
export class CreateCommentThreadTargetAbilityHandler
implements IAbilityHandler
{
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'CommentThreadTarget',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'CommentThreadTarget');
}
}
@ -54,11 +72,22 @@ export class UpdateCommentThreadTargetAbilityHandler
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<CommentThreadTargetArgs>();
const commentThreadTarget =
await this.prismaService.commentThreadTarget.findFirst({
await this.prismaService.client.commentThreadTarget.findFirst({
where: args.where,
});
assert(commentThreadTarget, '', NotFoundException);
const allowed = await relationAbilityChecker(
'CommentThreadTarget',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(
AbilityAction.Update,
subject('CommentThreadTarget', commentThreadTarget),
@ -76,7 +105,7 @@ export class DeleteCommentThreadTargetAbilityHandler
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<CommentThreadTargetArgs>();
const commentThreadTarget =
await this.prismaService.commentThreadTarget.findFirst({
await this.prismaService.client.commentThreadTarget.findFirst({
where: args.where,
});
assert(commentThreadTarget, '', NotFoundException);

View File

@ -13,10 +13,12 @@ import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { CommentThreadWhereInput } from 'src/core/@generated/comment-thread/comment-thread-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
class CommentThreadArgs {
where?: CommentThreadWhereInput;
[key: string]: any;
}
@Injectable()
@ -35,7 +37,23 @@ export class ReadCommentThreadAbilityHandler implements IAbilityHandler {
@Injectable()
export class CreateCommentThreadAbilityHandler implements IAbilityHandler {
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'CommentThread',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'CommentThread');
}
}
@ -47,11 +65,23 @@ export class UpdateCommentThreadAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<CommentThreadArgs>();
const commentThread = await this.prismaService.commentThread.findFirst({
where: args.where,
});
const commentThread =
await this.prismaService.client.commentThread.findFirst({
where: args.where,
});
assert(commentThread, '', NotFoundException);
const allowed = await relationAbilityChecker(
'CommentThread',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(
AbilityAction.Update,
subject('CommentThread', commentThread),
@ -66,9 +96,10 @@ export class DeleteCommentThreadAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<CommentThreadArgs>();
const commentThread = await this.prismaService.commentThread.findFirst({
where: args.where,
});
const commentThread =
await this.prismaService.client.commentThread.findFirst({
where: args.where,
});
assert(commentThread, '', NotFoundException);
return ability.can(

View File

@ -13,10 +13,12 @@ import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { CommentWhereInput } from 'src/core/@generated/comment/comment-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
class CommentArgs {
where?: CommentWhereInput;
[key: string]: any;
}
@Injectable()
@ -35,7 +37,23 @@ export class ReadCommentAbilityHandler implements IAbilityHandler {
@Injectable()
export class CreateCommentAbilityHandler implements IAbilityHandler {
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'Comment',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'Comment');
}
}
@ -47,11 +65,22 @@ export class UpdateCommentAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<CommentArgs>();
const comment = await this.prismaService.comment.findFirst({
const comment = await this.prismaService.client.comment.findFirst({
where: args.where,
});
assert(comment, '', NotFoundException);
const allowed = await relationAbilityChecker(
'Comment',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Update, subject('Comment', comment));
}
}
@ -63,7 +92,7 @@ export class DeleteCommentAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<CommentArgs>();
const comment = await this.prismaService.comment.findFirst({
const comment = await this.prismaService.client.comment.findFirst({
where: args.where,
});
assert(comment, '', NotFoundException);

View File

@ -13,10 +13,12 @@ import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { CompanyWhereInput } from 'src/core/@generated/company/company-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
class CompanyArgs {
where?: CompanyWhereInput;
[key: string]: any;
}
@Injectable()
@ -35,7 +37,23 @@ export class ReadCompanyAbilityHandler implements IAbilityHandler {
@Injectable()
export class CreateCompanyAbilityHandler implements IAbilityHandler {
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'Company',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'Company');
}
}
@ -47,12 +65,22 @@ export class UpdateCompanyAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<CompanyArgs>();
const company = await this.prismaService.company.findFirst({
const company = await this.prismaService.client.company.findFirst({
where: args.where,
});
assert(company, '', NotFoundException);
const allowed = await relationAbilityChecker(
'Company',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Update, subject('Company', company));
}
}
@ -64,7 +92,7 @@ export class DeleteCompanyAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<CompanyArgs>();
const company = await this.prismaService.company.findFirst({
const company = await this.prismaService.client.company.findFirst({
where: args.where,
});
assert(company, '', NotFoundException);

View File

@ -13,10 +13,12 @@ import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { PersonWhereInput } from 'src/core/@generated/person/person-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
class PersonArgs {
where?: PersonWhereInput;
[key: string]: any;
}
@Injectable()
@ -35,7 +37,23 @@ export class ReadPersonAbilityHandler implements IAbilityHandler {
@Injectable()
export class CreatePersonAbilityHandler implements IAbilityHandler {
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'Person',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'Person');
}
}
@ -47,11 +65,22 @@ export class UpdatePersonAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<PersonArgs>();
const person = await this.prismaService.person.findFirst({
const person = await this.prismaService.client.person.findFirst({
where: args.where,
});
assert(person, '', NotFoundException);
const allowed = await relationAbilityChecker(
'Person',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Update, subject('Person', person));
}
}
@ -63,7 +92,7 @@ export class DeletePersonAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<PersonArgs>();
const person = await this.prismaService.person.findFirst({
const person = await this.prismaService.client.person.findFirst({
where: args.where,
});
assert(person, '', NotFoundException);

View File

@ -12,11 +12,13 @@ import { IAbilityHandler } from 'src/ability/interfaces/ability-handler.interfac
import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { assert } from 'src/utils/assert';
import { PipelineProgressWhereInput } from 'src/core/@generated/pipeline-progress/pipeline-progress-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
class PipelineProgressArgs {
where?: PipelineProgressWhereInput;
[key: string]: any;
}
@Injectable()
@ -35,7 +37,23 @@ export class ReadPipelineProgressAbilityHandler implements IAbilityHandler {
@Injectable()
export class CreatePipelineProgressAbilityHandler implements IAbilityHandler {
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'PipelineProgress',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'PipelineProgress');
}
}
@ -48,11 +66,22 @@ export class UpdatePipelineProgressAbilityHandler implements IAbilityHandler {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<PipelineProgressArgs>();
const pipelineProgress =
await this.prismaService.pipelineProgress.findFirst({
await this.prismaService.client.pipelineProgress.findFirst({
where: args.where,
});
assert(pipelineProgress, '', NotFoundException);
const allowed = await relationAbilityChecker(
'PipelineProgress',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(
AbilityAction.Update,
subject('PipelineProgress', pipelineProgress),
@ -68,7 +97,7 @@ export class DeletePipelineProgressAbilityHandler implements IAbilityHandler {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<PipelineProgressArgs>();
const pipelineProgress =
await this.prismaService.pipelineProgress.findFirst({
await this.prismaService.client.pipelineProgress.findFirst({
where: args.where,
});
assert(pipelineProgress, '', NotFoundException);

View File

@ -13,10 +13,12 @@ import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { PipelineStageWhereInput } from 'src/core/@generated/pipeline-stage/pipeline-stage-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
class PipelineStageArgs {
where?: PipelineStageWhereInput;
[key: string]: any;
}
@Injectable()
@ -35,7 +37,23 @@ export class ReadPipelineStageAbilityHandler implements IAbilityHandler {
@Injectable()
export class CreatePipelineStageAbilityHandler implements IAbilityHandler {
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'PipelineStage',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'PipelineStage');
}
}
@ -47,11 +65,23 @@ export class UpdatePipelineStageAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<PipelineStageArgs>();
const pipelineStage = await this.prismaService.pipelineStage.findFirst({
where: args.where,
});
const pipelineStage =
await this.prismaService.client.pipelineStage.findFirst({
where: args.where,
});
assert(pipelineStage, '', NotFoundException);
const allowed = await relationAbilityChecker(
'PipelineStage',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(
AbilityAction.Update,
subject('PipelineStage', pipelineStage),
@ -66,9 +96,10 @@ export class DeletePipelineStageAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<PipelineStageArgs>();
const pipelineStage = await this.prismaService.pipelineStage.findFirst({
where: args.where,
});
const pipelineStage =
await this.prismaService.client.pipelineStage.findFirst({
where: args.where,
});
assert(pipelineStage, '', NotFoundException);
return ability.can(

View File

@ -13,10 +13,12 @@ import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { PipelineWhereInput } from 'src/core/@generated/pipeline/pipeline-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
class PipelineArgs {
where?: PipelineWhereInput;
[key: string]: any;
}
@Injectable()
@ -35,7 +37,23 @@ export class ReadPipelineAbilityHandler implements IAbilityHandler {
@Injectable()
export class CreatePipelineAbilityHandler implements IAbilityHandler {
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'Pipeline',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'Pipeline');
}
}
@ -47,11 +65,22 @@ export class UpdatePipelineAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<PipelineArgs>();
const pipeline = await this.prismaService.pipeline.findFirst({
const pipeline = await this.prismaService.client.pipeline.findFirst({
where: args.where,
});
assert(pipeline, '', NotFoundException);
const allowed = await relationAbilityChecker(
'Pipeline',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Update, subject('Pipeline', pipeline));
}
}
@ -63,7 +92,7 @@ export class DeletePipelineAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<PipelineArgs>();
const pipeline = await this.prismaService.pipeline.findFirst({
const pipeline = await this.prismaService.client.pipeline.findFirst({
where: args.where,
});
assert(pipeline, '', NotFoundException);

View File

@ -13,10 +13,12 @@ import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { RefreshTokenWhereInput } from 'src/core/@generated/refresh-token/refresh-token-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
class RefreshTokenArgs {
where?: RefreshTokenWhereInput;
[key: string]: any;
}
@Injectable()
@ -35,7 +37,23 @@ export class ReadRefreshTokenAbilityHandler implements IAbilityHandler {
@Injectable()
export class CreateRefreshTokenAbilityHandler implements IAbilityHandler {
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'RefreshToken',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'RefreshToken');
}
}
@ -47,11 +65,24 @@ export class UpdateRefreshTokenAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<RefreshTokenArgs>();
const refreshToken = await this.prismaService.refreshToken.findFirst({
where: args.where,
});
const refreshToken = await this.prismaService.client.refreshToken.findFirst(
{
where: args.where,
},
);
assert(refreshToken, '', NotFoundException);
const allowed = await relationAbilityChecker(
'RefreshToken',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(
AbilityAction.Update,
subject('RefreshToken', refreshToken),
@ -66,9 +97,11 @@ export class DeleteRefreshTokenAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<RefreshTokenArgs>();
const refreshToken = await this.prismaService.refreshToken.findFirst({
where: args.where,
});
const refreshToken = await this.prismaService.client.refreshToken.findFirst(
{
where: args.where,
},
);
assert(refreshToken, '', NotFoundException);
return ability.can(

View File

@ -12,11 +12,13 @@ import { IAbilityHandler } from 'src/ability/interfaces/ability-handler.interfac
import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { assert } from 'src/utils/assert';
import { UserWhereInput } from 'src/core/@generated/user/user-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
class UserArgs {
where?: UserWhereInput;
[key: string]: any;
}
@Injectable()
@ -35,7 +37,23 @@ export class ReadUserAbilityHandler implements IAbilityHandler {
@Injectable()
export class CreateUserAbilityHandler implements IAbilityHandler {
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'User',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'User');
}
}
@ -47,11 +65,22 @@ export class UpdateUserAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<UserArgs>();
const user = await this.prismaService.user.findFirst({
const user = await this.prismaService.client.user.findFirst({
where: args.where,
});
assert(user, '', NotFoundException);
const allowed = await relationAbilityChecker(
'User',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Update, subject('User', user));
}
}
@ -63,7 +92,7 @@ export class DeleteUserAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<UserArgs>();
const user = await this.prismaService.user.findFirst({
const user = await this.prismaService.client.user.findFirst({
where: args.where,
});
assert(user, '', NotFoundException);

View File

@ -13,10 +13,12 @@ import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { WorkspaceMemberWhereInput } from 'src/core/@generated/workspace-member/workspace-member-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
class WorksapceMemberArgs {
class WorkspaceMemberArgs {
where?: WorkspaceMemberWhereInput;
[key: string]: any;
}
@Injectable()
@ -35,7 +37,23 @@ export class ReadWorkspaceMemberAbilityHandler implements IAbilityHandler {
@Injectable()
export class CreateWorkspaceMemberAbilityHandler implements IAbilityHandler {
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'WorkspaceMember',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'WorkspaceMember');
}
}
@ -46,12 +64,24 @@ export class UpdateWorkspaceMemberAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<WorksapceMemberArgs>();
const workspaceMember = await this.prismaService.workspaceMember.findFirst({
where: args.where,
});
const args = gqlContext.getArgs<WorkspaceMemberArgs>();
const workspaceMember =
await this.prismaService.client.workspaceMember.findFirst({
where: args.where,
});
assert(workspaceMember, '', NotFoundException);
const allowed = await relationAbilityChecker(
'WorkspaceMember',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(
AbilityAction.Update,
subject('WorkspaceMember', workspaceMember),
@ -65,10 +95,11 @@ export class DeleteWorkspaceMemberAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<WorksapceMemberArgs>();
const workspaceMember = await this.prismaService.workspaceMember.findFirst({
where: args.where,
});
const args = gqlContext.getArgs<WorkspaceMemberArgs>();
const workspaceMember =
await this.prismaService.client.workspaceMember.findFirst({
where: args.where,
});
assert(workspaceMember, '', NotFoundException);
return ability.can(

View File

@ -1,24 +1,22 @@
import {
ExecutionContext,
ForbiddenException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { subject } from '@casl/ability';
import { IAbilityHandler } from 'src/ability/interfaces/ability-handler.interface';
import { PrismaService } from 'src/database/prisma.service';
import { AbilityAction } from 'src/ability/ability.action';
import { AppAbility } from 'src/ability/ability.factory';
import { WorkspaceWhereInput } from 'src/core/@generated/workspace/workspace-where.input';
import { relationAbilityChecker } from 'src/ability/ability.util';
import { assert } from 'src/utils/assert';
import { getRequest } from 'src/utils/extract-request';
class WorksapceArgs {
class WorkspaceArgs {
where?: WorkspaceWhereInput;
[key: string]: any;
}
@Injectable()
@ -37,7 +35,23 @@ export class ReadWorkspaceAbilityHandler implements IAbilityHandler {
@Injectable()
export class CreateWorkspaceAbilityHandler implements IAbilityHandler {
handle(ability: AppAbility) {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs();
const allowed = await relationAbilityChecker(
'Workspace',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Create, 'Workspace');
}
}
@ -47,15 +61,25 @@ export class UpdateWorkspaceAbilityHandler implements IAbilityHandler {
constructor(private readonly prismaService: PrismaService) {}
async handle(ability: AppAbility, context: ExecutionContext) {
const request = getRequest(context);
assert(request.user.workspace.id, '', ForbiddenException);
const workspace = await this.prismaService.workspace.findUnique({
where: { id: request.user.workspace.id },
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<WorkspaceArgs>();
const workspace = await this.prismaService.client.workspace.findFirst({
where: args.where,
});
assert(workspace, '', NotFoundException);
return ability.can(AbilityAction.Update, subject('Workspace', workspace));
const allowed = await relationAbilityChecker(
'Workspace',
ability,
this.prismaService.client,
args,
);
if (!allowed) {
return false;
}
return ability.can(AbilityAction.Update, 'Workspace');
}
}
@ -65,12 +89,12 @@ export class DeleteWorkspaceAbilityHandler implements IAbilityHandler {
async handle(ability: AppAbility, context: ExecutionContext) {
const gqlContext = GqlExecutionContext.create(context);
const args = gqlContext.getArgs<WorksapceArgs>();
const workspace = await this.prismaService.workspace.findFirst({
const args = gqlContext.getArgs<WorkspaceArgs>();
const workspace = await this.prismaService.client.workspace.findFirst({
where: args.where,
});
assert(workspace, '', NotFoundException);
return ability.can(AbilityAction.Delete, subject('Workspace', workspace));
return ability.can(AbilityAction.Delete, 'Workspace');
}
}

View File

@ -9,35 +9,35 @@ export class AttachmentService {
constructor(private readonly prismaService: PrismaService) {}
// Find
findFirst = this.prismaService.attachment.findFirst;
findFirstOrThrow = this.prismaService.attachment.findFirstOrThrow;
findFirst = this.prismaService.client.attachment.findFirst;
findFirstOrThrow = this.prismaService.client.attachment.findFirstOrThrow;
findUnique = this.prismaService.attachment.findUnique;
findUniqueOrThrow = this.prismaService.attachment.findUniqueOrThrow;
findUnique = this.prismaService.client.attachment.findUnique;
findUniqueOrThrow = this.prismaService.client.attachment.findUniqueOrThrow;
findMany = this.prismaService.attachment.findMany;
findMany = this.prismaService.client.attachment.findMany;
// Create
create = this.prismaService.attachment.create;
createMany = this.prismaService.attachment.createMany;
create = this.prismaService.client.attachment.create;
createMany = this.prismaService.client.attachment.createMany;
// Update
update = this.prismaService.attachment.update;
upsert = this.prismaService.attachment.upsert;
updateMany = this.prismaService.attachment.updateMany;
update = this.prismaService.client.attachment.update;
upsert = this.prismaService.client.attachment.upsert;
updateMany = this.prismaService.client.attachment.updateMany;
// Delete
delete = this.prismaService.attachment.delete;
deleteMany = this.prismaService.attachment.deleteMany;
delete = this.prismaService.client.attachment.delete;
deleteMany = this.prismaService.client.attachment.deleteMany;
// Aggregate
aggregate = this.prismaService.attachment.aggregate;
aggregate = this.prismaService.client.attachment.aggregate;
// Count
count = this.prismaService.attachment.count;
count = this.prismaService.client.attachment.count;
// GroupBy
groupBy = this.prismaService.attachment.groupBy;
groupBy = this.prismaService.client.attachment.groupBy;
getFileTypeFromFileName(fileName: string): AttachmentType {
const extension = fileName.split('.').pop()?.toLowerCase();

View File

@ -31,7 +31,7 @@ export class TokenService {
assert(expiresIn, '', InternalServerErrorException);
const expiresAt = addMilliseconds(new Date().getTime(), ms(expiresIn));
const user = await this.prismaService.user.findUnique({
const user = await this.prismaService.client.user.findUnique({
where: { id: userId },
include: {
workspaceMember: true,
@ -71,7 +71,7 @@ export class TokenService {
sub: userId,
};
const refreshToken = await this.prismaService.refreshToken.create({
const refreshToken = await this.prismaService.client.refreshToken.create({
data: refreshTokenPayload,
});
@ -122,13 +122,13 @@ export class TokenService {
UnprocessableEntityException,
);
const token = await this.prismaService.refreshToken.findUnique({
const token = await this.prismaService.client.refreshToken.findUnique({
where: { id: jwtPayload.jti },
});
assert(token, "This refresh token doesn't exist", NotFoundException);
const user = await this.prismaService.user.findUnique({
const user = await this.prismaService.client.user.findUnique({
where: {
id: jwtPayload.sub,
},
@ -141,7 +141,7 @@ export class TokenService {
if (token.isRevoked) {
// Revoke all user refresh tokens
await this.prismaService.refreshToken.updateMany({
await this.prismaService.client.refreshToken.updateMany({
where: {
id: {
in: user.refreshTokens.map(({ id }) => id),
@ -172,7 +172,7 @@ export class TokenService {
} = await this.verifyRefreshToken(token);
// Revoke old refresh token
await this.prismaService.refreshToken.update({
await this.prismaService.client.refreshToken.update({
where: {
id,
},

View File

@ -24,7 +24,7 @@ export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
}
async validate(payload: JwtPayload): Promise<PassportUser> {
const user = await this.prismaService.user.findUniqueOrThrow({
const user = await this.prismaService.client.user.findUniqueOrThrow({
where: { id: payload.sub },
});
@ -32,9 +32,10 @@ export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
throw new UnauthorizedException();
}
const workspace = await this.prismaService.workspace.findUniqueOrThrow({
where: { id: payload.workspaceId },
});
const workspace =
await this.prismaService.client.workspace.findUniqueOrThrow({
where: { id: payload.workspaceId },
});
if (!workspace) {
throw new UnauthorizedException();

View File

@ -1,9 +1,6 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CanActivate } from '@nestjs/common';
import { CommentThreadService } from 'src/core/comment/services/comment-thread.service';
import { CreateOneCommentGuard } from 'src/guards/create-one-comment.guard';
import { CreateOneCommentThreadGuard } from 'src/guards/create-one-comment-thread.guard';
import { AbilityFactory } from 'src/ability/ability.factory';
import { CommentThreadResolver } from './comment-thread.resolver';
@ -12,8 +9,6 @@ describe('CommentThreadResolver', () => {
let resolver: CommentThreadResolver;
beforeEach(async () => {
const mockGuard: CanActivate = { canActivate: jest.fn(() => true) };
const module: TestingModule = await Test.createTestingModule({
providers: [
CommentThreadResolver,
@ -26,12 +21,7 @@ describe('CommentThreadResolver', () => {
useValue: {},
},
],
})
.overrideGuard(CreateOneCommentGuard)
.useValue(mockGuard)
.overrideGuard(CreateOneCommentThreadGuard)
.useValue(mockGuard)
.compile();
}).compile();
resolver = module.get<CommentThreadResolver>(CommentThreadResolver);
});

View File

@ -9,7 +9,6 @@ import { Workspace } from 'src/core/@generated/workspace/workspace.model';
import { AuthWorkspace } from 'src/decorators/auth-workspace.decorator';
import { CommentThread } from 'src/core/@generated/comment-thread/comment-thread.model';
import { CreateOneCommentThreadArgs } from 'src/core/@generated/comment-thread/create-one-comment-thread.args';
import { CreateOneCommentThreadGuard } from 'src/guards/create-one-comment-thread.guard';
import { FindManyCommentThreadArgs } from 'src/core/@generated/comment-thread/find-many-comment-thread.args';
import { CommentThreadService } from 'src/core/comment/services/comment-thread.service';
import { UpdateOneCommentThreadArgs } from 'src/core/@generated/comment-thread/update-one-comment-thread.args';
@ -35,7 +34,6 @@ import { DeleteManyCommentThreadArgs } from 'src/core/@generated/comment-thread/
export class CommentThreadResolver {
constructor(private readonly commentThreadService: CommentThreadService) {}
@UseGuards(CreateOneCommentThreadGuard)
@Mutation(() => CommentThread, {
nullable: false,
})
@ -51,6 +49,15 @@ export class CommentThreadResolver {
data: {
...args.data,
...{ workspace: { connect: { id: workspace.id } } },
commentThreadTargets: args.data?.commentThreadTargets?.createMany
? {
createMany: {
data: args.data.commentThreadTargets.createMany.data.map(
(target) => ({ ...target, workspaceId: workspace.id }),
),
},
}
: undefined,
},
select: prismaSelect.value,
} as Prisma.CommentThreadCreateArgs);
@ -65,6 +72,7 @@ export class CommentThreadResolver {
@CheckAbilities(UpdateCommentThreadAbilityHandler)
async updateOneCommentThread(
@Args() args: UpdateOneCommentThreadArgs,
@AuthWorkspace() workspace: Workspace,
@PrismaSelector({ modelName: 'CommentThread' })
prismaSelect: PrismaSelect<'CommentThread'>,
): Promise<Partial<CommentThread>> {
@ -84,7 +92,18 @@ export class CommentThreadResolver {
}
const updatedCommentThread = await this.commentThreadService.update({
where: args.where,
data: args.data,
data: {
...args.data,
commentThreadTargets: args.data?.commentThreadTargets?.createMany
? {
createMany: {
data: args.data.commentThreadTargets.createMany.data.map(
(target) => ({ ...target, workspaceId: workspace.id }),
),
},
}
: undefined,
},
select: prismaSelect.value,
} as Prisma.CommentThreadUpdateArgs);

View File

@ -1,8 +1,6 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CanActivate } from '@nestjs/common';
import { CommentService } from 'src/core/comment/services/comment.service';
import { CreateOneCommentGuard } from 'src/guards/create-one-comment.guard';
import { AbilityFactory } from 'src/ability/ability.factory';
import { CommentResolver } from './comment.resolver';
@ -11,8 +9,6 @@ describe('CommentResolver', () => {
let resolver: CommentResolver;
beforeEach(async () => {
const mockGuard: CanActivate = { canActivate: jest.fn(() => true) };
const module: TestingModule = await Test.createTestingModule({
providers: [
CommentResolver,
@ -25,10 +21,7 @@ describe('CommentResolver', () => {
useValue: {},
},
],
})
.overrideGuard(CreateOneCommentGuard)
.useValue(mockGuard)
.compile();
}).compile();
resolver = module.get<CommentResolver>(CommentResolver);
});

View File

@ -8,7 +8,6 @@ import { Workspace } from 'src/core/@generated/workspace/workspace.model';
import { AuthWorkspace } from 'src/decorators/auth-workspace.decorator';
import { CreateOneCommentArgs } from 'src/core/@generated/comment/create-one-comment.args';
import { Comment } from 'src/core/@generated/comment/comment.model';
import { CreateOneCommentGuard } from 'src/guards/create-one-comment.guard';
import { CommentService } from 'src/core/comment/services/comment.service';
import {
PrismaSelector,
@ -25,7 +24,6 @@ import { User } from 'src/core/@generated/user/user.model';
export class CommentResolver {
constructor(private readonly commentService: CommentService) {}
@UseGuards(CreateOneCommentGuard)
@Mutation(() => Comment, {
nullable: false,
})

View File

@ -7,33 +7,35 @@ export class CommentThreadTargetService {
constructor(private readonly prismaService: PrismaService) {}
// Find
findFirst = this.prismaService.commentThreadTarget.findFirst;
findFirstOrThrow = this.prismaService.commentThreadTarget.findFirstOrThrow;
findFirst = this.prismaService.client.commentThreadTarget.findFirst;
findFirstOrThrow =
this.prismaService.client.commentThreadTarget.findFirstOrThrow;
findUnique = this.prismaService.commentThreadTarget.findUnique;
findUniqueOrThrow = this.prismaService.commentThreadTarget.findUniqueOrThrow;
findUnique = this.prismaService.client.commentThreadTarget.findUnique;
findUniqueOrThrow =
this.prismaService.client.commentThreadTarget.findUniqueOrThrow;
findMany = this.prismaService.commentThreadTarget.findMany;
findMany = this.prismaService.client.commentThreadTarget.findMany;
// Create
create = this.prismaService.commentThreadTarget.create;
createMany = this.prismaService.commentThreadTarget.createMany;
create = this.prismaService.client.commentThreadTarget.create;
createMany = this.prismaService.client.commentThreadTarget.createMany;
// Update
update = this.prismaService.commentThreadTarget.update;
upsert = this.prismaService.commentThreadTarget.upsert;
updateMany = this.prismaService.commentThreadTarget.updateMany;
update = this.prismaService.client.commentThreadTarget.update;
upsert = this.prismaService.client.commentThreadTarget.upsert;
updateMany = this.prismaService.client.commentThreadTarget.updateMany;
// Delete
delete = this.prismaService.commentThreadTarget.delete;
deleteMany = this.prismaService.commentThreadTarget.deleteMany;
delete = this.prismaService.client.commentThreadTarget.delete;
deleteMany = this.prismaService.client.commentThreadTarget.deleteMany;
// Aggregate
aggregate = this.prismaService.commentThreadTarget.aggregate;
aggregate = this.prismaService.client.commentThreadTarget.aggregate;
// Count
count = this.prismaService.commentThreadTarget.count;
count = this.prismaService.client.commentThreadTarget.count;
// GroupBy
groupBy = this.prismaService.commentThreadTarget.groupBy;
groupBy = this.prismaService.client.commentThreadTarget.groupBy;
}

View File

@ -7,33 +7,33 @@ export class CommentThreadService {
constructor(private readonly prismaService: PrismaService) {}
// Find
findFirst = this.prismaService.commentThread.findFirst;
findFirstOrThrow = this.prismaService.commentThread.findFirstOrThrow;
findFirst = this.prismaService.client.commentThread.findFirst;
findFirstOrThrow = this.prismaService.client.commentThread.findFirstOrThrow;
findUnique = this.prismaService.commentThread.findUnique;
findUniqueOrThrow = this.prismaService.commentThread.findUniqueOrThrow;
findUnique = this.prismaService.client.commentThread.findUnique;
findUniqueOrThrow = this.prismaService.client.commentThread.findUniqueOrThrow;
findMany = this.prismaService.commentThread.findMany;
findMany = this.prismaService.client.commentThread.findMany;
// Create
create = this.prismaService.commentThread.create;
createMany = this.prismaService.commentThread.createMany;
create = this.prismaService.client.commentThread.create;
createMany = this.prismaService.client.commentThread.createMany;
// Update
update = this.prismaService.commentThread.update;
upsert = this.prismaService.commentThread.upsert;
updateMany = this.prismaService.commentThread.updateMany;
update = this.prismaService.client.commentThread.update;
upsert = this.prismaService.client.commentThread.upsert;
updateMany = this.prismaService.client.commentThread.updateMany;
// Delete
delete = this.prismaService.commentThread.delete;
deleteMany = this.prismaService.commentThread.deleteMany;
delete = this.prismaService.client.commentThread.delete;
deleteMany = this.prismaService.client.commentThread.deleteMany;
// Aggregate
aggregate = this.prismaService.commentThread.aggregate;
aggregate = this.prismaService.client.commentThread.aggregate;
// Count
count = this.prismaService.commentThread.count;
count = this.prismaService.client.commentThread.count;
// GroupBy
groupBy = this.prismaService.commentThread.groupBy;
groupBy = this.prismaService.client.commentThread.groupBy;
}

View File

@ -7,33 +7,33 @@ export class CommentService {
constructor(private readonly prismaService: PrismaService) {}
// Find
findFirst = this.prismaService.comment.findFirst;
findFirstOrThrow = this.prismaService.comment.findFirstOrThrow;
findFirst = this.prismaService.client.comment.findFirst;
findFirstOrThrow = this.prismaService.client.comment.findFirstOrThrow;
findUnique = this.prismaService.comment.findUnique;
findUniqueOrThrow = this.prismaService.comment.findUniqueOrThrow;
findUnique = this.prismaService.client.comment.findUnique;
findUniqueOrThrow = this.prismaService.client.comment.findUniqueOrThrow;
findMany = this.prismaService.comment.findMany;
findMany = this.prismaService.client.comment.findMany;
// Create
create = this.prismaService.comment.create;
createMany = this.prismaService.comment.createMany;
create = this.prismaService.client.comment.create;
createMany = this.prismaService.client.comment.createMany;
// Update
update = this.prismaService.comment.update;
upsert = this.prismaService.comment.upsert;
updateMany = this.prismaService.comment.updateMany;
update = this.prismaService.client.comment.update;
upsert = this.prismaService.client.comment.upsert;
updateMany = this.prismaService.client.comment.updateMany;
// Delete
delete = this.prismaService.comment.delete;
deleteMany = this.prismaService.comment.deleteMany;
delete = this.prismaService.client.comment.delete;
deleteMany = this.prismaService.client.comment.deleteMany;
// Aggregate
aggregate = this.prismaService.comment.aggregate;
aggregate = this.prismaService.client.comment.aggregate;
// Count
count = this.prismaService.comment.count;
count = this.prismaService.client.comment.count;
// GroupBy
groupBy = this.prismaService.comment.groupBy;
groupBy = this.prismaService.client.comment.groupBy;
}

View File

@ -1,9 +1,5 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CanActivate } from '@nestjs/common';
import { UpdateOneGuard } from 'src/guards/update-one.guard';
import { DeleteManyGuard } from 'src/guards/delete-many.guard';
import { CreateOneGuard } from 'src/guards/create-one.guard';
import { AbilityFactory } from 'src/ability/ability.factory';
import { CompanyService } from './company.service';
@ -13,8 +9,6 @@ describe('CompanyResolver', () => {
let resolver: CompanyResolver;
beforeEach(async () => {
const mockGuard: CanActivate = { canActivate: jest.fn(() => true) };
const module: TestingModule = await Test.createTestingModule({
providers: [
CompanyResolver,
@ -27,14 +21,7 @@ describe('CompanyResolver', () => {
useValue: {},
},
],
})
.overrideGuard(UpdateOneGuard)
.useValue(mockGuard)
.overrideGuard(DeleteManyGuard)
.useValue(mockGuard)
.overrideGuard(CreateOneGuard)
.useValue(mockGuard)
.compile();
}).compile();
resolver = module.get<CompanyResolver>(CompanyResolver);
});

View File

@ -12,9 +12,6 @@ import { UpdateOneCompanyArgs } from 'src/core/@generated/company/update-one-com
import { CreateOneCompanyArgs } from 'src/core/@generated/company/create-one-company.args';
import { AffectedRows } from 'src/core/@generated/prisma/affected-rows.output';
import { DeleteManyCompanyArgs } from 'src/core/@generated/company/delete-many-company.args';
import { UpdateOneGuard } from 'src/guards/update-one.guard';
import { DeleteManyGuard } from 'src/guards/delete-many.guard';
import { CreateOneGuard } from 'src/guards/create-one.guard';
import {
PrismaSelect,
PrismaSelector,
@ -78,7 +75,6 @@ export class CompanyResolver {
});
}
@UseGuards(UpdateOneGuard)
@Mutation(() => Company, {
nullable: true,
})
@ -96,7 +92,6 @@ export class CompanyResolver {
} as Prisma.CompanyUpdateArgs);
}
@UseGuards(DeleteManyGuard)
@Mutation(() => AffectedRows, {
nullable: false,
})
@ -110,7 +105,6 @@ export class CompanyResolver {
});
}
@UseGuards(CreateOneGuard)
@Mutation(() => Company, {
nullable: false,
})

View File

@ -8,35 +8,35 @@ export class CompanyService {
constructor(private readonly prismaService: PrismaService) {}
// Find
findFirst = this.prismaService.company.findFirst;
findFirstOrThrow = this.prismaService.company.findFirstOrThrow;
findFirst = this.prismaService.client.company.findFirst;
findFirstOrThrow = this.prismaService.client.company.findFirstOrThrow;
findUnique = this.prismaService.company.findUnique;
findUniqueOrThrow = this.prismaService.company.findUniqueOrThrow;
findUnique = this.prismaService.client.company.findUnique;
findUniqueOrThrow = this.prismaService.client.company.findUniqueOrThrow;
findMany = this.prismaService.company.findMany;
findMany = this.prismaService.client.company.findMany;
// Create
create = this.prismaService.company.create;
createMany = this.prismaService.company.createMany;
create = this.prismaService.client.company.create;
createMany = this.prismaService.client.company.createMany;
// Update
update = this.prismaService.company.update;
upsert = this.prismaService.company.upsert;
updateMany = this.prismaService.company.updateMany;
update = this.prismaService.client.company.update;
upsert = this.prismaService.client.company.upsert;
updateMany = this.prismaService.client.company.updateMany;
// Delete
delete = this.prismaService.company.delete;
deleteMany = this.prismaService.company.deleteMany;
delete = this.prismaService.client.company.delete;
deleteMany = this.prismaService.client.company.deleteMany;
// Aggregate
aggregate = this.prismaService.company.aggregate;
aggregate = this.prismaService.client.company.aggregate;
// Count
count = this.prismaService.company.count;
count = this.prismaService.client.company.count;
// GroupBy
groupBy = this.prismaService.company.groupBy;
groupBy = this.prismaService.client.company.groupBy;
async createDefaultCompanies({ workspaceId }: { workspaceId: string }) {
const companies = companiesSeed.map((company) => ({
...company,

View File

@ -1,9 +1,5 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CanActivate } from '@nestjs/common';
import { UpdateOneGuard } from 'src/guards/update-one.guard';
import { DeleteManyGuard } from 'src/guards/delete-many.guard';
import { CreateOneGuard } from 'src/guards/create-one.guard';
import { AbilityFactory } from 'src/ability/ability.factory';
import { PersonService } from './person.service';
@ -13,8 +9,6 @@ describe('PersonResolver', () => {
let resolver: PersonResolver;
beforeEach(async () => {
const mockGuard: CanActivate = { canActivate: jest.fn(() => true) };
const module: TestingModule = await Test.createTestingModule({
providers: [
PersonResolver,
@ -27,14 +21,7 @@ describe('PersonResolver', () => {
useValue: {},
},
],
})
.overrideGuard(UpdateOneGuard)
.useValue(mockGuard)
.overrideGuard(DeleteManyGuard)
.useValue(mockGuard)
.overrideGuard(CreateOneGuard)
.useValue(mockGuard)
.compile();
}).compile();
resolver = module.get<PersonResolver>(PersonResolver);
});

View File

@ -20,9 +20,6 @@ import { AffectedRows } from 'src/core/@generated/prisma/affected-rows.output';
import { DeleteManyPersonArgs } from 'src/core/@generated/person/delete-many-person.args';
import { Workspace } from 'src/core/@generated/workspace/workspace.model';
import { AuthWorkspace } from 'src/decorators/auth-workspace.decorator';
import { UpdateOneGuard } from 'src/guards/update-one.guard';
import { DeleteManyGuard } from 'src/guards/delete-many.guard';
import { CreateOneGuard } from 'src/guards/create-one.guard';
import {
PrismaSelect,
PrismaSelector,
@ -95,7 +92,6 @@ export class PersonResolver {
return `${parent.firstName ?? ''} ${parent.lastName ?? ''}`;
}
@UseGuards(UpdateOneGuard)
@Mutation(() => Person, {
nullable: true,
})
@ -128,7 +124,6 @@ export class PersonResolver {
} as Prisma.PersonUpdateArgs);
}
@UseGuards(DeleteManyGuard)
@Mutation(() => AffectedRows, {
nullable: false,
})
@ -142,7 +137,6 @@ export class PersonResolver {
});
}
@UseGuards(CreateOneGuard)
@Mutation(() => Person, {
nullable: false,
})

View File

@ -10,35 +10,35 @@ export class PersonService {
constructor(private readonly prismaService: PrismaService) {}
// Find
findFirst = this.prismaService.person.findFirst;
findFirstOrThrow = this.prismaService.person.findFirstOrThrow;
findFirst = this.prismaService.client.person.findFirst;
findFirstOrThrow = this.prismaService.client.person.findFirstOrThrow;
findUnique = this.prismaService.person.findUnique;
findUniqueOrThrow = this.prismaService.person.findUniqueOrThrow;
findUnique = this.prismaService.client.person.findUnique;
findUniqueOrThrow = this.prismaService.client.person.findUniqueOrThrow;
findMany = this.prismaService.person.findMany;
findMany = this.prismaService.client.person.findMany;
// Create
create = this.prismaService.person.create;
createMany = this.prismaService.person.createMany;
create = this.prismaService.client.person.create;
createMany = this.prismaService.client.person.createMany;
// Update
update = this.prismaService.person.update;
upsert = this.prismaService.person.upsert;
updateMany = this.prismaService.person.updateMany;
update = this.prismaService.client.person.update;
upsert = this.prismaService.client.person.upsert;
updateMany = this.prismaService.client.person.updateMany;
// Delete
delete = this.prismaService.person.delete;
deleteMany = this.prismaService.person.deleteMany;
delete = this.prismaService.client.person.delete;
deleteMany = this.prismaService.client.person.deleteMany;
// Aggregate
aggregate = this.prismaService.person.aggregate;
aggregate = this.prismaService.client.person.aggregate;
// Count
count = this.prismaService.person.count;
count = this.prismaService.client.person.count;
// GroupBy
groupBy = this.prismaService.person.groupBy;
groupBy = this.prismaService.client.person.groupBy;
async createDefaultPeople({
workspaceId,
companies,

View File

@ -7,33 +7,35 @@ export class PipelineProgressService {
constructor(private readonly prismaService: PrismaService) {}
// Find
findFirst = this.prismaService.pipelineProgress.findFirst;
findFirstOrThrow = this.prismaService.pipelineProgress.findFirstOrThrow;
findFirst = this.prismaService.client.pipelineProgress.findFirst;
findFirstOrThrow =
this.prismaService.client.pipelineProgress.findFirstOrThrow;
findUnique = this.prismaService.pipelineProgress.findUnique;
findUniqueOrThrow = this.prismaService.pipelineProgress.findUniqueOrThrow;
findUnique = this.prismaService.client.pipelineProgress.findUnique;
findUniqueOrThrow =
this.prismaService.client.pipelineProgress.findUniqueOrThrow;
findMany = this.prismaService.pipelineProgress.findMany;
findMany = this.prismaService.client.pipelineProgress.findMany;
// Create
create = this.prismaService.pipelineProgress.create;
createMany = this.prismaService.pipelineProgress.createMany;
create = this.prismaService.client.pipelineProgress.create;
createMany = this.prismaService.client.pipelineProgress.createMany;
// Update
update = this.prismaService.pipelineProgress.update;
upsert = this.prismaService.pipelineProgress.upsert;
updateMany = this.prismaService.pipelineProgress.updateMany;
update = this.prismaService.client.pipelineProgress.update;
upsert = this.prismaService.client.pipelineProgress.upsert;
updateMany = this.prismaService.client.pipelineProgress.updateMany;
// Delete
delete = this.prismaService.pipelineProgress.delete;
deleteMany = this.prismaService.pipelineProgress.deleteMany;
delete = this.prismaService.client.pipelineProgress.delete;
deleteMany = this.prismaService.client.pipelineProgress.deleteMany;
// Aggregate
aggregate = this.prismaService.pipelineProgress.aggregate;
aggregate = this.prismaService.client.pipelineProgress.aggregate;
// Count
count = this.prismaService.pipelineProgress.count;
count = this.prismaService.client.pipelineProgress.count;
// GroupBy
groupBy = this.prismaService.pipelineProgress.groupBy;
groupBy = this.prismaService.client.pipelineProgress.groupBy;
}

View File

@ -8,35 +8,35 @@ export class PipelineStageService {
constructor(private readonly prismaService: PrismaService) {}
// Find
findFirst = this.prismaService.pipelineStage.findFirst;
findFirstOrThrow = this.prismaService.pipelineStage.findFirstOrThrow;
findFirst = this.prismaService.client.pipelineStage.findFirst;
findFirstOrThrow = this.prismaService.client.pipelineStage.findFirstOrThrow;
findUnique = this.prismaService.pipelineStage.findUnique;
findUniqueOrThrow = this.prismaService.pipelineStage.findUniqueOrThrow;
findUnique = this.prismaService.client.pipelineStage.findUnique;
findUniqueOrThrow = this.prismaService.client.pipelineStage.findUniqueOrThrow;
findMany = this.prismaService.pipelineStage.findMany;
findMany = this.prismaService.client.pipelineStage.findMany;
// Create
create = this.prismaService.pipelineStage.create;
createMany = this.prismaService.pipelineStage.createMany;
create = this.prismaService.client.pipelineStage.create;
createMany = this.prismaService.client.pipelineStage.createMany;
// Update
update = this.prismaService.pipelineStage.update;
upsert = this.prismaService.pipelineStage.upsert;
updateMany = this.prismaService.pipelineStage.updateMany;
update = this.prismaService.client.pipelineStage.update;
upsert = this.prismaService.client.pipelineStage.upsert;
updateMany = this.prismaService.client.pipelineStage.updateMany;
// Delete
delete = this.prismaService.pipelineStage.delete;
deleteMany = this.prismaService.pipelineStage.deleteMany;
delete = this.prismaService.client.pipelineStage.delete;
deleteMany = this.prismaService.client.pipelineStage.deleteMany;
// Aggregate
aggregate = this.prismaService.pipelineStage.aggregate;
aggregate = this.prismaService.client.pipelineStage.aggregate;
// Count
count = this.prismaService.pipelineStage.count;
count = this.prismaService.client.pipelineStage.count;
// GroupBy
groupBy = this.prismaService.pipelineStage.groupBy;
groupBy = this.prismaService.client.pipelineStage.groupBy;
// Customs
async createDefaultPipelineStages({

View File

@ -10,35 +10,35 @@ export class PipelineService {
constructor(private readonly prismaService: PrismaService) {}
// Find
findFirst = this.prismaService.pipeline.findFirst;
findFirstOrThrow = this.prismaService.pipeline.findFirstOrThrow;
findFirst = this.prismaService.client.pipeline.findFirst;
findFirstOrThrow = this.prismaService.client.pipeline.findFirstOrThrow;
findUnique = this.prismaService.pipeline.findUnique;
findUniqueOrThrow = this.prismaService.pipeline.findUniqueOrThrow;
findUnique = this.prismaService.client.pipeline.findUnique;
findUniqueOrThrow = this.prismaService.client.pipeline.findUniqueOrThrow;
findMany = this.prismaService.pipeline.findMany;
findMany = this.prismaService.client.pipeline.findMany;
// Create
create = this.prismaService.pipeline.create;
createMany = this.prismaService.pipeline.createMany;
create = this.prismaService.client.pipeline.create;
createMany = this.prismaService.client.pipeline.createMany;
// Update
update = this.prismaService.pipeline.update;
upsert = this.prismaService.pipeline.upsert;
updateMany = this.prismaService.pipeline.updateMany;
update = this.prismaService.client.pipeline.update;
upsert = this.prismaService.client.pipeline.upsert;
updateMany = this.prismaService.client.pipeline.updateMany;
// Delete
delete = this.prismaService.pipeline.delete;
deleteMany = this.prismaService.pipeline.deleteMany;
delete = this.prismaService.client.pipeline.delete;
deleteMany = this.prismaService.client.pipeline.deleteMany;
// Aggregate
aggregate = this.prismaService.pipeline.aggregate;
aggregate = this.prismaService.client.pipeline.aggregate;
// Count
count = this.prismaService.pipeline.count;
count = this.prismaService.client.pipeline.count;
// GroupBy
groupBy = this.prismaService.pipeline.groupBy;
groupBy = this.prismaService.client.pipeline.groupBy;
// Customs
async createDefaultPipeline({ workspaceId }: { workspaceId: string }) {

View File

@ -19,35 +19,35 @@ export class UserService {
) {}
// Find
findFirst = this.prismaService.user.findFirst;
findFirstOrThrow = this.prismaService.user.findFirstOrThrow;
findFirst = this.prismaService.client.user.findFirst;
findFirstOrThrow = this.prismaService.client.user.findFirstOrThrow;
findUnique = this.prismaService.user.findUnique;
findUniqueOrThrow = this.prismaService.user.findUniqueOrThrow;
findUnique = this.prismaService.client.user.findUnique;
findUniqueOrThrow = this.prismaService.client.user.findUniqueOrThrow;
findMany = this.prismaService.user.findMany;
findMany = this.prismaService.client.user.findMany;
// Create
create = this.prismaService.user.create;
createMany = this.prismaService.user.createMany;
create = this.prismaService.client.user.create;
createMany = this.prismaService.client.user.createMany;
// Update
update = this.prismaService.user.update;
upsert = this.prismaService.user.upsert;
updateMany = this.prismaService.user.updateMany;
update = this.prismaService.client.user.update;
upsert = this.prismaService.client.user.upsert;
updateMany = this.prismaService.client.user.updateMany;
// Delete
delete = this.prismaService.user.delete;
deleteMany = this.prismaService.user.deleteMany;
delete = this.prismaService.client.user.delete;
deleteMany = this.prismaService.client.user.deleteMany;
// Aggregate
aggregate = this.prismaService.user.aggregate;
aggregate = this.prismaService.client.user.aggregate;
// Count
count = this.prismaService.user.count;
count = this.prismaService.client.user.count;
// GroupBy
groupBy = this.prismaService.user.groupBy;
groupBy = this.prismaService.client.user.groupBy;
// Customs
async createUser<T extends Prisma.UserCreateArgs>(
@ -68,7 +68,7 @@ export class UserService {
assert(workspace, 'workspace is missing', BadRequestException);
// Create user
const user = await this.prismaService.user.upsert({
const user = await this.prismaService.client.user.upsert({
where: {
email: args.data.email,
},

View File

@ -7,33 +7,34 @@ export class WorkspaceMemberService {
constructor(private readonly prismaService: PrismaService) {}
// Find
findFirst = this.prismaService.workspaceMember.findFirst;
findFirstOrThrow = this.prismaService.workspaceMember.findFirstOrThrow;
findFirst = this.prismaService.client.workspaceMember.findFirst;
findFirstOrThrow = this.prismaService.client.workspaceMember.findFirstOrThrow;
findUnique = this.prismaService.workspaceMember.findUnique;
findUniqueOrThrow = this.prismaService.workspaceMember.findUniqueOrThrow;
findUnique = this.prismaService.client.workspaceMember.findUnique;
findUniqueOrThrow =
this.prismaService.client.workspaceMember.findUniqueOrThrow;
findMany = this.prismaService.workspaceMember.findMany;
findMany = this.prismaService.client.workspaceMember.findMany;
// Create
create = this.prismaService.workspaceMember.create;
createMany = this.prismaService.workspaceMember.createMany;
create = this.prismaService.client.workspaceMember.create;
createMany = this.prismaService.client.workspaceMember.createMany;
// Update
update = this.prismaService.workspaceMember.update;
upsert = this.prismaService.workspaceMember.upsert;
updateMany = this.prismaService.workspaceMember.updateMany;
update = this.prismaService.client.workspaceMember.update;
upsert = this.prismaService.client.workspaceMember.upsert;
updateMany = this.prismaService.client.workspaceMember.updateMany;
// Delete
delete = this.prismaService.workspaceMember.delete;
deleteMany = this.prismaService.workspaceMember.deleteMany;
delete = this.prismaService.client.workspaceMember.delete;
deleteMany = this.prismaService.client.workspaceMember.deleteMany;
// Aggregate
aggregate = this.prismaService.workspaceMember.aggregate;
aggregate = this.prismaService.client.workspaceMember.aggregate;
// Count
count = this.prismaService.workspaceMember.count;
count = this.prismaService.client.workspaceMember.count;
// GroupBy
groupBy = this.prismaService.workspaceMember.groupBy;
groupBy = this.prismaService.client.workspaceMember.groupBy;
}

View File

@ -19,35 +19,35 @@ export class WorkspaceService {
) {}
// Find
findFirst = this.prismaService.workspace.findFirst;
findFirstOrThrow = this.prismaService.workspace.findFirstOrThrow;
findFirst = this.prismaService.client.workspace.findFirst;
findFirstOrThrow = this.prismaService.client.workspace.findFirstOrThrow;
findUnique = this.prismaService.workspace.findUnique;
findUniqueOrThrow = this.prismaService.workspace.findUniqueOrThrow;
findUnique = this.prismaService.client.workspace.findUnique;
findUniqueOrThrow = this.prismaService.client.workspace.findUniqueOrThrow;
findMany = this.prismaService.workspace.findMany;
findMany = this.prismaService.client.workspace.findMany;
// Create
create = this.prismaService.workspace.create;
createMany = this.prismaService.workspace.createMany;
create = this.prismaService.client.workspace.create;
createMany = this.prismaService.client.workspace.createMany;
// Update
update = this.prismaService.workspace.update;
upsert = this.prismaService.workspace.upsert;
updateMany = this.prismaService.workspace.updateMany;
update = this.prismaService.client.workspace.update;
upsert = this.prismaService.client.workspace.upsert;
updateMany = this.prismaService.client.workspace.updateMany;
// Delete
delete = this.prismaService.workspace.delete;
deleteMany = this.prismaService.workspace.deleteMany;
delete = this.prismaService.client.workspace.delete;
deleteMany = this.prismaService.client.workspace.deleteMany;
// Aggregate
aggregate = this.prismaService.workspace.aggregate;
aggregate = this.prismaService.client.workspace.aggregate;
// Count
count = this.prismaService.workspace.count;
count = this.prismaService.client.workspace.count;
// GroupBy
groupBy = this.prismaService.workspace.groupBy;
groupBy = this.prismaService.client.workspace.groupBy;
// Customs
async createDefaultWorkspace() {

View File

@ -0,0 +1,14 @@
/*
Warnings:
- Added the required column `workspaceId` to the `comment_thread_targets` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "comment_thread_targets" ADD COLUMN "workspaceId" TEXT NOT NULL;
-- AddForeignKey
ALTER TABLE "comment_thread_targets" ADD CONSTRAINT "comment_thread_targets_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "attachments" ADD CONSTRAINT "attachments_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@ -5,24 +5,33 @@ import {
OnModuleInit,
} from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { Prisma, PrismaClient } from '@prisma/client';
import { createPrismaQueryEventHandler } from 'prisma-query-log';
import { EnvironmentService } from 'src/integrations/environment/environment.service';
// TODO: Check if this is still needed
if (!global.prisma) {
global.prisma = new PrismaClient();
}
export default global.prisma;
// Prepare Prisma extenstion ability
const createPrismaClient = (options: Prisma.PrismaClientOptions) => {
const client = new PrismaClient(options);
return client;
};
type ExtendedPrismaClient = ReturnType<typeof createPrismaClient>;
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
export class PrismaService implements OnModuleInit {
private readonly logger = new Logger(PrismaService.name);
private prismaClient!: ExtendedPrismaClient;
public get client(): ExtendedPrismaClient {
return this.prismaClient;
}
constructor(private readonly environmentService: EnvironmentService) {
const debugMode = environmentService.isDebugMode();
super({
this.prismaClient = createPrismaClient({
errorFormat: 'minimal',
log: debugMode
? [
@ -44,16 +53,16 @@ export class PrismaService extends PrismaClient implements OnModuleInit {
colorParameter: '\u001B[90m',
});
this.$on('query' as any, logHandler);
this.prismaClient.$on('query' as any, logHandler);
}
}
async onModuleInit() {
await this.$connect();
async onModuleInit(): Promise<void> {
await this.prismaClient.$connect();
}
async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => {
this.prismaClient.$on('beforeExit', async () => {
await app.close();
});
}

View File

@ -173,8 +173,10 @@ model Workspace {
/// @TypeGraphQL.omit(input: true, output: true)
deletedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Attachment Attachment[]
CommentThreadTarget CommentThreadTarget[]
@@map("workspaces")
}
@ -379,9 +381,12 @@ model CommentThreadTarget {
/// @Validator.IsOptional()
id String @id @default(uuid())
commentThread CommentThread @relation(fields: [commentThreadId], references: [id], onDelete: Cascade)
commentThread CommentThread @relation(fields: [commentThreadId], references: [id], onDelete: Cascade)
commentThreadId String
/// @TypeGraphQL.omit(input: true, output: false)
workspace Workspace @relation(fields: [workspaceId], references: [id])
/// @TypeGraphQL.omit(input: true, output: true)
workspaceId String
commentableType CommentableType
commentableId String
@ -515,6 +520,8 @@ model Attachment {
activityId String
activity CommentThread @relation(fields: [activityId], references: [id])
/// @TypeGraphQL.omit(input: true, output: false)
workspace Workspace @relation(fields: [workspaceId], references: [id])
/// @TypeGraphQL.omit(input: true, output: true)
workspaceId String

View File

@ -18,6 +18,7 @@ export const seedComments = async (prisma: PrismaClient) => {
update: {},
create: {
id: 'twenty-fe256b39-3ec3-4fe3-8997-b76aa0bfb600',
workspaceId: 'twenty-7ed9d212-1c25-4d02-bf25-6aeccf7ea419',
commentableType: 'Company',
commentableId: 'twenty-fe256b39-3ec3-4fe3-8997-b76aa0bfa408',
commentThreadId: 'twenty-fe256b39-3ec3-4fe3-8997-b76aa0bfb400',
@ -68,6 +69,7 @@ export const seedComments = async (prisma: PrismaClient) => {
update: {},
create: {
id: 'twenty-fe256b39-3ec3-4fe3-8997-a76aa0bfb600',
workspaceId: 'twenty-7ed9d212-1c25-4d02-bf25-6aeccf7ea419',
commentableType: 'Person',
commentableId: 'twenty-755035db-623d-41fe-92e7-dd45b7c568e1',
commentThreadId: 'twenty-fe256b39-3ec3-4fe3-8997-b76aa0bfc408',
@ -103,6 +105,7 @@ export const seedComments = async (prisma: PrismaClient) => {
update: {},
create: {
id: 'twenty-dev-fe256b39-3ec3-4fe3-8997-a76aa0bfba00',
workspaceId: 'twenty-dev-7ed9d212-1c25-4d02-bf25-6aeccf7ea420',
commentableType: 'Company',
commentableId: 'twenty-dev-a674fa6c-1455-4c57-afaf-dd5dc086361e',
commentThreadId: 'twenty-dev-fe256b39-3ec3-4fe3-8997-b76aaabfb408',

View File

@ -1,106 +0,0 @@
import {
CanActivate,
ExecutionContext,
HttpException,
HttpStatus,
Injectable,
} from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { PrismaService } from 'src/database/prisma.service';
@Injectable()
export class CreateOneCommentThreadGuard implements CanActivate {
constructor(private prismaService: PrismaService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const gqlContext = GqlExecutionContext.create(context);
// TODO: type request
const request = gqlContext.getContext().req;
const args = gqlContext.getArgs();
const targets = args.data?.commentThreadTargets?.createMany?.data;
const comments = args.data?.comments?.createMany?.data;
const workspace = request.user.workspace;
if (!targets || targets.length === 0) {
throw new HttpException(
{ reason: 'Missing commentThreadTargets' },
HttpStatus.BAD_REQUEST,
);
}
await targets.map(async (target) => {
if (!target.commentableId || !target.commentableType) {
throw new HttpException(
{
reason:
'Missing commentThreadTarget.commentableId or commentThreadTarget.commentableType',
},
HttpStatus.BAD_REQUEST,
);
}
if (!['Person', 'Company'].includes(target.commentableType)) {
throw new HttpException(
{ reason: 'Invalid commentThreadTarget.commentableType' },
HttpStatus.BAD_REQUEST,
);
}
const targetEntity = await this.prismaService[
target.commentableType
].findUnique({
where: { id: target.commentableId },
});
if (!targetEntity || targetEntity.workspaceId !== workspace.id) {
throw new HttpException(
{ reason: 'CommentThreadTarget not found' },
HttpStatus.NOT_FOUND,
);
}
});
if (!comments) {
return true;
}
await comments.map(async (comment) => {
if (!comment.authorId) {
throw new HttpException(
{ reason: 'Missing comment.authorId' },
HttpStatus.BAD_REQUEST,
);
}
const author = await this.prismaService.user.findUnique({
where: { id: comment.authorId },
});
if (!author) {
throw new HttpException(
{ reason: 'Comment.authorId not found' },
HttpStatus.NOT_FOUND,
);
}
const userWorkspaceMember =
await this.prismaService.workspaceMember.findFirst({
where: { userId: author.id },
});
if (
!userWorkspaceMember ||
userWorkspaceMember.workspaceId !== workspace.id
) {
throw new HttpException(
{ reason: 'userWorkspaceMember.workspaceId not found' },
HttpStatus.NOT_FOUND,
);
}
});
return true;
}
}

View File

@ -1,72 +0,0 @@
import {
CanActivate,
ExecutionContext,
HttpException,
HttpStatus,
Injectable,
} from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { PrismaService } from 'src/database/prisma.service';
@Injectable()
export class CreateOneCommentGuard implements CanActivate {
constructor(private prismaService: PrismaService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const gqlContext = GqlExecutionContext.create(context);
const request = gqlContext.getContext().req;
const args = gqlContext.getArgs();
const authorId = args.data?.author?.connect?.id;
const commentThreadId = args.data?.commentThread?.connect?.id;
if (!authorId || !commentThreadId) {
throw new HttpException(
{ reason: 'Missing author or commentThread' },
HttpStatus.BAD_REQUEST,
);
}
const author = await this.prismaService.user.findUnique({
where: { id: authorId },
});
const commentThread = await this.prismaService.commentThread.findUnique({
where: { id: commentThreadId },
});
if (!author || !commentThread) {
throw new HttpException(
{ reason: 'Author or commentThread not found' },
HttpStatus.NOT_FOUND,
);
}
const userWorkspaceMember =
await this.prismaService.workspaceMember.findFirst({
where: { userId: author.id },
});
if (!userWorkspaceMember) {
throw new HttpException(
{ reason: 'Author or commentThread not found' },
HttpStatus.NOT_FOUND,
);
}
const workspace = request.user.workspace;
if (
userWorkspaceMember.workspaceId !== workspace.id ||
commentThread.workspaceId !== workspace.id
) {
throw new HttpException(
{ reason: 'Author or commentThread not found' },
HttpStatus.NOT_FOUND,
);
}
return true;
}
}

View File

@ -1,13 +0,0 @@
import { CanActivate, Injectable } from '@nestjs/common';
import { PrismaService } from 'src/database/prisma.service';
@Injectable()
export class CreateOneGuard implements CanActivate {
constructor(private prismaService: PrismaService) {}
async canActivate(): Promise<boolean> {
// TODO
return true;
}
}

View File

@ -1,13 +0,0 @@
import { CanActivate, Injectable } from '@nestjs/common';
import { PrismaService } from 'src/database/prisma.service';
@Injectable()
export class DeleteManyGuard implements CanActivate {
constructor(private prismaService: PrismaService) {}
async canActivate(): Promise<boolean> {
// TODO
return true;
}
}

View File

@ -1,50 +0,0 @@
import {
CanActivate,
ExecutionContext,
HttpException,
HttpStatus,
Injectable,
} from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { PrismaService } from 'src/database/prisma.service';
@Injectable()
export class UpdateOneGuard implements CanActivate {
constructor(private prismaService: PrismaService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const gqlContext = GqlExecutionContext.create(context);
const request = gqlContext.getContext().req;
const entity = gqlContext.getArgByIndex(3).returnType?.name;
const args = gqlContext.getArgs();
if (!entity || !args.where?.id) {
throw new HttpException(
{ reason: 'Invalid Request' },
HttpStatus.BAD_REQUEST,
);
}
const object = await this.prismaService[entity].findUniqueOrThrow({
where: { id: args.where.id },
});
if (!object) {
throw new HttpException(
{ reason: 'Record not found' },
HttpStatus.NOT_FOUND,
);
}
const workspace = request.user.workspace;
if (object.workspaceId !== workspace.id) {
throw new HttpException(
{ reason: 'Record not found' },
HttpStatus.NOT_FOUND,
);
}
return true;
}
}

View File

@ -15,7 +15,7 @@ export class PrismaHealthIndicator extends HealthIndicator {
async isDatabaseInstanceHealthy(key: string): Promise<HealthIndicatorResult> {
try {
await this.prismaService.$queryRaw`SELECT 1`;
await this.prismaService.client.$queryRaw`SELECT 1`;
return this.getStatus(key, true);
} catch (e) {
throw new HealthCheckError('Prisma check failed', e);