mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-16 02:36:19 +00:00
Merge branch 'dev' into SP-197-be-retrieve-devices-in-the-gateway
This commit is contained in:
@ -12,6 +12,8 @@ import { CommunityModule } from './community/community.module';
|
||||
import { BuildingModule } from './building/building.module';
|
||||
import { FloorModule } from './floor/floor.module';
|
||||
import { UnitModule } from './unit/unit.module';
|
||||
import { RoleModule } from './role/role.module';
|
||||
import { SeederModule } from '@app/common/seed/seeder.module';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
@ -19,6 +21,7 @@ import { UnitModule } from './unit/unit.module';
|
||||
}),
|
||||
AuthenticationModule,
|
||||
UserModule,
|
||||
RoleModule,
|
||||
CommunityModule,
|
||||
BuildingModule,
|
||||
FloorModule,
|
||||
@ -28,6 +31,7 @@ import { UnitModule } from './unit/unit.module';
|
||||
GroupModule,
|
||||
DeviceModule,
|
||||
UserDevicePermissionModule,
|
||||
SeederModule,
|
||||
],
|
||||
controllers: [AuthenticationController],
|
||||
})
|
||||
|
@ -9,6 +9,8 @@ import { UserAuthService } from './services';
|
||||
import { UserRepository } from '../../libs/common/src/modules/user/repositories';
|
||||
import { UserSessionRepository } from '../../libs/common/src/modules/session/repositories/session.repository';
|
||||
import { UserOtpRepository } from '../../libs/common/src/modules/user-otp/repositories/user-otp.repository';
|
||||
import { UserRoleRepository } from '@app/common/modules/user-role/repositories';
|
||||
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, UserRepositoryModule, CommonModule],
|
||||
@ -19,6 +21,8 @@ import { UserOtpRepository } from '../../libs/common/src/modules/user-otp/reposi
|
||||
UserRepository,
|
||||
UserSessionRepository,
|
||||
UserOtpRepository,
|
||||
UserRoleRepository,
|
||||
RoleTypeRepository,
|
||||
],
|
||||
exports: [AuthenticationService, UserAuthService],
|
||||
})
|
||||
|
@ -14,9 +14,9 @@ import { UserSignUpDto } from '../dtos/user-auth.dto';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { ResponseMessage } from '../../../libs/common/src/response/response.decorator';
|
||||
import { UserLoginDto } from '../dtos/user-login.dto';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { ForgetPasswordDto, UserOtpDto, VerifyOtpDto } from '../dtos';
|
||||
import { RefreshTokenGuard } from '@app/common/guards/jwt-refresh.auth.guard';
|
||||
import { SuperAdminRoleGuard } from 'src/guards/super.admin.role.guard';
|
||||
|
||||
@Controller({
|
||||
version: '1',
|
||||
@ -47,12 +47,12 @@ export class UserAuthController {
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
data: accessToken,
|
||||
message: 'User Loggedin Successfully',
|
||||
message: 'User Logged in Successfully',
|
||||
};
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(SuperAdminRoleGuard)
|
||||
@Delete('user/delete/:id')
|
||||
async userDelete(@Param('id') id: string) {
|
||||
await this.userAuthService.deleteUser(id);
|
||||
@ -98,7 +98,7 @@ export class UserAuthController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(SuperAdminRoleGuard)
|
||||
@Get('user/list')
|
||||
async userList() {
|
||||
const userList = await this.userAuthService.userList();
|
||||
|
@ -1,3 +1,5 @@
|
||||
import { RoleTypeRepository } from './../../../libs/common/src/modules/role-type/repositories/role.type.repository';
|
||||
import { UserRoleRepository } from './../../../libs/common/src/modules/user-role/repositories/user.role.repository';
|
||||
import { UserRepository } from '../../../libs/common/src/modules/user/repositories';
|
||||
import {
|
||||
BadRequestException,
|
||||
@ -26,6 +28,8 @@ export class UserAuthService {
|
||||
private readonly helperHashService: HelperHashService,
|
||||
private readonly authService: AuthService,
|
||||
private readonly emailService: EmailService,
|
||||
private readonly userRoleRepository: UserRoleRepository,
|
||||
private readonly roleTypeRepository: RoleTypeRepository,
|
||||
) {}
|
||||
|
||||
async signUp(userSignUpDto: UserSignUpDto): Promise<UserEntity> {
|
||||
@ -33,12 +37,22 @@ export class UserAuthService {
|
||||
if (findUser) {
|
||||
throw new BadRequestException('User already registered with given email');
|
||||
}
|
||||
const salt = this.helperHashService.randomSalt(10);
|
||||
const password = this.helperHashService.bcrypt(
|
||||
const salt = this.helperHashService.randomSalt(10); // Hash the password using bcrypt
|
||||
const hashedPassword = await this.helperHashService.bcrypt(
|
||||
userSignUpDto.password,
|
||||
salt,
|
||||
);
|
||||
return await this.userRepository.save({ ...userSignUpDto, password });
|
||||
|
||||
try {
|
||||
const user = await this.userRepository.save({
|
||||
...userSignUpDto,
|
||||
password: hashedPassword,
|
||||
});
|
||||
|
||||
return user;
|
||||
} catch (error) {
|
||||
throw new BadRequestException('Failed to register user');
|
||||
}
|
||||
}
|
||||
|
||||
async findUser(email: string) {
|
||||
@ -67,6 +81,7 @@ export class UserAuthService {
|
||||
|
||||
async userLogin(data: UserLoginDto) {
|
||||
const user = await this.authService.validateUser(data.email, data.password);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('Invalid login credentials.');
|
||||
}
|
||||
@ -89,6 +104,9 @@ export class UserAuthService {
|
||||
email: user.email,
|
||||
userId: user.uuid,
|
||||
uuid: user.uuid,
|
||||
roles: user?.roles?.map((role) => {
|
||||
return { uuid: role.uuid, type: role.roleType.type };
|
||||
}),
|
||||
sessionId: session[1].uuid,
|
||||
});
|
||||
}
|
||||
|
@ -12,12 +12,14 @@ import {
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddBuildingDto, AddUserBuildingDto } from '../dtos/add.building.dto';
|
||||
import { GetBuildingChildDto } from '../dtos/get.building.dto';
|
||||
import { UpdateBuildingNameDto } from '../dtos/update.building.dto';
|
||||
import { CheckCommunityTypeGuard } from 'src/guards/community.type.guard';
|
||||
import { CheckUserBuildingGuard } from 'src/guards/user.building.guard';
|
||||
import { AdminRoleGuard } from 'src/guards/admin.role.guard';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { BuildingPermissionGuard } from 'src/guards/building.permission.guard';
|
||||
|
||||
@ApiTags('Building Module')
|
||||
@Controller({
|
||||
@ -28,12 +30,17 @@ export class BuildingController {
|
||||
constructor(private readonly buildingService: BuildingService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckCommunityTypeGuard)
|
||||
@UseGuards(AdminRoleGuard, CheckCommunityTypeGuard)
|
||||
@Post()
|
||||
async addBuilding(@Body() addBuildingDto: AddBuildingDto) {
|
||||
try {
|
||||
const building = await this.buildingService.addBuilding(addBuildingDto);
|
||||
return { message: 'Building added successfully', uuid: building.uuid };
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'Building added successfully',
|
||||
data: building,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -43,7 +50,7 @@ export class BuildingController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, BuildingPermissionGuard)
|
||||
@Get(':buildingUuid')
|
||||
async getBuildingByUuid(@Param('buildingUuid') buildingUuid: string) {
|
||||
try {
|
||||
@ -59,7 +66,7 @@ export class BuildingController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, BuildingPermissionGuard)
|
||||
@Get('child/:buildingUuid')
|
||||
async getBuildingChildByUuid(
|
||||
@Param('buildingUuid') buildingUuid: string,
|
||||
@ -79,7 +86,7 @@ export class BuildingController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, BuildingPermissionGuard)
|
||||
@Get('parent/:buildingUuid')
|
||||
async getBuildingParentByUuid(@Param('buildingUuid') buildingUuid: string) {
|
||||
try {
|
||||
@ -94,12 +101,16 @@ export class BuildingController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserBuildingGuard)
|
||||
@UseGuards(AdminRoleGuard, CheckUserBuildingGuard)
|
||||
@Post('user')
|
||||
async addUserBuilding(@Body() addUserBuildingDto: AddUserBuildingDto) {
|
||||
try {
|
||||
await this.buildingService.addUserBuilding(addUserBuildingDto);
|
||||
return { message: 'user building added successfully' };
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'user building added successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -122,7 +133,7 @@ export class BuildingController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, BuildingPermissionGuard)
|
||||
@Put('rename/:buildingUuid')
|
||||
async renameBuildingByUuid(
|
||||
@Param('buildingUuid') buildingUuid: string,
|
||||
|
@ -10,6 +10,7 @@ import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.s
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { SpacePermissionService } from '@app/common/helper/services';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@ -26,7 +27,8 @@ import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
SpacePermissionService,
|
||||
],
|
||||
exports: [CommunityService],
|
||||
exports: [CommunityService, SpacePermissionService],
|
||||
})
|
||||
export class CommunityModule {}
|
||||
|
@ -12,7 +12,6 @@ import {
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import {
|
||||
AddCommunityDto,
|
||||
AddUserCommunityDto,
|
||||
@ -20,6 +19,9 @@ import {
|
||||
import { GetCommunityChildDto } from '../dtos/get.community.dto';
|
||||
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
||||
import { CheckUserCommunityGuard } from 'src/guards/user.community.guard';
|
||||
import { AdminRoleGuard } from 'src/guards/admin.role.guard';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { CommunityPermissionGuard } from 'src/guards/community.permission.guard';
|
||||
|
||||
@ApiTags('Community Module')
|
||||
@Controller({
|
||||
@ -30,13 +32,18 @@ export class CommunityController {
|
||||
constructor(private readonly communityService: CommunityService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(AdminRoleGuard)
|
||||
@Post()
|
||||
async addCommunity(@Body() addCommunityDto: AddCommunityDto) {
|
||||
try {
|
||||
const community =
|
||||
await this.communityService.addCommunity(addCommunityDto);
|
||||
return { message: 'Community added successfully', uuid: community.uuid };
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'Community added successfully',
|
||||
data: community,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -46,7 +53,7 @@ export class CommunityController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, CommunityPermissionGuard)
|
||||
@Get(':communityUuid')
|
||||
async getCommunityByUuid(@Param('communityUuid') communityUuid: string) {
|
||||
try {
|
||||
@ -62,7 +69,7 @@ export class CommunityController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, CommunityPermissionGuard)
|
||||
@Get('child/:communityUuid')
|
||||
async getCommunityChildByUuid(
|
||||
@Param('communityUuid') communityUuid: string,
|
||||
@ -96,12 +103,16 @@ export class CommunityController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserCommunityGuard)
|
||||
@UseGuards(AdminRoleGuard, CheckUserCommunityGuard)
|
||||
@Post('user')
|
||||
async addUserCommunity(@Body() addUserCommunityDto: AddUserCommunityDto) {
|
||||
try {
|
||||
await this.communityService.addUserCommunity(addUserCommunityDto);
|
||||
return { message: 'user community added successfully' };
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'user community added successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -110,7 +121,7 @@ export class CommunityController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, CommunityPermissionGuard)
|
||||
@Put('rename/:communityUuid')
|
||||
async renameCommunityByUuid(
|
||||
@Param('communityUuid') communityUuid: string,
|
||||
|
@ -9,6 +9,7 @@ import {
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
UseGuards,
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import {
|
||||
@ -22,6 +23,8 @@ import {
|
||||
import { ControlDeviceDto } from '../dtos/control.device.dto';
|
||||
import { CheckRoomGuard } from 'src/guards/room.guard';
|
||||
import { CheckGroupGuard } from 'src/guards/group.guard';
|
||||
import { CheckUserHavePermission } from 'src/guards/user.device.permission.guard';
|
||||
import { CheckUserHaveControllablePermission } from 'src/guards/user.device.controllable.permission.guard';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
|
||||
@ApiTags('Device Module')
|
||||
@ -37,10 +40,13 @@ export class DeviceController {
|
||||
@Get('room')
|
||||
async getDevicesByRoomId(
|
||||
@Query() getDeviceByRoomUuidDto: GetDeviceByRoomUuidDto,
|
||||
@Req() req: any,
|
||||
) {
|
||||
try {
|
||||
const userUuid = req.user.uuid;
|
||||
return await this.deviceService.getDevicesByRoomId(
|
||||
getDeviceByRoomUuidDto,
|
||||
userUuid,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
@ -55,7 +61,15 @@ export class DeviceController {
|
||||
@Post('room')
|
||||
async addDeviceInRoom(@Body() addDeviceInRoomDto: AddDeviceInRoomDto) {
|
||||
try {
|
||||
return await this.deviceService.addDeviceInRoom(addDeviceInRoomDto);
|
||||
const device =
|
||||
await this.deviceService.addDeviceInRoom(addDeviceInRoomDto);
|
||||
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'device added in room successfully',
|
||||
data: device,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -68,10 +82,13 @@ export class DeviceController {
|
||||
@Get('group')
|
||||
async getDevicesByGroupId(
|
||||
@Query() getDeviceByGroupIdDto: GetDeviceByGroupIdDto,
|
||||
@Req() req: any,
|
||||
) {
|
||||
try {
|
||||
const userUuid = req.user.uuid;
|
||||
return await this.deviceService.getDevicesByGroupId(
|
||||
getDeviceByGroupIdDto,
|
||||
userUuid,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
@ -94,11 +111,18 @@ export class DeviceController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, CheckUserHavePermission)
|
||||
@Get(':deviceUuid')
|
||||
async getDeviceDetailsByDeviceId(@Param('deviceUuid') deviceUuid: string) {
|
||||
async getDeviceDetailsByDeviceId(
|
||||
@Param('deviceUuid') deviceUuid: string,
|
||||
@Req() req: any,
|
||||
) {
|
||||
try {
|
||||
return await this.deviceService.getDeviceDetailsByDeviceId(deviceUuid);
|
||||
const userUuid = req.user.uuid;
|
||||
return await this.deviceService.getDeviceDetailsByDeviceId(
|
||||
deviceUuid,
|
||||
userUuid,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -107,7 +131,7 @@ export class DeviceController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, CheckUserHavePermission)
|
||||
@Get(':deviceUuid/functions')
|
||||
async getDeviceInstructionByDeviceId(
|
||||
@Param('deviceUuid') deviceUuid: string,
|
||||
@ -124,7 +148,7 @@ export class DeviceController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, CheckUserHavePermission)
|
||||
@Get(':deviceUuid/functions/status')
|
||||
async getDevicesInstructionStatus(@Param('deviceUuid') deviceUuid: string) {
|
||||
try {
|
||||
@ -138,11 +162,17 @@ export class DeviceController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('control')
|
||||
async controlDevice(@Body() controlDeviceDto: ControlDeviceDto) {
|
||||
@UseGuards(JwtAuthGuard, CheckUserHaveControllablePermission)
|
||||
@Post(':deviceUuid/control')
|
||||
async controlDevice(
|
||||
@Body() controlDeviceDto: ControlDeviceDto,
|
||||
@Param('deviceUuid') deviceUuid: string,
|
||||
) {
|
||||
try {
|
||||
return await this.deviceService.controlDevice(controlDeviceDto);
|
||||
return await this.deviceService.controlDevice(
|
||||
controlDeviceDto,
|
||||
deviceUuid,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
|
@ -5,15 +5,14 @@ import { ConfigModule } from '@nestjs/config';
|
||||
import { ProductRepositoryModule } from '@app/common/modules/product/product.repository.module';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import { DeviceRepositoryModule } from '@app/common/modules/device';
|
||||
import {
|
||||
DeviceRepository,
|
||||
DeviceUserTypeRepository,
|
||||
} from '@app/common/modules/device/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||
import { GroupRepository } from '@app/common/modules/group/repositories';
|
||||
import { GroupRepositoryModule } from '@app/common/modules/group/group.repository.module';
|
||||
import { DeviceUserPermissionRepository } from '@app/common/modules/device-user-permission/repositories';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule,
|
||||
@ -25,12 +24,13 @@ import { GroupRepositoryModule } from '@app/common/modules/group/group.repositor
|
||||
providers: [
|
||||
DeviceService,
|
||||
ProductRepository,
|
||||
DeviceUserTypeRepository,
|
||||
DeviceUserPermissionRepository,
|
||||
PermissionTypeRepository,
|
||||
SpaceRepository,
|
||||
DeviceRepository,
|
||||
GroupDeviceRepository,
|
||||
GroupRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [DeviceService],
|
||||
})
|
||||
|
@ -2,14 +2,6 @@ import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class ControlDeviceDto {
|
||||
@ApiProperty({
|
||||
description: 'deviceUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public deviceUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'code',
|
||||
required: true,
|
||||
|
@ -4,7 +4,6 @@ import {
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
@ -18,7 +17,6 @@ import {
|
||||
GetDeviceDetailsFunctionsStatusInterface,
|
||||
GetDeviceDetailsInterface,
|
||||
controlDeviceInterface,
|
||||
updateDeviceFirmwareInterface,
|
||||
} from '../interfaces/get.device.interface';
|
||||
import {
|
||||
GetDeviceByGroupIdDto,
|
||||
@ -29,6 +27,8 @@ import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
import { In } from 'typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceService {
|
||||
@ -50,13 +50,25 @@ export class DeviceService {
|
||||
|
||||
async getDevicesByRoomId(
|
||||
getDeviceByRoomUuidDto: GetDeviceByRoomUuidDto,
|
||||
userUuid: string,
|
||||
): Promise<GetDeviceDetailsInterface[]> {
|
||||
try {
|
||||
const devices = await this.deviceRepository.find({
|
||||
where: {
|
||||
spaceDevice: { uuid: getDeviceByRoomUuidDto.roomUuid },
|
||||
permission: {
|
||||
userUuid,
|
||||
permissionType: {
|
||||
type: In([PermissionType.READ, PermissionType.CONTROLLABLE]),
|
||||
},
|
||||
},
|
||||
},
|
||||
relations: ['spaceDevice', 'productDevice'],
|
||||
relations: [
|
||||
'spaceDevice',
|
||||
'productDevice',
|
||||
'permission',
|
||||
'permission.permissionType',
|
||||
],
|
||||
});
|
||||
const devicesData = await Promise.all(
|
||||
devices.map(async (device) => {
|
||||
@ -67,9 +79,11 @@ export class DeviceService {
|
||||
uuid: device.uuid,
|
||||
productUuid: device.productDevice.uuid,
|
||||
productType: device.productDevice.prodType,
|
||||
permissionType: device.permission[0].permissionType.type,
|
||||
} as GetDeviceDetailsInterface;
|
||||
}),
|
||||
);
|
||||
|
||||
return devicesData;
|
||||
} catch (error) {
|
||||
// Handle the error here
|
||||
@ -80,11 +94,29 @@ export class DeviceService {
|
||||
}
|
||||
}
|
||||
|
||||
async getDevicesByGroupId(getDeviceByGroupIdDto: GetDeviceByGroupIdDto) {
|
||||
async getDevicesByGroupId(
|
||||
getDeviceByGroupIdDto: GetDeviceByGroupIdDto,
|
||||
userUuid: string,
|
||||
) {
|
||||
try {
|
||||
const groupDevices = await this.groupDeviceRepository.find({
|
||||
where: { group: { uuid: getDeviceByGroupIdDto.groupUuid } },
|
||||
relations: ['device'],
|
||||
where: {
|
||||
group: { uuid: getDeviceByGroupIdDto.groupUuid },
|
||||
device: {
|
||||
permission: {
|
||||
userUuid,
|
||||
permissionType: {
|
||||
type: PermissionType.READ || PermissionType.CONTROLLABLE,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
relations: [
|
||||
'device',
|
||||
'device.productDevice',
|
||||
'device.permission',
|
||||
'device.permission.permissionType',
|
||||
],
|
||||
});
|
||||
const devicesData = await Promise.all(
|
||||
groupDevices.map(async (device) => {
|
||||
@ -92,9 +124,10 @@ export class DeviceService {
|
||||
...(await this.getDeviceDetailsByDeviceIdTuya(
|
||||
device.device.deviceTuyaUuid,
|
||||
)),
|
||||
uuid: device.uuid,
|
||||
uuid: device.device.uuid,
|
||||
productUuid: device.device.productDevice.uuid,
|
||||
productType: device.device.productDevice.prodType,
|
||||
permissionType: device.device.permission[0].permissionType.type,
|
||||
} as GetDeviceDetailsInterface;
|
||||
}),
|
||||
);
|
||||
@ -107,7 +140,6 @@ export class DeviceService {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async addDeviceInRoom(addDeviceInRoomDto: AddDeviceInRoomDto) {
|
||||
try {
|
||||
const device = await this.getDeviceDetailsByDeviceIdTuya(
|
||||
@ -118,12 +150,11 @@ export class DeviceService {
|
||||
throw new Error('Product UUID is missing for the device.');
|
||||
}
|
||||
|
||||
await this.deviceRepository.save({
|
||||
return await this.deviceRepository.save({
|
||||
deviceTuyaUuid: addDeviceInRoomDto.deviceTuyaUuid,
|
||||
spaceDevice: { uuid: addDeviceInRoomDto.roomUuid },
|
||||
productDevice: { uuid: device.productUuid },
|
||||
});
|
||||
return { message: 'device added in room successfully' };
|
||||
} catch (error) {
|
||||
if (error.code === '23505') {
|
||||
throw new HttpException(
|
||||
@ -161,12 +192,9 @@ export class DeviceService {
|
||||
}
|
||||
}
|
||||
|
||||
async controlDevice(controlDeviceDto: ControlDeviceDto) {
|
||||
async controlDevice(controlDeviceDto: ControlDeviceDto, deviceUuid: string) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(
|
||||
controlDeviceDto.deviceUuid,
|
||||
false,
|
||||
);
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid, false);
|
||||
|
||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||
throw new NotFoundException('Device Not Found');
|
||||
@ -185,7 +213,10 @@ export class DeviceService {
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
throw new HttpException(
|
||||
error.message || 'Device Not Found',
|
||||
error.status || HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
}
|
||||
async controlDeviceTuya(
|
||||
@ -213,8 +244,19 @@ export class DeviceService {
|
||||
}
|
||||
}
|
||||
|
||||
async getDeviceDetailsByDeviceId(deviceUuid: string) {
|
||||
async getDeviceDetailsByDeviceId(deviceUuid: string, userUuid: string) {
|
||||
try {
|
||||
const userDevicePermission = await this.getUserDevicePermission(
|
||||
userUuid,
|
||||
deviceUuid,
|
||||
);
|
||||
|
||||
const deviceDetails = await this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: deviceUuid,
|
||||
},
|
||||
relations: ['productDevice'],
|
||||
});
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
|
||||
if (!deviceDetails) {
|
||||
@ -230,9 +272,13 @@ export class DeviceService {
|
||||
uuid: deviceDetails.uuid,
|
||||
productUuid: deviceDetails.productDevice.uuid,
|
||||
productType: deviceDetails.productDevice.prodType,
|
||||
permissionType: userDevicePermission,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
throw new HttpException(
|
||||
error.message || 'Device Not Found',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
}
|
||||
async getDeviceDetailsByDeviceIdTuya(
|
||||
@ -255,6 +301,7 @@ export class DeviceService {
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { productName, productId, id, ...rest } = camelCaseResponse.result;
|
||||
|
||||
return {
|
||||
...rest,
|
||||
productUuid: product.uuid,
|
||||
@ -465,4 +512,13 @@ export class DeviceService {
|
||||
);
|
||||
}
|
||||
}
|
||||
private async getUserDevicePermission(userUuid: string, deviceUuid: string) {
|
||||
const device = await this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: deviceUuid,
|
||||
},
|
||||
relations: ['permission', 'permission.permissionType'],
|
||||
});
|
||||
return device.permission[0].permissionType.type;
|
||||
}
|
||||
}
|
||||
|
@ -12,12 +12,14 @@ import {
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddFloorDto, AddUserFloorDto } from '../dtos/add.floor.dto';
|
||||
import { GetFloorChildDto } from '../dtos/get.floor.dto';
|
||||
import { UpdateFloorNameDto } from '../dtos/update.floor.dto';
|
||||
import { CheckBuildingTypeGuard } from 'src/guards/building.type.guard';
|
||||
import { CheckUserFloorGuard } from 'src/guards/user.floor.guard';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { AdminRoleGuard } from 'src/guards/admin.role.guard';
|
||||
import { FloorPermissionGuard } from 'src/guards/floor.permission.guard';
|
||||
|
||||
@ApiTags('Floor Module')
|
||||
@Controller({
|
||||
@ -28,12 +30,17 @@ export class FloorController {
|
||||
constructor(private readonly floorService: FloorService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckBuildingTypeGuard)
|
||||
@UseGuards(AdminRoleGuard, CheckBuildingTypeGuard)
|
||||
@Post()
|
||||
async addFloor(@Body() addFloorDto: AddFloorDto) {
|
||||
try {
|
||||
const floor = await this.floorService.addFloor(addFloorDto);
|
||||
return { message: 'Floor added successfully', uuid: floor.uuid };
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'Floor added successfully',
|
||||
data: floor,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -43,7 +50,7 @@ export class FloorController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, FloorPermissionGuard)
|
||||
@Get(':floorUuid')
|
||||
async getFloorByUuid(@Param('floorUuid') floorUuid: string) {
|
||||
try {
|
||||
@ -58,7 +65,7 @@ export class FloorController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, FloorPermissionGuard)
|
||||
@Get('child/:floorUuid')
|
||||
async getFloorChildByUuid(
|
||||
@Param('floorUuid') floorUuid: string,
|
||||
@ -78,7 +85,7 @@ export class FloorController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, FloorPermissionGuard)
|
||||
@Get('parent/:floorUuid')
|
||||
async getFloorParentByUuid(@Param('floorUuid') floorUuid: string) {
|
||||
try {
|
||||
@ -93,12 +100,16 @@ export class FloorController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserFloorGuard)
|
||||
@UseGuards(AdminRoleGuard, CheckUserFloorGuard)
|
||||
@Post('user')
|
||||
async addUserFloor(@Body() addUserFloorDto: AddUserFloorDto) {
|
||||
try {
|
||||
await this.floorService.addUserFloor(addUserFloorDto);
|
||||
return { message: 'user floor added successfully' };
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'user floor added successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -122,7 +133,7 @@ export class FloorController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, FloorPermissionGuard)
|
||||
@Put('rename/:floorUuid')
|
||||
async renameFloorByUuid(
|
||||
@Param('floorUuid') floorUuid: string,
|
||||
|
@ -12,11 +12,11 @@ import {
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddGroupDto } from '../dtos/add.group.dto';
|
||||
import { ControlGroupDto } from '../dtos/control.group.dto';
|
||||
import { RenameGroupDto } from '../dtos/rename.group.dto copy';
|
||||
import { CheckProductUuidForAllDevicesGuard } from 'src/guards/device.product.guard';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
|
||||
@ApiTags('Group Module')
|
||||
@Controller({
|
||||
|
20
src/guards/admin.role.guard.ts
Normal file
20
src/guards/admin.role.guard.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { BadRequestException, UnauthorizedException } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
export class AdminRoleGuard extends AuthGuard('jwt') {
|
||||
handleRequest(err, user) {
|
||||
if (err || !user) {
|
||||
throw err || new UnauthorizedException();
|
||||
} else {
|
||||
const isAdmin = user.roles.some(
|
||||
(role) =>
|
||||
role.type === RoleType.SUPER_ADMIN || role.type === RoleType.ADMIN,
|
||||
);
|
||||
if (!isAdmin) {
|
||||
throw new BadRequestException('Only admin role can access this route');
|
||||
}
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
35
src/guards/building.permission.guard.ts
Normal file
35
src/guards/building.permission.guard.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { SpacePermissionService } from '@app/common/helper/services/space.permission.service';
|
||||
import {
|
||||
BadRequestException,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class BuildingPermissionGuard implements CanActivate {
|
||||
constructor(private readonly permissionService: SpacePermissionService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { buildingUuid } = req.params;
|
||||
const { user } = req;
|
||||
|
||||
if (!buildingUuid) {
|
||||
throw new BadRequestException('buildingUuid is required');
|
||||
}
|
||||
|
||||
await this.permissionService.checkUserPermission(
|
||||
buildingUuid,
|
||||
user.uuid,
|
||||
'building',
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
35
src/guards/community.permission.guard.ts
Normal file
35
src/guards/community.permission.guard.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { SpacePermissionService } from '@app/common/helper/services/space.permission.service';
|
||||
import {
|
||||
BadRequestException,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class CommunityPermissionGuard implements CanActivate {
|
||||
constructor(private readonly permissionService: SpacePermissionService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { communityUuid } = req.params;
|
||||
const { user } = req;
|
||||
|
||||
if (!communityUuid) {
|
||||
throw new BadRequestException('communityUuid is required');
|
||||
}
|
||||
|
||||
await this.permissionService.checkUserPermission(
|
||||
communityUuid,
|
||||
user.uuid,
|
||||
'community',
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,97 +0,0 @@
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { DeviceUserTypeRepository } from '@app/common/modules/device/repositories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
HttpStatus,
|
||||
ExecutionContext,
|
||||
BadRequestException,
|
||||
applyDecorators,
|
||||
SetMetadata,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
|
||||
@Injectable()
|
||||
export class DevicePermissionGuard implements CanActivate {
|
||||
constructor(
|
||||
private reflector: Reflector,
|
||||
private readonly deviceUserTypeRepository: DeviceUserTypeRepository,
|
||||
private readonly permissionTypeRepository: PermissionTypeRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
try {
|
||||
const { deviceId } = req.headers;
|
||||
const userId = req.user.uuid;
|
||||
|
||||
const requirePermission =
|
||||
this.reflector.getAllAndOverride<PermissionType>('permission', [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (!requirePermission) {
|
||||
return true;
|
||||
}
|
||||
await this.checkDevicePermission(deviceId, userId, requirePermission);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async checkDevicePermission(
|
||||
deviceId: string,
|
||||
userId: string,
|
||||
requirePermission,
|
||||
) {
|
||||
const [userPermissionDetails, permissionDetails] = await Promise.all([
|
||||
this.deviceUserTypeRepository.findOne({
|
||||
where: { deviceUuid: deviceId, userUuid: userId },
|
||||
}),
|
||||
this.permissionTypeRepository.findOne({
|
||||
where: {
|
||||
type: requirePermission,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
if (!userPermissionDetails) {
|
||||
throw new BadRequestException('User Permission Details Not Found');
|
||||
}
|
||||
if (userPermissionDetails.permissionTypeUuid !== permissionDetails.uuid) {
|
||||
throw new BadRequestException(
|
||||
`User Does not have a ${requirePermission}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
console.error(error);
|
||||
|
||||
if (error instanceof BadRequestException) {
|
||||
response
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.json({ statusCode: HttpStatus.BAD_REQUEST, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.NOT_FOUND).json({
|
||||
statusCode: HttpStatus.NOT_FOUND,
|
||||
message: 'User Permission not found',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function AuthGuardWithRoles(permission?: string) {
|
||||
return applyDecorators(
|
||||
SetMetadata('permission', permission),
|
||||
UseGuards(JwtAuthGuard),
|
||||
UseGuards(DevicePermissionGuard),
|
||||
);
|
||||
}
|
35
src/guards/floor.permission.guard.ts
Normal file
35
src/guards/floor.permission.guard.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { SpacePermissionService } from '@app/common/helper/services/space.permission.service';
|
||||
import {
|
||||
BadRequestException,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class FloorPermissionGuard implements CanActivate {
|
||||
constructor(private readonly permissionService: SpacePermissionService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { floorUuid } = req.params;
|
||||
const { user } = req;
|
||||
|
||||
if (!floorUuid) {
|
||||
throw new BadRequestException('floorUuid is required');
|
||||
}
|
||||
|
||||
await this.permissionService.checkUserPermission(
|
||||
floorUuid,
|
||||
user.uuid,
|
||||
'floor',
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
35
src/guards/room.permission.guard.ts
Normal file
35
src/guards/room.permission.guard.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { SpacePermissionService } from '@app/common/helper/services/space.permission.service';
|
||||
import {
|
||||
BadRequestException,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class RoomPermissionGuard implements CanActivate {
|
||||
constructor(private readonly permissionService: SpacePermissionService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { roomUuid } = req.params;
|
||||
const { user } = req;
|
||||
|
||||
if (!roomUuid) {
|
||||
throw new BadRequestException('roomUuid is required');
|
||||
}
|
||||
|
||||
await this.permissionService.checkUserPermission(
|
||||
roomUuid,
|
||||
user.uuid,
|
||||
'room',
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
21
src/guards/super.admin.role.guard.ts
Normal file
21
src/guards/super.admin.role.guard.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { BadRequestException, UnauthorizedException } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
export class SuperAdminRoleGuard extends AuthGuard('jwt') {
|
||||
handleRequest(err, user) {
|
||||
if (err || !user) {
|
||||
throw err || new UnauthorizedException();
|
||||
} else {
|
||||
const isSuperAdmin = user.roles.some(
|
||||
(role) => role.type === RoleType.SUPER_ADMIN,
|
||||
);
|
||||
if (!isSuperAdmin) {
|
||||
throw new BadRequestException(
|
||||
'Only super admin role can access this route',
|
||||
);
|
||||
}
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
35
src/guards/unit.permission.guard.ts
Normal file
35
src/guards/unit.permission.guard.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { SpacePermissionService } from '@app/common/helper/services/space.permission.service';
|
||||
import {
|
||||
BadRequestException,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class UnitPermissionGuard implements CanActivate {
|
||||
constructor(private readonly permissionService: SpacePermissionService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { unitUuid } = req.params;
|
||||
const { user } = req;
|
||||
|
||||
if (!unitUuid) {
|
||||
throw new BadRequestException('unitUuid is required');
|
||||
}
|
||||
|
||||
await this.permissionService.checkUserPermission(
|
||||
unitUuid,
|
||||
user.uuid,
|
||||
'unit',
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
92
src/guards/user.device.controllable.permission.guard.ts
Normal file
92
src/guards/user.device.controllable.permission.guard.ts
Normal file
@ -0,0 +1,92 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserHaveControllablePermission implements CanActivate {
|
||||
constructor(
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const userUuid = req.user.uuid;
|
||||
const { deviceUuid } = req.params;
|
||||
|
||||
const userIsFound = await this.checkUserIsFound(userUuid);
|
||||
if (!userIsFound) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
const userDevicePermission = await this.checkUserDevicePermission(
|
||||
userUuid,
|
||||
deviceUuid,
|
||||
);
|
||||
|
||||
if (userDevicePermission === PermissionType.CONTROLLABLE) {
|
||||
return true;
|
||||
} else {
|
||||
throw new BadRequestException(
|
||||
'You do not have controllable access to this device',
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
return !!userData;
|
||||
}
|
||||
|
||||
private async checkUserDevicePermission(
|
||||
userUuid: string,
|
||||
deviceUuid: string,
|
||||
): Promise<string> {
|
||||
const device = await this.deviceRepository.findOne({
|
||||
where: { uuid: deviceUuid, permission: { userUuid: userUuid } },
|
||||
relations: ['permission', 'permission.permissionType'],
|
||||
});
|
||||
|
||||
if (!device) {
|
||||
throw new BadRequestException(
|
||||
'You do not have controllable access to this device',
|
||||
);
|
||||
}
|
||||
|
||||
return device.permission[0].permissionType.type; // Assuming permissionType is a string
|
||||
}
|
||||
|
||||
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.INTERNAL_SERVER_ERROR).json({
|
||||
statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
91
src/guards/user.device.permission.guard.ts
Normal file
91
src/guards/user.device.permission.guard.ts
Normal file
@ -0,0 +1,91 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserHavePermission implements CanActivate {
|
||||
constructor(
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const userUuid = req.user.uuid;
|
||||
const { deviceUuid } = req.params;
|
||||
|
||||
const userIsFound = await this.checkUserIsFound(userUuid);
|
||||
if (!userIsFound) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
const userDevicePermission = await this.checkUserDevicePermission(
|
||||
userUuid,
|
||||
deviceUuid,
|
||||
);
|
||||
|
||||
if (
|
||||
userDevicePermission === PermissionType.READ ||
|
||||
userDevicePermission === PermissionType.CONTROLLABLE
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
throw new BadRequestException('You do not have access to this device');
|
||||
}
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
return !!userData;
|
||||
}
|
||||
|
||||
private async checkUserDevicePermission(
|
||||
userUuid: string,
|
||||
deviceUuid: string,
|
||||
): Promise<string> {
|
||||
const device = await this.deviceRepository.findOne({
|
||||
where: { uuid: deviceUuid, permission: { userUuid: userUuid } },
|
||||
relations: ['permission', 'permission.permissionType'],
|
||||
});
|
||||
|
||||
if (!device) {
|
||||
throw new BadRequestException('You do not have access to this device');
|
||||
}
|
||||
|
||||
return device.permission[0].permissionType.type; // Assuming permissionType is a string
|
||||
}
|
||||
|
||||
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.INTERNAL_SERVER_ERROR).json({
|
||||
statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -4,6 +4,7 @@ import rateLimit from 'express-rate-limit';
|
||||
import helmet from 'helmet';
|
||||
import { setupSwaggerAuthentication } from '../libs/common/src/util/user-auth.swagger.utils';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { SeederService } from '@app/common/seed/services/seeder.service';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AuthModule);
|
||||
@ -34,6 +35,13 @@ async function bootstrap() {
|
||||
}),
|
||||
);
|
||||
|
||||
const seederService = app.get(SeederService);
|
||||
try {
|
||||
await seederService.seed();
|
||||
console.log('Seeding complete!');
|
||||
} catch (error) {
|
||||
console.error('Seeding failed!', error);
|
||||
}
|
||||
await app.listen(process.env.PORT || 4000);
|
||||
}
|
||||
console.log('Starting auth at port ...', process.env.PORT || 4000);
|
||||
|
1
src/role/controllers/index.ts
Normal file
1
src/role/controllers/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './role.controller';
|
54
src/role/controllers/role.controller.ts
Normal file
54
src/role/controllers/role.controller.ts
Normal file
@ -0,0 +1,54 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { RoleService } from '../services/role.service';
|
||||
import { AddUserRoleDto } from '../dtos';
|
||||
import { SuperAdminRoleGuard } from 'src/guards/super.admin.role.guard';
|
||||
|
||||
@ApiTags('Role Module')
|
||||
@Controller({
|
||||
version: '1',
|
||||
path: 'role',
|
||||
})
|
||||
export class RoleController {
|
||||
constructor(private readonly roleService: RoleService) {}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(SuperAdminRoleGuard)
|
||||
@Get('types')
|
||||
async fetchRoleTypes() {
|
||||
try {
|
||||
const roleTypes = await this.roleService.fetchRoleTypes();
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
message: 'Role Types fetched Successfully',
|
||||
data: roleTypes,
|
||||
};
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(SuperAdminRoleGuard)
|
||||
@Post()
|
||||
async addUserRoleType(@Body() addUserRoleDto: AddUserRoleDto) {
|
||||
try {
|
||||
await this.roleService.addUserRoleType(addUserRoleDto);
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
message: 'User Role Added Successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
1
src/role/dtos/index.ts
Normal file
1
src/role/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './role.add.dto';
|
24
src/role/dtos/role.add.dto.ts
Normal file
24
src/role/dtos/role.add.dto.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsEnum, IsIn, IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class AddUserRoleDto {
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Role type (ADMIN)',
|
||||
enum: [RoleType.ADMIN],
|
||||
required: true,
|
||||
})
|
||||
@IsEnum(RoleType)
|
||||
@IsIn([RoleType.ADMIN], {
|
||||
message: 'roleType must be one of the following values: ADMIN',
|
||||
})
|
||||
roleType: RoleType;
|
||||
}
|
25
src/role/role.module.ts
Normal file
25
src/role/role.module.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import { DeviceRepositoryModule } from '@app/common/modules/device';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { RoleService } from './services/role.service';
|
||||
import { RoleController } from './controllers/role.controller';
|
||||
import { DeviceUserPermissionRepository } from '@app/common/modules/device-user-permission/repositories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
|
||||
import { UserRoleRepository } from '@app/common/modules/user-role/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, DeviceRepositoryModule],
|
||||
controllers: [RoleController],
|
||||
providers: [
|
||||
DeviceUserPermissionRepository,
|
||||
PermissionTypeRepository,
|
||||
DeviceRepository,
|
||||
RoleService,
|
||||
RoleTypeRepository,
|
||||
UserRoleRepository,
|
||||
],
|
||||
exports: [RoleService],
|
||||
})
|
||||
export class RoleModule {}
|
1
src/role/services/index.ts
Normal file
1
src/role/services/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './role.service';
|
54
src/role/services/role.service.ts
Normal file
54
src/role/services/role.service.ts
Normal file
@ -0,0 +1,54 @@
|
||||
import { RoleTypeRepository } from './../../../libs/common/src/modules/role-type/repositories/role.type.repository';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { AddUserRoleDto } from '../dtos/role.add.dto';
|
||||
import { UserRoleRepository } from '@app/common/modules/user-role/repositories';
|
||||
import { QueryFailedError } from 'typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class RoleService {
|
||||
constructor(
|
||||
private readonly roleTypeRepository: RoleTypeRepository,
|
||||
private readonly userRoleRepository: UserRoleRepository,
|
||||
) {}
|
||||
|
||||
async addUserRoleType(addUserRoleDto: AddUserRoleDto) {
|
||||
try {
|
||||
const roleType = await this.fetchRoleByType(addUserRoleDto.roleType);
|
||||
|
||||
if (roleType.uuid) {
|
||||
return await this.userRoleRepository.save({
|
||||
user: { uuid: addUserRoleDto.userUuid },
|
||||
roleType: { uuid: roleType.uuid },
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof QueryFailedError &&
|
||||
error.driverError.code === '23505'
|
||||
) {
|
||||
// Postgres unique constraint violation error code
|
||||
throw new HttpException(
|
||||
'This role already exists for this user',
|
||||
HttpStatus.CONFLICT,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
error.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async fetchRoleTypes() {
|
||||
const roleTypes = await this.roleTypeRepository.find();
|
||||
|
||||
return roleTypes;
|
||||
}
|
||||
private async fetchRoleByType(roleType: string) {
|
||||
return await this.roleTypeRepository.findOne({
|
||||
where: {
|
||||
type: roleType,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
@ -11,11 +11,13 @@ import {
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddRoomDto, AddUserRoomDto } from '../dtos/add.room.dto';
|
||||
import { UpdateRoomNameDto } from '../dtos/update.room.dto';
|
||||
import { CheckUnitTypeGuard } from 'src/guards/unit.type.guard';
|
||||
import { CheckUserRoomGuard } from 'src/guards/user.room.guard';
|
||||
import { AdminRoleGuard } from 'src/guards/admin.role.guard';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { RoomPermissionGuard } from 'src/guards/room.permission.guard';
|
||||
|
||||
@ApiTags('Room Module')
|
||||
@Controller({
|
||||
@ -26,12 +28,17 @@ export class RoomController {
|
||||
constructor(private readonly roomService: RoomService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUnitTypeGuard)
|
||||
@UseGuards(AdminRoleGuard, CheckUnitTypeGuard)
|
||||
@Post()
|
||||
async addRoom(@Body() addRoomDto: AddRoomDto) {
|
||||
try {
|
||||
const room = await this.roomService.addRoom(addRoomDto);
|
||||
return { message: 'Room added successfully', uuid: room.uuid };
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'Room added successfully',
|
||||
data: room,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -41,7 +48,7 @@ export class RoomController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, RoomPermissionGuard)
|
||||
@Get(':roomUuid')
|
||||
async getRoomByUuid(@Param('roomUuid') roomUuid: string) {
|
||||
try {
|
||||
@ -56,7 +63,7 @@ export class RoomController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, RoomPermissionGuard)
|
||||
@Get('parent/:roomUuid')
|
||||
async getRoomParentByUuid(@Param('roomUuid') roomUuid: string) {
|
||||
try {
|
||||
@ -70,12 +77,16 @@ export class RoomController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserRoomGuard)
|
||||
@UseGuards(AdminRoleGuard, CheckUserRoomGuard)
|
||||
@Post('user')
|
||||
async addUserRoom(@Body() addUserRoomDto: AddUserRoomDto) {
|
||||
try {
|
||||
await this.roomService.addUserRoom(addUserRoomDto);
|
||||
return { message: 'user room added successfully' };
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'user room added successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -98,7 +109,7 @@ export class RoomController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, RoomPermissionGuard)
|
||||
@Put('rename/:roomUuid')
|
||||
async renameRoomByUuid(
|
||||
@Param('roomUuid') roomUuid: string,
|
||||
|
@ -12,12 +12,14 @@ import {
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddUnitDto, AddUserUnitDto } from '../dtos/add.unit.dto';
|
||||
import { GetUnitChildDto } from '../dtos/get.unit.dto';
|
||||
import { UpdateUnitNameDto } from '../dtos/update.unit.dto';
|
||||
import { CheckFloorTypeGuard } from 'src/guards/floor.type.guard';
|
||||
import { CheckUserUnitGuard } from 'src/guards/user.unit.guard';
|
||||
import { AdminRoleGuard } from 'src/guards/admin.role.guard';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { UnitPermissionGuard } from 'src/guards/unit.permission.guard';
|
||||
|
||||
@ApiTags('Unit Module')
|
||||
@Controller({
|
||||
@ -28,12 +30,17 @@ export class UnitController {
|
||||
constructor(private readonly unitService: UnitService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckFloorTypeGuard)
|
||||
@UseGuards(AdminRoleGuard, CheckFloorTypeGuard)
|
||||
@Post()
|
||||
async addUnit(@Body() addUnitDto: AddUnitDto) {
|
||||
try {
|
||||
const unit = await this.unitService.addUnit(addUnitDto);
|
||||
return { message: 'Unit added successfully', uuid: unit.uuid };
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'Unit added successfully',
|
||||
data: unit,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -43,7 +50,7 @@ export class UnitController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, UnitPermissionGuard)
|
||||
@Get(':unitUuid')
|
||||
async getUnitByUuid(@Param('unitUuid') unitUuid: string) {
|
||||
try {
|
||||
@ -58,7 +65,7 @@ export class UnitController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, UnitPermissionGuard)
|
||||
@Get('child/:unitUuid')
|
||||
async getUnitChildByUuid(
|
||||
@Param('unitUuid') unitUuid: string,
|
||||
@ -75,7 +82,7 @@ export class UnitController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, UnitPermissionGuard)
|
||||
@Get('parent/:unitUuid')
|
||||
async getUnitParentByUuid(@Param('unitUuid') unitUuid: string) {
|
||||
try {
|
||||
@ -89,12 +96,16 @@ export class UnitController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserUnitGuard)
|
||||
@UseGuards(AdminRoleGuard, CheckUserUnitGuard)
|
||||
@Post('user')
|
||||
async addUserUnit(@Body() addUserUnitDto: AddUserUnitDto) {
|
||||
try {
|
||||
await this.unitService.addUserUnit(addUserUnitDto);
|
||||
return { message: 'user unit added successfully' };
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'user unit added successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@ -117,7 +128,7 @@ export class UnitController {
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, UnitPermissionGuard)
|
||||
@Put('rename/:unitUuid')
|
||||
async renameUnitByUuid(
|
||||
@Param('unitUuid') unitUuid: string,
|
||||
|
@ -0,0 +1 @@
|
||||
export * from './user-device-permission.controller';
|
||||
|
@ -1,7 +1,9 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Param,
|
||||
Post,
|
||||
@ -11,8 +13,8 @@ import {
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { UserDevicePermissionService } from '../services/user-device-permission.service';
|
||||
import { UserDevicePermissionAddDto } from '../dtos/user-device-permission.add.dto';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { UserDevicePermissionEditDto } from '../dtos/user-device-permission.edit.dto';
|
||||
import { AdminRoleGuard } from 'src/guards/admin.role.guard';
|
||||
|
||||
@ApiTags('Device Permission Module')
|
||||
@Controller({
|
||||
@ -25,7 +27,7 @@ export class UserDevicePermissionController {
|
||||
) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(AdminRoleGuard)
|
||||
@Post('add')
|
||||
async addDevicePermission(
|
||||
@Body() userDevicePermissionDto: UserDevicePermissionAddDto,
|
||||
@ -40,40 +42,45 @@ export class UserDevicePermissionController {
|
||||
message: 'User Permission for Devices Added Successfully',
|
||||
data: addDetails,
|
||||
};
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('edit/:userId')
|
||||
@UseGuards(AdminRoleGuard)
|
||||
@Put('edit/:devicePermissionUuid')
|
||||
async editDevicePermission(
|
||||
@Param('userId') userId: string,
|
||||
@Param('devicePermissionUuid') devicePermissionUuid: string,
|
||||
@Body() userDevicePermissionEditDto: UserDevicePermissionEditDto,
|
||||
) {
|
||||
try {
|
||||
await this.userDevicePermissionService.editUserPermission(
|
||||
userId,
|
||||
devicePermissionUuid,
|
||||
userDevicePermissionEditDto,
|
||||
);
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
message: 'User Permission for Devices Updated Successfully',
|
||||
data: {},
|
||||
};
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('list')
|
||||
async fetchDevicePermission() {
|
||||
@UseGuards(AdminRoleGuard)
|
||||
@Get(':deviceUuid/list')
|
||||
async fetchDevicePermission(@Param('deviceUuid') deviceUuid: string) {
|
||||
try {
|
||||
const deviceDetails =
|
||||
await this.userDevicePermissionService.fetchuserPermission();
|
||||
await this.userDevicePermissionService.fetchUserPermission(deviceUuid);
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
message: 'Device Details fetched Successfully',
|
||||
@ -83,4 +90,25 @@ export class UserDevicePermissionController {
|
||||
throw new Error(err);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminRoleGuard)
|
||||
@Delete(':devicePermissionUuid')
|
||||
async deleteDevicePermission(
|
||||
@Param('devicePermissionUuid') devicePermissionUuid: string,
|
||||
) {
|
||||
try {
|
||||
await this.userDevicePermissionService.deleteDevicePermission(
|
||||
devicePermissionUuid,
|
||||
);
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
message: 'User Permission for Devices Deleted Successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,2 @@
|
||||
export * from './user-device-permission.add.dto';
|
||||
export * from './user-device-permission.edit.dto';
|
||||
|
@ -1,28 +1,29 @@
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
import { IsEnum, IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class UserDevicePermissionAddDto {
|
||||
@ApiProperty({
|
||||
description: 'user id',
|
||||
description: 'user uuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
userId: string;
|
||||
userUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'permission type id',
|
||||
description: 'permission type',
|
||||
enum: PermissionType,
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
permissionTypeId: string;
|
||||
@IsEnum(PermissionType)
|
||||
permissionType: PermissionType;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'device id',
|
||||
description: 'device uuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
deviceId: string;
|
||||
deviceUuid: string;
|
||||
}
|
||||
|
@ -1,7 +1,13 @@
|
||||
import { OmitType } from '@nestjs/swagger';
|
||||
import { UserDevicePermissionAddDto } from './user-device-permission.add.dto';
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsEnum } from 'class-validator';
|
||||
|
||||
export class UserDevicePermissionEditDto extends OmitType(
|
||||
UserDevicePermissionAddDto,
|
||||
['userId'],
|
||||
) {}
|
||||
export class UserDevicePermissionEditDto {
|
||||
@ApiProperty({
|
||||
description: 'permission type',
|
||||
enum: PermissionType,
|
||||
required: true,
|
||||
})
|
||||
@IsEnum(PermissionType)
|
||||
permissionType: PermissionType;
|
||||
}
|
||||
|
@ -0,0 +1 @@
|
||||
export * from './user-device-permission.service';
|
||||
|
@ -1,36 +1,107 @@
|
||||
import { DeviceUserTypeRepository } from '@app/common/modules/device/repositories';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { UserDevicePermissionAddDto } from '../dtos/user-device-permission.add.dto';
|
||||
import { UserDevicePermissionEditDto } from '../dtos/user-device-permission.edit.dto';
|
||||
import { DeviceUserPermissionRepository } from '@app/common/modules/device-user-permission/repositories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class UserDevicePermissionService {
|
||||
constructor(
|
||||
private readonly deviceUserTypeRepository: DeviceUserTypeRepository,
|
||||
private readonly deviceUserPermissionRepository: DeviceUserPermissionRepository,
|
||||
private readonly permissionTypeRepository: PermissionTypeRepository,
|
||||
) {}
|
||||
|
||||
async addUserPermission(userDevicePermissionDto: UserDevicePermissionAddDto) {
|
||||
return await this.deviceUserTypeRepository.save({
|
||||
userUuid: userDevicePermissionDto.userId,
|
||||
deviceUuid: userDevicePermissionDto.deviceId,
|
||||
permissionTypeUuid: userDevicePermissionDto.permissionTypeId,
|
||||
});
|
||||
try {
|
||||
const permissionType = await this.getPermissionType(
|
||||
userDevicePermissionDto.permissionType,
|
||||
);
|
||||
return await this.deviceUserPermissionRepository.save({
|
||||
userUuid: userDevicePermissionDto.userUuid,
|
||||
deviceUuid: userDevicePermissionDto.deviceUuid,
|
||||
permissionType: {
|
||||
uuid: permissionType.uuid,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.code === '23505') {
|
||||
throw new HttpException(
|
||||
'This User already belongs to this device',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
error.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async editUserPermission(
|
||||
userId: string,
|
||||
devicePermissionUuid: string,
|
||||
userDevicePermissionEditDto: UserDevicePermissionEditDto,
|
||||
) {
|
||||
return await this.deviceUserTypeRepository.update(
|
||||
{ userUuid: userId },
|
||||
{
|
||||
deviceUuid: userDevicePermissionEditDto.deviceId,
|
||||
permissionTypeUuid: userDevicePermissionEditDto.permissionTypeId,
|
||||
},
|
||||
);
|
||||
try {
|
||||
const permissionType = await this.getPermissionType(
|
||||
userDevicePermissionEditDto.permissionType,
|
||||
);
|
||||
return await this.deviceUserPermissionRepository.update(
|
||||
{ uuid: devicePermissionUuid },
|
||||
{
|
||||
permissionType: {
|
||||
uuid: permissionType.uuid,
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
if (error.code === '23505') {
|
||||
throw new HttpException(
|
||||
'This User already belongs to this device',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
error.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async fetchuserPermission() {
|
||||
return await this.deviceUserTypeRepository.find();
|
||||
async fetchUserPermission(deviceUuid: string) {
|
||||
const devicePermissions = await this.deviceUserPermissionRepository.find({
|
||||
where: {
|
||||
deviceUuid: deviceUuid,
|
||||
},
|
||||
relations: ['permissionType', 'user'],
|
||||
});
|
||||
return devicePermissions.map((permission) => {
|
||||
return {
|
||||
uuid: permission.uuid,
|
||||
deviceUuid: permission.deviceUuid,
|
||||
firstName: permission.user.firstName,
|
||||
lastName: permission.user.lastName,
|
||||
email: permission.user.email,
|
||||
permissionType: permission.permissionType.type,
|
||||
};
|
||||
});
|
||||
}
|
||||
private async getPermissionType(permissionType: string) {
|
||||
return await this.permissionTypeRepository.findOne({
|
||||
where: {
|
||||
type: permissionType,
|
||||
},
|
||||
});
|
||||
}
|
||||
async deleteDevicePermission(devicePermissionUuid: string) {
|
||||
try {
|
||||
return await this.deviceUserPermissionRepository.delete({
|
||||
uuid: devicePermissionUuid,
|
||||
});
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,18 +1,18 @@
|
||||
import { DeviceRepositoryModule } from '@app/common/modules/device';
|
||||
import {
|
||||
DeviceRepository,
|
||||
DeviceUserTypeRepository,
|
||||
} from '@app/common/modules/device/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { UserDevicePermissionService } from './services/user-device-permission.service';
|
||||
import { UserDevicePermissionController } from './controllers/user-device-permission.controller';
|
||||
import { DeviceUserPermissionRepository } from '@app/common/modules/device-user-permission/repositories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, DeviceRepositoryModule],
|
||||
controllers: [UserDevicePermissionController],
|
||||
providers: [
|
||||
DeviceUserTypeRepository,
|
||||
DeviceUserPermissionRepository,
|
||||
PermissionTypeRepository,
|
||||
DeviceRepository,
|
||||
UserDevicePermissionService,
|
||||
],
|
||||
|
@ -2,7 +2,7 @@ import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||
import { UserService } from '../services/user.service';
|
||||
import { UserListDto } from '../dtos/user.list.dto';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AdminRoleGuard } from 'src/guards/admin.role.guard';
|
||||
|
||||
@ApiTags('User Module')
|
||||
@Controller({
|
||||
@ -13,7 +13,7 @@ export class UserController {
|
||||
constructor(private readonly userService: UserService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(AdminRoleGuard)
|
||||
@Get('list')
|
||||
async userList(@Query() userListDto: UserListDto) {
|
||||
try {
|
||||
|
Reference in New Issue
Block a user