Skip to content

Commit

Permalink
fix(tickets): update relations creation and enable permission checks
Browse files Browse the repository at this point in the history
  • Loading branch information
getlarge committed Dec 17, 2023
1 parent 23118dd commit 79a3c87
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 37 deletions.
10 changes: 7 additions & 3 deletions apps/auth/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { LoggerModule } from 'nestjs-pino';

import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AppConfigService, EnvironmentVariables } from './env';
import { EnvironmentVariables } from './env';
import { HealthModule } from './health/health.module';
import { UsersModule } from './users/users.module';

Expand All @@ -23,7 +23,9 @@ import { UsersModule } from './users/users.module';
}),
LoggerModule.forRootAsync({
inject: [ConfigService],
useFactory: (configService: AppConfigService) => ({
useFactory: (
configService: ConfigService<EnvironmentVariables, true>,
) => ({
pinoHttp: {
transport:
process.env.NODE_ENV !== 'production'
Expand All @@ -38,7 +40,9 @@ import { UsersModule } from './users/users.module';
}),
MongooseModule.forRootAsync({
inject: [ConfigService],
useFactory: (configService: AppConfigService) => ({
useFactory: (
configService: ConfigService<EnvironmentVariables, true>,
) => ({
uri: configService.get<string>('MONGODB_URI'),
}),
}),
Expand Down
11 changes: 6 additions & 5 deletions apps/auth/src/app/health/health.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
import { Resources } from '@ticketing/shared/constants';
import { Connection } from 'mongoose';

import { AppConfigService } from '../env';
import type { EnvironmentVariables } from '../env';

@ApiTags(Resources.HEALTH)
@Controller({ path: Resources.HEALTH, version: VERSION_NEUTRAL })
Expand All @@ -35,21 +35,22 @@ export class HealthController {
rssThreshold: number;

constructor(
@Inject(ConfigService) private readonly configService: AppConfigService,
@Inject(ConfigService)
private readonly configService: ConfigService<EnvironmentVariables, true>,
@Inject(getConnectionToken())
private readonly mongooseConnection: Connection,
private readonly health: HealthCheckService,
private readonly http: HttpHealthIndicator,
private readonly mongo: MongooseHealthIndicator,
private readonly memory: MemoryHealthIndicator
private readonly memory: MemoryHealthIndicator,
) {
this.heapUsedThreshold = this.configService.get<number>(
'HEAP_USED_TRESHOLD',
HEALTH_DEFAULT_HEAP_USED_TRESHOLD
HEALTH_DEFAULT_HEAP_USED_TRESHOLD,
);
this.rssThreshold = this.configService.get<number>(
'MEMORY_RSS_TRESHOLD',
HEALTH_DEFAULT_MEMORY_RSS_TRESHOLD
HEALTH_DEFAULT_MEMORY_RSS_TRESHOLD,
);
}

Expand Down
5 changes: 3 additions & 2 deletions apps/auth/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { Logger } from 'nestjs-pino';
import { resolve } from 'path';

import { AppModule } from './app/app.module';
import { AppConfigService } from './app/env';
import { EnvironmentVariables } from './app/env';
import { APP_FOLDER, DEFAULT_PORT } from './app/shared/constants';

async function bootstrap(): Promise<void> {
Expand All @@ -43,7 +43,8 @@ async function bootstrap(): Promise<void> {
{ bufferLogs: true, abortOnError: false },
);

const configService = app.get<AppConfigService>(ConfigService);
const configService =
app.get<ConfigService<EnvironmentVariables, true>>(ConfigService);
const port = configService.get('PORT', DEFAULT_PORT, { infer: true });
const environment = configService.get('NODE_ENV', { infer: true });
const swaggerUiPrefix = configService.get('SWAGGER_PATH', { infer: true });
Expand Down
5 changes: 3 additions & 2 deletions apps/expiration/src/app/health/health.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
} from '@ticketing/microservices/shared/redis';
import { Resources } from '@ticketing/shared/constants';

import { AppConfigService } from '../env';
import { EnvironmentVariables } from '../env';

@ApiTags(Resources.HEALTH)
@Controller({ path: Resources.HEALTH, version: VERSION_NEUTRAL })
Expand All @@ -41,7 +41,8 @@ export class HealthController {
readonly microserviceOptions: MicroserviceHealthIndicatorOptions;

constructor(
@Inject(ConfigService) private readonly configService: AppConfigService,
@Inject(ConfigService)
private readonly configService: ConfigService<EnvironmentVariables, true>,
private readonly health: HealthCheckService,
private readonly http: HttpHealthIndicator,
private readonly memory: MemoryHealthIndicator,
Expand Down
5 changes: 3 additions & 2 deletions apps/tickets/src/app/health/health.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
import { Resources } from '@ticketing/shared/constants';
import { Connection } from 'mongoose';

import { AppConfigService } from '../env';
import type { EnvironmentVariables } from '../env';

@ApiTags(Resources.HEALTH)
@Controller({ path: Resources.HEALTH, version: VERSION_NEUTRAL })
Expand All @@ -43,7 +43,8 @@ export class HealthController {
readonly microserviceOptions: MicroserviceHealthIndicatorOptions;

constructor(
@Inject(ConfigService) private readonly configService: AppConfigService,
@Inject(ConfigService)
private readonly configService: ConfigService<EnvironmentVariables, true>,
@Inject(getConnectionToken())
private readonly mongooseConnection: Connection,
private readonly health: HealthCheckService,
Expand Down
34 changes: 20 additions & 14 deletions apps/tickets/src/app/tickets/tickets.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,12 @@ import {
ParseObjectId,
ParseQuery,
} from '@ticketing/microservices/shared/pipes';
import { Actions, Resources } from '@ticketing/shared/constants';
import { relationTupleToString } from '@ticketing/microservices/shared/relation-tuple-parser';
import {
Actions,
CURRENT_USER_KEY,
Resources,
} from '@ticketing/shared/constants';
import { requestValidationErrorFactory } from '@ticketing/shared/errors';
import { User } from '@ticketing/shared/models';
import { FastifyRequest } from 'fastify/types/request';
Expand Down Expand Up @@ -127,19 +132,20 @@ export class TicketsController {
return this.ticketsService.findById(id);
}

@PermissionCheck(
({ currentUserId, resourceId }) =>
`${PermissionNamespaces[Resources.TICKETS]}:${resourceId}#owners@${
PermissionNamespaces[Resources.USERS]
}:${currentUserId}`,
(ctx) => {
const req = ctx.switchToHttp().getRequest<FastifyRequest>();
return {
currentUserId: get(req, 'user.id'),
resourceId: get(req, 'params.id'),
};
},
)
@PermissionCheck((ctx) => {
const req = ctx.switchToHttp().getRequest<FastifyRequest>();
const currentUserId = get(req, `${CURRENT_USER_KEY}.id`);
const resourceId = get(req, 'params.id');
return relationTupleToString({
namespace: PermissionNamespaces[Resources.TICKETS],
object: resourceId,
relation: 'owners',
subjectIdOrSet: {
namespace: PermissionNamespaces[Resources.USERS],
object: currentUserId,
},
});
})
@UseGuards(OryAuthGuard, OryPermissionGuard)
@UsePipes(
new ValidationPipe({
Expand Down
21 changes: 12 additions & 9 deletions apps/tickets/src/app/tickets/tickets.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
PermissionNamespaces,
} from '@ticketing/microservices/shared/models';
import { transactionManager } from '@ticketing/microservices/shared/mongo';
import { parseRelationTuple } from '@ticketing/microservices/shared/relation-tuple-parser';
import { RelationTuple } from '@ticketing/microservices/shared/relation-tuple-parser';
import { Resources } from '@ticketing/shared/constants';
import { User } from '@ticketing/shared/models';
import { isEmpty } from 'lodash-es';
Expand Down Expand Up @@ -65,13 +65,17 @@ export class TicketsService {
const newTicket = docs[0].toJSON<Ticket>();
this.logger.debug(`Created ticket ${newTicket.id}`);

const relationTuple = `${PermissionNamespaces[Resources.TICKETS]}:${
newTicket.id
}#owners@${PermissionNamespaces[Resources.USERS]}:${currentUser.id}`;
const relationTuple = new RelationTuple(
PermissionNamespaces[Resources.TICKETS],
newTicket.id,
'owners',
{
namespace: PermissionNamespaces[Resources.USERS],
object: currentUser.id,
},
);
const relationShipCreated =
await this.oryPermissionService.createRelation(
parseRelationTuple(relationTuple).unwrapOrThrow(),
);
await this.oryPermissionService.createRelation(relationTuple);
if (!relationShipCreated) {
throw new BadRequestException(
`Could not create relation ${relationTuple}`,
Expand Down Expand Up @@ -141,6 +145,7 @@ export class TicketsService {
} else if (ticket.orderId) {
throw new BadRequestException(`Ticket ${id} is currently reserved`);
}

ticket.set(update);
await ticket.save({ session });
const updatedTicket = ticket.toJSON<Ticket>();
Expand Down Expand Up @@ -169,7 +174,6 @@ export class TicketsService {
}
ticket.set({ orderId });
await ticket.save({ session });
// TODO: create relation between ticket and order
const updatedTicket = ticket.toJSON<Ticket>();
await lastValueFrom(
this.emitEvent(Patterns.TicketUpdated, updatedTicket),
Expand All @@ -196,7 +200,6 @@ export class TicketsService {
}
ticket.set({ orderId: undefined });
await ticket.save({ session: manager.session });
// TODO: delete relation between ticket and order
const updatedTicket = ticket.toJSON<Ticket>();
await lastValueFrom(
this.emitEvent(Patterns.TicketUpdated, updatedTicket).pipe(),
Expand Down

0 comments on commit 79a3c87

Please sign in to comment.