@thealiqaf/nestjs-permission-management
Version:
A NestJS module for permission management
116 lines • 6.25 kB
JavaScript
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UserPermissionService = void 0;
const common_1 = require("@nestjs/common");
const mongoose_1 = require("@nestjs/mongoose");
const mongoose_2 = require("mongoose");
const user_permission_schema_1 = require("../schemas/user-permission.schema");
const logger_service_1 = require("../common/services/logger.service");
const permission_schema_1 = require("../schemas/permission.schema");
let UserPermissionService = class UserPermissionService {
userPermissionModel;
permissionModel;
logger;
constructor(userPermissionModel, permissionModel, logger) {
this.userPermissionModel = userPermissionModel;
this.permissionModel = permissionModel;
this.logger = logger;
}
async validatePermissionIds(ids) {
if (!ids || ids.length === 0)
return;
const foundPermissions = await this.permissionModel
.find({ _id: { $in: ids } })
.select('_id');
const foundIds = foundPermissions.map((p) => p._id.toString());
const notFound = ids.filter((id) => !foundIds.includes(id));
if (notFound.length > 0) {
throw new common_1.BadRequestException(`Permission IDs not found: ${notFound.join(', ')}`);
}
}
async createUserPermission(createUserPermissionDto) {
if (!(0, mongoose_2.isValidObjectId)(createUserPermissionDto.userId)) {
throw new common_1.BadRequestException('Invalid userId format');
}
const userExists = await this.userPermissionModel.exists({ _id: createUserPermissionDto.userId });
if (!userExists) {
throw new common_1.BadRequestException('User ID does not exist');
}
await this.validatePermissionIds(createUserPermissionDto.permissions);
const existingUserPermission = await this.userPermissionModel.findOne({
userId: createUserPermissionDto.userId,
});
if (existingUserPermission) {
throw new common_1.BadRequestException('User Permission already exists for this user');
}
const createdUserPermission = new this.userPermissionModel(createUserPermissionDto);
this.logger.log(`Creating user permission, data: ${JSON.stringify(createUserPermissionDto)}`);
return await createdUserPermission.save();
}
async findAllUserPermissions() {
return this.userPermissionModel.find().populate('permissions').lean();
}
async findUserPermissionById(id) {
const userPermission = await this.userPermissionModel.findById(id).populate('permissions');
if (!userPermission) {
throw new common_1.NotFoundException('User Permission not found');
}
return userPermission;
}
async updateUserPermission(id, updateUserPermissionDto) {
const updates = Object.fromEntries(Object.entries(updateUserPermissionDto).filter(([_, v]) => v !== undefined));
if (updates.permissions) {
const permissions = await this.permissionModel.find({ _id: { $in: updates.permissions } });
if (permissions.length !== updates.permissions.length) {
throw new common_1.BadRequestException('Some permissions are invalid');
}
}
const existingUserPermission = await this.userPermissionModel.findById(id);
if (!existingUserPermission) {
throw new common_1.NotFoundException('User Permission not found');
}
if (updates.permissions) {
const existingPermissionIds = existingUserPermission.permissions.map(p => p.toString());
const duplicatedPermissions = updates.permissions.filter((permId) => existingPermissionIds.includes(permId));
if (duplicatedPermissions.length > 0) {
throw new common_1.BadRequestException(`The following permissions are already assigned to this user: ${duplicatedPermissions.join(', ')}`);
}
}
const updatedUserPermission = await this.userPermissionModel.findByIdAndUpdate(id, { $set: updates }, { new: true, runValidators: true }).populate('permissions');
if (!updatedUserPermission) {
throw new common_1.NotFoundException('User Permission not found after update');
}
this.logger.log(`Updated user permission with ID ${id}: ${JSON.stringify(updates)}`);
return updatedUserPermission;
}
async deleteUserPermission(id) {
const deletedUserPermission = await this.userPermissionModel.findByIdAndDelete(id);
if (!deletedUserPermission) {
throw new common_1.NotFoundException('User Permission not found');
}
this.logger.log(`Deleting user permission with ID ${id}`);
return deletedUserPermission;
}
};
exports.UserPermissionService = UserPermissionService;
exports.UserPermissionService = UserPermissionService = __decorate([
(0, common_1.Injectable)(),
__param(0, (0, mongoose_1.InjectModel)(user_permission_schema_1.UserPermission.name)),
__param(1, (0, mongoose_1.InjectModel)(permission_schema_1.Permission.name)),
__metadata("design:paramtypes", [mongoose_2.Model,
mongoose_2.Model,
logger_service_1.LoggerService])
], UserPermissionService);
//# sourceMappingURL=user-permission.service.js.map