mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-11-26 23:44:53 +00:00
71 lines
1.9 KiB
TypeScript
71 lines
1.9 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 { UserRepository } from '@app/common/modules/user/repositories';
|
|
|
|
@Injectable()
|
|
export class CheckUserUnitGuard implements CanActivate {
|
|
constructor(
|
|
private readonly spaceRepository: SpaceRepository,
|
|
private readonly userRepository: UserRepository,
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const req = context.switchToHttp().getRequest();
|
|
|
|
try {
|
|
const { userUuid, unitUuid } = req.body;
|
|
|
|
await this.checkUserIsFound(userUuid);
|
|
|
|
await this.checkUnitIsFound(unitUuid);
|
|
|
|
return true;
|
|
} catch (error) {
|
|
this.handleGuardError(error, context);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private async checkUserIsFound(userUuid: string) {
|
|
const userData = await this.userRepository.findOne({
|
|
where: { uuid: userUuid },
|
|
});
|
|
if (!userData) {
|
|
throw new NotFoundException('User not found');
|
|
}
|
|
}
|
|
|
|
private async checkUnitIsFound(spaceUuid: string) {
|
|
const spaceData = await this.spaceRepository.findOne({
|
|
where: { uuid: spaceUuid },
|
|
relations: ['spaceType'],
|
|
});
|
|
if (!spaceData) {
|
|
throw new NotFoundException('Unit not found');
|
|
}
|
|
}
|
|
|
|
private handleGuardError(error: Error, context: ExecutionContext) {
|
|
const response = context.switchToHttp().getResponse();
|
|
if (
|
|
error instanceof BadRequestException ||
|
|
error instanceof NotFoundException
|
|
) {
|
|
response
|
|
.status(HttpStatus.NOT_FOUND)
|
|
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
|
} else {
|
|
response.status(HttpStatus.BAD_REQUEST).json({
|
|
statusCode: HttpStatus.BAD_REQUEST,
|
|
message: 'invalid userUuid or unitUuid',
|
|
});
|
|
}
|
|
}
|
|
}
|