Skip to content

Commit

Permalink
refactor: update authentication guards and add logging statements
Browse files Browse the repository at this point in the history
  • Loading branch information
getlarge committed Dec 17, 2023
1 parent 2079007 commit fc93a58
Show file tree
Hide file tree
Showing 8 changed files with 36 additions and 34 deletions.
10 changes: 5 additions & 5 deletions apps/auth/src/app/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { SecurityRequirements } from '@ticketing/microservices/shared/constants'
import { CurrentUser } from '@ticketing/microservices/shared/decorators';
import {
OryActionAuthGuard,
OryAuthGuard,
OryAuthenticationGuard,
} from '@ticketing/microservices/shared/guards';
import { Actions, Resources } from '@ticketing/shared/constants';
import { requestValidationErrorFactory } from '@ticketing/shared/errors';
Expand All @@ -41,7 +41,7 @@ export class UsersController {
transform: true,
exceptionFactory: requestValidationErrorFactory,
forbidUnknownValues: true,
})
}),
)
@ApiOperation({
description: 'Triggered when a user is created in Ory',
Expand All @@ -65,7 +65,7 @@ export class UsersController {
transform: true,
exceptionFactory: requestValidationErrorFactory,
forbidUnknownValues: true,
})
}),
)
@ApiOperation({
description: 'Triggered when a user signed in via Ory',
Expand All @@ -91,7 +91,7 @@ export class UsersController {
transform: true,
exceptionFactory: requestValidationErrorFactory,
forbidUnknownValues: true,
})
}),
)
@ApiOperation({
description: 'Request creation of a user',
Expand All @@ -108,7 +108,7 @@ export class UsersController {
return this.usersService.signUp(credentials);
}

@UseGuards(OryAuthGuard)
@UseGuards(OryAuthenticationGuard)
@ApiOperation({
description: 'Get details about currently signed in user',
summary: `Get current user - Scope : ${Resources.USERS}:${Actions.READ_ONE}`,
Expand Down
11 changes: 6 additions & 5 deletions apps/orders/src/app/orders/orders.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
PermissionCheck,
} from '@ticketing/microservices/shared/decorators';
import {
OryAuthGuard,
OryAuthenticationGuard,
OryPermissionGuard,
} from '@ticketing/microservices/shared/guards';
import { PermissionNamespaces } from '@ticketing/microservices/shared/models';
Expand All @@ -48,6 +48,7 @@ import { OrdersService } from './orders.service';
export class OrdersController {
constructor(private readonly ordersService: OrdersService) {}

// TODO: check if ticket is reserved via Ory by adding orders to the tickets relations
@PermissionCheck((ctx) => {
const req = ctx.switchToHttp().getRequest<FastifyRequest>();
const currentUserId = get(req, `${CURRENT_USER_KEY}.id`);
Expand All @@ -62,7 +63,7 @@ export class OrdersController {
},
});
})
@UseGuards(OryAuthGuard, OryPermissionGuard)
@UseGuards(OryAuthenticationGuard, OryPermissionGuard)
@UsePipes(
new ValidationPipe({
transform: true,
Expand Down Expand Up @@ -91,7 +92,7 @@ export class OrdersController {
return this.ordersService.create(order, currentUser);
}

@UseGuards(OryAuthGuard)
@UseGuards(OryAuthenticationGuard)
@ApiBearerAuth(SecurityRequirements.Bearer)
@ApiCookieAuth(SecurityRequirements.Session)
@ApiOperation({
Expand Down Expand Up @@ -123,7 +124,7 @@ export class OrdersController {
},
});
})
@UseGuards(OryAuthGuard)
@UseGuards(OryAuthenticationGuard)
@ApiBearerAuth(SecurityRequirements.Bearer)
@ApiCookieAuth(SecurityRequirements.Session)
@ApiOperation({
Expand Down Expand Up @@ -154,7 +155,7 @@ export class OrdersController {
},
});
})
@UseGuards(OryAuthGuard)
@UseGuards(OryAuthenticationGuard)
@UsePipes(
new ValidationPipe({
transform: true,
Expand Down
7 changes: 6 additions & 1 deletion apps/orders/src/app/orders/orders.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ export class OrdersService {
);
await res[0].populate('ticket');
const order = res[0].toJSON<Order>();
this.logger.debug(`Created order ${order.id}`);
// 5. Create a relation between the ticket and the order
const relationTupleWithTicket = new RelationTuple(
PermissionNamespaces[Resources.ORDERS],
Expand All @@ -136,6 +137,9 @@ export class OrdersService {
},
);
await this.createRelationShip(relationTupleWithTicket);
this.logger.debug(
`Created relation ${relationTupleWithTicket.toString()}`,
);
// 6. Create a relation between the user and the order
const relationTupleWithUser = new RelationTuple(
PermissionNamespaces[Resources.ORDERS],
Expand All @@ -147,9 +151,10 @@ export class OrdersService {
},
);
await this.createRelationShip(relationTupleWithUser);

this.logger.debug(`Created relation ${relationTupleWithUser.toString()}`);
// 7. Publish an event
await lastValueFrom(this.emitEvent(Patterns.OrderCreated, order));
this.logger.debug(`Sent event ${Patterns.OrderCreated}`);
return order;
});
if (result.error) {
Expand Down
4 changes: 2 additions & 2 deletions apps/payments/src/app/payments/payments.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
PermissionCheck,
} from '@ticketing/microservices/shared/decorators';
import {
OryAuthGuard,
OryAuthenticationGuard,
OryPermissionGuard,
} from '@ticketing/microservices/shared/guards';
import { PermissionNamespaces } from '@ticketing/microservices/shared/models';
Expand Down Expand Up @@ -58,7 +58,7 @@ export class PaymentsController {
},
});
})
@UseGuards(OryAuthGuard, OryPermissionGuard)
@UseGuards(OryAuthenticationGuard, OryPermissionGuard)
@UsePipes(
new ValidationPipe({
transform: true,
Expand Down
19 changes: 6 additions & 13 deletions apps/payments/src/app/payments/payments.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
Injectable,
Logger,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { InjectModel } from '@nestjs/mongoose';
Expand Down Expand Up @@ -65,20 +64,14 @@ export class PaymentsService {
if (!order) {
throw new NotFoundException(`Order ${orderId} not found`);
}
// 2. make sure the order belongs to the user
if (order.userId !== currentUser.id) {
throw new UnauthorizedException(
`User ${currentUser.id} is not a valid owner`,
);
}
// 3. make sure the order is not cancelled
// 2. make sure the order is not cancelled
if (order.status === OrderStatus.Cancelled) {
throw new BadRequestException(
`Order ${orderId} has been cancelled and can't be paid for`,
);
}

// 4. make sure the payment amount match the order price and create payment with Stripe
// 3. make sure the payment amount match the order price and create payment with Stripe
const charge = await this.stripeService.charges.create(
{
amount: order.price * 100,
Expand All @@ -92,7 +85,7 @@ export class PaymentsService {

await using manager = await transactionManager(this.paymentModel);
const result = await manager.wrap(async (session) => {
// 5. Create charge instance in Mongo
// 4. Create charge instance in Mongo
const res = await this.paymentModel.create(
[
{
Expand All @@ -103,7 +96,7 @@ export class PaymentsService {
{ session },
);
const payment = res[0].toJSON<Payment>();
// 6. create a relation between the order and the payment
// 5. create a relation between the order and the payment
const relationTupleWithOrder = new RelationTuple(
PermissionNamespaces[Resources.PAYMENTS],
payment.id,
Expand All @@ -115,7 +108,7 @@ export class PaymentsService {
);
await this.createRelationShip(relationTupleWithOrder);

// 7. create a relation between the user and the payment
// 6. create a relation between the user and the payment
const relationTupleWithUser = new RelationTuple(
PermissionNamespaces[Resources.PAYMENTS],
payment.id,
Expand All @@ -127,7 +120,7 @@ export class PaymentsService {
);
await this.createRelationShip(relationTupleWithUser);

// 8. emit payment:create event
// 7. emit payment:create event
await firstValueFrom(
this.client.emit<
PaymentCreatedEvent['name'],
Expand Down
6 changes: 3 additions & 3 deletions apps/tickets/src/app/tickets/tickets.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {
PermissionCheck,
} from '@ticketing/microservices/shared/decorators';
import {
OryAuthGuard,
OryAuthenticationGuard,
OryPermissionGuard,
} from '@ticketing/microservices/shared/guards';
import {
Expand Down Expand Up @@ -68,7 +68,7 @@ import { TicketsService } from './tickets.service';
export class TicketsController {
constructor(private readonly ticketsService: TicketsService) {}

@UseGuards(OryAuthGuard)
@UseGuards(OryAuthenticationGuard)
@UsePipes(
new ValidationPipe({
transform: true,
Expand Down Expand Up @@ -146,7 +146,7 @@ export class TicketsController {
},
});
})
@UseGuards(OryAuthGuard, OryPermissionGuard)
@UseGuards(OryAuthenticationGuard, OryPermissionGuard)
@UsePipes(
new ValidationPipe({
transform: true,
Expand Down
2 changes: 1 addition & 1 deletion libs/microservices/shared/guards/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export * from './jwt.strategy';
export * from './jwt-auth.guard';
export * from './ory-action-auth.guard';
export * from './ory-auth.guard';
export * from './ory-authentication.guard';
export * from './ory-permission.guard';
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import {
Logger,
UnauthorizedException,
} from '@nestjs/common';
import { OryService } from '@ticketing/microservices/ory-client';
import { OryAuthenticationService } from '@ticketing/microservices/ory-client';
import type { FastifyRequest } from 'fastify/types/request';

@Injectable()
export class OryAuthGuard implements CanActivate {
readonly logger = new Logger(OryAuthGuard.name);
export class OryAuthenticationGuard implements CanActivate {
readonly logger = new Logger(OryAuthenticationGuard.name);

constructor(@Inject(OryService) private readonly oryService: OryService) {}
constructor(
@Inject(OryAuthenticationService)
private readonly oryService: OryAuthenticationService,
) {}

private getRequest(context: ExecutionContext): FastifyRequest {
return context.switchToHttp().getRequest();
Expand Down

0 comments on commit fc93a58

Please sign in to comment.