UNPKG

mongodb-dynamic-api

Version:

Auto generated CRUD API for MongoDB using NestJS

82 lines 3.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseSocketPoliciesGuard = exports.BasePoliciesGuard = void 0; const common_1 = require("@nestjs/common"); const websockets_1 = require("@nestjs/websockets"); const logger_1 = require("../logger"); const services_1 = require("../services"); class BasePoliciesGuard extends services_1.BaseService { constructor(model) { super(model); this.model = model; } async canActivate(context) { const { user, query, params } = context.switchToHttp().getRequest(); if (this.abilityPredicate) { if (!user) { throw new common_1.ForbiddenException('Access Denied'); } this.user = user; if (params?.id) { await this.findOneDocumentWithAbilityPredicate(params.id, query); } else if (this.routeType === 'Aggregate' && query && this.queryToPipeline) { await this.aggregateDocumentsWithAbilityPredicate(this.queryToPipeline(query)); } else { await this.findManyDocumentsWithAbilityPredicate(query); } } return true; } } exports.BasePoliciesGuard = BasePoliciesGuard; class BaseSocketPoliciesGuard extends services_1.BaseService { constructor(model) { super(model); this.model = model; } async canActivate(context) { this.logger = new logger_1.MongoDBDynamicApiLogger(`SocketPoliciesGuard-${this.routeType}-${this.entity?.name}`); const [socket, data, _, _event] = context.getArgs(); this.logger.debug('canActivate', { socketId: socket.id, socketUser: socket.user, data, event: _event, isPublic: this.isPublic, abilityPredicate: !!this.abilityPredicate, }); if (!this.isPublic) { if (!socket.user) { this.logger.warn('No user data in socket'); throw new websockets_1.WsException('Access Denied'); } if (this.abilityPredicate) { try { this.user = socket.user; const { id } = data || {}; if (id) { this.logger.debug(`Finding one document with id: ${id} and ability predicate`); await this.findOneDocumentWithAbilityPredicate(id); } else if (this.routeType === 'Aggregate' && data && this.queryToPipeline) { this.logger.debug('Aggregating documents with ability predicate'); await this.aggregateDocumentsWithAbilityPredicate(this.queryToPipeline(data)); } else { this.logger.debug('Finding many documents with ability predicate'); await this.findManyDocumentsWithAbilityPredicate(data); } } catch (error) { this.logger.error('Error in canActivate', error); throw new websockets_1.WsException(error.message); } } } return true; } } exports.BaseSocketPoliciesGuard = BaseSocketPoliciesGuard; //# sourceMappingURL=base-policies.guard.js.map