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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
331 changes: 331 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@
"@nestjs/core": "^11.0.1",
"@nestjs/jwt": "^11.0.0",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/platform-socket.io": "^11.1.0",
"@nestjs/swagger": "^11.0.6",
"@nestjs/typeorm": "^11.0.0",
"@nestjs/websockets": "^11.1.0",
"@tensorflow/tfjs-node": "^4.22.0",
"@types/bcrypt": "^5.0.2",
"bcryptjs": "^3.0.2",
Expand Down
35 changes: 35 additions & 0 deletions src/auth/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { Socket } from 'socket.io';
import { ConfigService } from '@nestjs/config';
import { UserService } from 'src/user/user.service';
import { User } from 'src/user/entities/user.entity';
Expand Down Expand Up @@ -50,3 +51,37 @@ export class AuthGuard implements CanActivate {
return type === 'Bearer' ? token : undefined;
}
}

@Injectable()
export class AuthGuardWs implements CanActivate {
constructor(
private jwtService: JwtService,
private configService: ConfigService,
private userService: UserService,
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const client: Socket = context.switchToWs().getClient();
const token = client.handshake.headers['authorization']?.split(' ')[1];
if (!token) {
client.disconnect();
return false;
}
let payload: JwtPayload;
try {
payload = this.jwtService.verify(token, {
secret: this.configService.get('JWT_SECRET'),
});
} catch {
client.disconnect();
return false;
}
const user = await this.userService.findByEmail(payload.email);
if (!user) {
throw new UnauthorizedException();
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
client.data.user = user;
return true;
}
}
29 changes: 29 additions & 0 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import {
BadRequestException,
ForbiddenException,
} from '@nestjs/common';
import { Socket } from 'socket.io';
import { plainToInstance } from 'class-transformer';
import { UserService } from 'src/user/user.service';
import { LoginDTO, LoginResponseDTO } from './dto/login.dto';
import { UserDTO } from 'src/user/dto/user.dto';
import { JwtService } from '@nestjs/jwt';
import { User, UserRole } from 'src/user/entities/user.entity';
import { ConfigService } from '@nestjs/config';
import { JwtPayload } from './auth.type';

@Injectable()
export class AuthService {
Expand Down Expand Up @@ -97,4 +99,31 @@ export class AuthService {
async validatePassword(user: User, password: string): Promise<boolean> {
return await bcrypt.compare(password, user.password);
}

async validateUserWs(client: Socket) {
const token = client.handshake.headers['authorization']?.split(' ')[1];
if (!token) {
client.disconnect();
return;
}
let payload: JwtPayload;
try {
payload = this.jwtService.verify(token, {
secret: this.configService.get('JWT_SECRET'),
});
} catch {
client.disconnect();
return;
}
const user = await this.userService.findByEmail(payload.email);
if (!user) {
client.disconnect();
return;
}
await this.userService.setWsId(user.email, client.id);
}

async disconnectUserWs(client: Socket) {
await this.userService.removeWsId(client.id);
}
}
33 changes: 32 additions & 1 deletion src/auth/roles.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from 'src/auth/roles.decorador';
import { Request } from 'express';
import { UserRole } from 'src/user/entities/user.entity';
import { Socket } from 'socket.io';
import { User, UserRole } from 'src/user/entities/user.entity';

interface RequestWithUser extends Request {
user?: { role: UserRole };
Expand Down Expand Up @@ -46,3 +47,33 @@ export class RolesGuard implements CanActivate {
return true;
}
}

@Injectable()
export class RolesGuardWs implements CanActivate {
constructor(private reflector: Reflector) {}

canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<UserRole[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);

if (!requiredRoles || requiredRoles.length === 0) {
return true;
}

const client: Socket = context.switchToWs().getClient();
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const user: User = client.data.user as User;

if (!user) {
return false;
}

if (!requiredRoles.includes(user.role)) {
return false;
}

return true;
}
}
14 changes: 14 additions & 0 deletions src/order/dto/order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,17 @@ export class UpdateOrderStatusDTO {
@IsEnum(OrderStatus)
status: OrderStatus;
}

export class UpdateOrderStatusWsDTO {
@ApiProperty({ description: 'ID of the order' })
@IsString()
@IsUUID()
id: string;

@ApiProperty({
description: 'New status of the order',
enum: OrderStatus,
})
@IsEnum(OrderStatus)
status: OrderStatus;
}
77 changes: 77 additions & 0 deletions src/order/order.gateway.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import {
UseFilters,
UseGuards,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import {
ConnectedSocket,
MessageBody,
OnGatewayConnection,
OnGatewayDisconnect,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
WsException,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { UpdateOrderStatusWsDTO } from './dto/order';
import { OrderService } from './order.service';
import { AuthGuardWs } from 'src/auth/auth.guard';
import { AuthService } from 'src/auth/auth.service';
import { RolesGuardWs } from 'src/auth/roles.guard';
import { Roles } from 'src/auth/roles.decorador';
import { UserRole } from 'src/user/entities/user.entity';
import { WebsocketExceptionsFilter } from './ws.filters';

@WebSocketGateway({
cors: {
origin: '*',
},
})
export class OrderGateway implements OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server: Server;
connections: Socket[] = [];

constructor(
private readonly authService: AuthService,
private readonly orderService: OrderService,
) {}

handleConnection(client: Socket) {
this.authService.validateUserWs(client);

Check warning on line 43 in src/order/order.gateway.ts

View workflow job for this annotation

GitHub Actions / lint

Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator
}

handleDisconnect(client: Socket) {
this.authService.disconnectUserWs(client);

Check warning on line 47 in src/order/order.gateway.ts

View workflow job for this annotation

GitHub Actions / lint

Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator
}

@UseFilters(new WebsocketExceptionsFilter())
@UsePipes(
new ValidationPipe({
exceptionFactory: (errors) => new WsException(errors),
}),
)
@UseGuards(AuthGuardWs, RolesGuardWs)
@Roles(UserRole.ADMIN, UserRole.BRANCH_ADMIN)
@SubscribeMessage('updateOrder')
update(
@ConnectedSocket() client: Socket,
@MessageBody() data: UpdateOrderStatusWsDTO,
) {
this.orderService.update(data.id, data.status).then((order) => {

Check warning on line 63 in src/order/order.gateway.ts

View workflow job for this annotation

GitHub Actions / lint

Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator
if (!order) {
this.server.to(client.id).emit('error', {
message: 'Order not found',
data: { id: data.id },
});
}
this.orderService.getUserByOrderId(order.id).then((user) => {

Check warning on line 70 in src/order/order.gateway.ts

View workflow job for this annotation

GitHub Actions / lint

Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator
if (user.wsId) {
client.to(user.wsId).emit('order', order);
}
});
});
}
}
2 changes: 2 additions & 0 deletions src/order/order.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { OrderController } from './controllers/order.controller';
import { Coupon } from 'src/discount/entities/coupon.entity';
import { CouponService } from 'src/discount/services/coupon.service';
import { InventoryModule } from 'src/inventory/inventory.module';
import { OrderGateway } from './order.gateway';

@Module({
imports: [
Expand Down Expand Up @@ -53,6 +54,7 @@ import { InventoryModule } from 'src/inventory/inventory.module';
CountryService,
PromoService,
CouponService,
OrderGateway,
],
exports: [OrderService],
})
Expand Down
20 changes: 18 additions & 2 deletions src/order/order.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,13 @@ export class OrderService {
async update(id: string, status: OrderStatus): Promise<Order> {
const order = await this.findOne(id);
if (order.status === OrderStatus.COMPLETED) {
throw new BadRequestException('A COMPLETED order cannot be modified');
console.log('A COMPLETED order cannot be modified');
return order;
}
if (status === OrderStatus.APPROVED) {
if (
status === OrderStatus.APPROVED &&
order.status !== OrderStatus.APPROVED
) {
for (const detail of order.details) {
const inv = await this.inventoryService.findByPresentationAndBranch(
detail.productPresentation.id,
Expand Down Expand Up @@ -479,6 +483,18 @@ export class OrderService {
{} as Record<OrderStatus, number>,
);
}

async getUserByOrderId(orderId: string): Promise<User> {
const order = await this.orderRepository.findOne({
where: { id: orderId },
relations: ['user'],
});
if (!order) {
throw new NotFoundException('Order not found');
}
return order.user;
}

async getSalesReport(
startDate: Date,
endDate: Date,
Expand Down
28 changes: 28 additions & 0 deletions src/order/ws.filters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { ArgumentsHost, Catch, HttpException } from '@nestjs/common';
import { BaseWsExceptionFilter, WsException } from '@nestjs/websockets';
import { Socket } from 'socket.io';

@Catch(WsException, HttpException)
export class WebsocketExceptionsFilter extends BaseWsExceptionFilter {
catch(exception: WsException | HttpException, host: ArgumentsHost) {
const client: Socket = host.switchToWs().getClient();
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const data: any = host.switchToWs().getData();
const error =
exception instanceof WsException
? exception.getError()
: exception.getResponse();
const details = error instanceof Object ? { ...error } : { message: error };
client.send(
JSON.stringify({
event: 'error',
data: {
id: client.id,
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
rid: data.rid as string,
...details,
},
}),
);
}
}
3 changes: 3 additions & 0 deletions src/user/entities/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,7 @@ export class User extends BaseModel {
eager: true,
})
userMoto: UserMoto;

@Column({ type: 'character varying', name: 'ws_id', nullable: true })
wsId: string | undefined;
}
13 changes: 13 additions & 0 deletions src/user/migrations/1746249862267-add-ws-id-user-migration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddWsIdUserMigration1746249862267 implements MigrationInterface {
name = 'AddWsIdUserMigration1746249862267';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "user" ADD "ws_id" character varying`);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "user" DROP COLUMN "ws_id"`);
}
}
18 changes: 18 additions & 0 deletions src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,4 +369,22 @@ export class UserService {

return qb.getCount();
}

async setWsId(email: string, wsId: string): Promise<void> {
const user = await this.findByEmail(email);
if (!user) {
return;
}
user.wsId = wsId;
await this.userRepository.save(user);
}

async removeWsId(wsId: string): Promise<void> {
const user = await this.userRepository.findOneBy({ wsId });
if (!user) {
return;
}
user.wsId = undefined;
await this.userRepository.save(user);
}
}
Loading