mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-11-27 08:04:55 +00:00
84 lines
2.4 KiB
TypeScript
84 lines
2.4 KiB
TypeScript
import {
|
|
CanActivate,
|
|
ExecutionContext,
|
|
Injectable,
|
|
HttpStatus,
|
|
} from '@nestjs/common';
|
|
|
|
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
|
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
|
|
|
@Injectable()
|
|
export class CheckRoomGuard implements CanActivate {
|
|
constructor(
|
|
private readonly spaceRepository: SpaceRepository,
|
|
private readonly deviceRepository: DeviceRepository,
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const req = context.switchToHttp().getRequest();
|
|
|
|
try {
|
|
if (req.query && req.query.roomUuid) {
|
|
const { roomUuid } = req.query;
|
|
await this.checkRoomIsFound(roomUuid);
|
|
} else if (req.body && req.body.roomUuid && req.body.deviceUuid) {
|
|
const { roomUuid, deviceUuid } = req.body;
|
|
await this.checkRoomIsFound(roomUuid);
|
|
await this.checkDeviceIsFound(deviceUuid);
|
|
} else {
|
|
throw new BadRequestException('Invalid request parameters');
|
|
}
|
|
|
|
return true;
|
|
} catch (error) {
|
|
this.handleGuardError(error, context);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private async checkRoomIsFound(roomUuid: string) {
|
|
const room = await this.spaceRepository.findOne({
|
|
where: {
|
|
uuid: roomUuid,
|
|
spaceType: {
|
|
type: 'room',
|
|
},
|
|
},
|
|
});
|
|
if (!room) {
|
|
throw new NotFoundException('Room not found');
|
|
}
|
|
}
|
|
async checkDeviceIsFound(deviceUuid: string) {
|
|
const response = await this.deviceRepository.findOne({
|
|
where: {
|
|
uuid: deviceUuid,
|
|
},
|
|
});
|
|
|
|
if (!response.uuid) {
|
|
throw new NotFoundException('Device not found');
|
|
}
|
|
}
|
|
|
|
private handleGuardError(error: Error, context: ExecutionContext) {
|
|
const response = context.switchToHttp().getResponse();
|
|
if (error instanceof NotFoundException) {
|
|
response
|
|
.status(HttpStatus.NOT_FOUND)
|
|
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
|
} else if (error instanceof BadRequestException) {
|
|
response
|
|
.status(HttpStatus.BAD_REQUEST)
|
|
.json({ statusCode: HttpStatus.BAD_REQUEST, message: error.message });
|
|
} else {
|
|
response.status(HttpStatus.BAD_REQUEST).json({
|
|
statusCode: HttpStatus.BAD_REQUEST,
|
|
message: error.message || 'Invalid UUID',
|
|
});
|
|
}
|
|
}
|
|
}
|