How to use notPermitted method in Mocha

Best JavaScript code snippet using mocha

services.tests.js

Source:services.tests.js Github

copy

Full Screen

1/* eslint-env mocha */2/* eslint-disable func-names, prefer-arrow-callback */3import { PublicationCollector } from 'meteor/johanbrook:publication-collector';4import { assert } from 'chai';5import { Meteor } from 'meteor/meteor';6import { Random } from 'meteor/random';7import { _ } from 'meteor/underscore';8import '../../../../i18n/en.i18n.json';9import faker from 'faker';10import { Factory } from 'meteor/dburles:factory';11import { Accounts } from 'meteor/accounts-base';12import { Roles } from 'meteor/alanning:roles';13import { createService, removeService, updateService, favService, unfavService } from '../methods';14import './publications';15import './factories';16import Services from '../services';17import Categories from '../../categories/categories';18import '../../categories/server/factories';19import PersonalSpaces from '../../personalspaces/personalspaces';20function pspaceHasService(user, id) {21 const pspace = PersonalSpaces.findOne({22 userId: user,23 unsorted: { $elemMatch: { type: 'service', element_id: id } },24 });25 const inFavs = Meteor.users.findOne(user).favServices.includes(id);26 return pspace !== undefined && inFavs;27}28describe('services', function () {29 describe('mutators', function () {30 it('builds correctly from factory', function () {31 const service = Factory.create('service');32 assert.typeOf(service, 'object');33 });34 });35 describe('publications', function () {36 let userId;37 let oneServiceId;38 let structureServiceId;39 let categoryId;40 let groupServiceId;41 let userStruct;42 beforeEach(function () {43 Meteor.roleAssignment.remove({});44 Meteor.users.remove({});45 Meteor.roles.remove({});46 Categories.remove({});47 Roles.createRole('admin');48 Roles.createRole('adminStructure');49 const email = faker.internet.email();50 userStruct = faker.company.companyName();51 userId = Accounts.createUser({52 email,53 username: email,54 password: 'toto',55 structure: userStruct,56 firstName: faker.name.firstName(),57 lastName: faker.name.lastName(),58 });59 Meteor.users.update(userId, { $set: { isActive: true } });60 Services.remove({});61 _.times(3, () => {62 Factory.create('service', { title: `test${Random.id()}` });63 });64 structureServiceId = Factory.create('service', { title: 'structureService', structure: userStruct })._id;65 Factory.create('service', { title: 'otherStructureService', structure: 'otherStructure' });66 categoryId = Factory.create('categorie')._id;67 oneServiceId = Factory.create('service', { title: 'test', categories: [categoryId] })._id;68 groupServiceId = Factory.create('service')._id;69 });70 describe('services.all', function () {71 it('sends all services (except structure specific ones)', function (done) {72 const collector = new PublicationCollector({ userId });73 collector.collect('services.all', (collections) => {74 assert.equal(collections.services.length, 5);75 // check that structure specific service is not present76 assert.equal(collections.services.filter((serv) => serv._id === structureServiceId).length, 0);77 done();78 });79 });80 });81 describe('services.structure', function () {82 it('sends all user structure specific services', function (done) {83 const collector = new PublicationCollector({ userId });84 collector.collect('services.structure', (collections) => {85 assert.equal(collections.services.length, 1);86 assert.equal(collections.services[0]._id, structureServiceId);87 done();88 });89 });90 });91 describe('services.one.admin', function () {92 it('sends one service to admin or adminStructure user only', function (done) {93 const collector = new PublicationCollector({ userId });94 collector.collect('services.one.admin', { _id: oneServiceId }, (collections) => {95 // non admin user : no result96 assert.notProperty(collections, 'services');97 });98 Roles.addUsersToRoles(userId, 'adminStructure', userStruct);99 const structureCollector = new PublicationCollector({ userId });100 structureCollector.collect('services.one.admin', { _id: structureServiceId }, (collections) => {101 assert.equal(collections.services.length, 1);102 assert.equal(collections.services[0]._id, structureServiceId);103 assert.property(collections.services[0], 'content');104 });105 Roles.removeUsersFromRoles(userId, 'adminStructure', userStruct);106 Roles.addUsersToRoles(userId, 'admin');107 const adminCollector = new PublicationCollector({ userId });108 adminCollector.collect('services.one.admin', { _id: oneServiceId }, (collections) => {109 assert.equal(collections.services.length, 1);110 assert.equal(collections.services[0]._id, oneServiceId);111 assert.property(collections.services[0], 'content');112 });113 done();114 });115 });116 describe('services.group', function () {117 it('sends services from a list of services ids', function (done) {118 const collector = new PublicationCollector({ userId });119 collector.collect('services.group', { ids: [oneServiceId, groupServiceId] }, (collections) => {120 assert.equal(collections.services.length, 2);121 assert.equal(122 collections.services.filter((serv) => [oneServiceId, groupServiceId].includes(serv._id)).length,123 2,124 );125 done();126 });127 });128 });129 describe('services.one', function () {130 it('sends one service and corresponding categories selected by service slug', function (done) {131 const collector = new PublicationCollector({ userId });132 collector.collect('services.one', { slug: 'test' }, (collections) => {133 assert.equal(collections.services.length, 1);134 assert.equal(collections.categories.length, 1);135 assert.equal(collections.services[0]._id, oneServiceId);136 assert.equal(collections.categories[0]._id, categoryId);137 done();138 });139 });140 });141 });142 describe('methods', function () {143 let userId;144 let adminId;145 let adminStructureId;146 let serviceId;147 let structureServiceId;148 let otherStructureServiceId;149 let chatData;150 beforeEach(function () {151 // Clear152 Services.remove({});153 PersonalSpaces.remove({});154 Meteor.roleAssignment.remove({});155 Meteor.users.remove({});156 Meteor.roles.remove({});157 Roles.createRole('admin');158 Roles.createRole('adminStructure');159 // Generate 'users'160 const email = faker.internet.email();161 userId = Accounts.createUser({162 email,163 username: email,164 password: 'toto',165 structure: 'maStructure',166 firstName: faker.name.firstName(),167 lastName: faker.name.lastName(),168 });169 const emailAdminStructure = `struct${faker.internet.email()}`;170 adminStructureId = Accounts.createUser({171 email: emailAdminStructure,172 username: emailAdminStructure,173 password: 'toto',174 structure: 'maStructure',175 firstName: faker.name.firstName(),176 lastName: faker.name.lastName(),177 });178 const emailAdmin = `admin${faker.internet.email()}`;179 adminId = Accounts.createUser({180 email: emailAdmin,181 username: emailAdmin,182 password: 'toto',183 structure: 'maStructure',184 firstName: faker.name.firstName(),185 lastName: faker.name.lastName(),186 });187 // set this user as global admin188 Roles.addUsersToRoles(adminId, 'admin');189 Roles.addUsersToRoles(adminStructureId, 'adminStructure', 'maStructure');190 // set users as active191 Meteor.users.update({}, { $set: { isActive: true } }, { multi: true });192 serviceId = Factory.create('service')._id;193 structureServiceId = Factory.create('service', { structure: 'maStructure' })._id;194 otherStructureServiceId = Factory.create('service', { structure: 'autreStructure' })._id;195 // add service to userId favorites196 Meteor.users.update({ _id: userId }, { $set: { favServices: [serviceId, structureServiceId] } });197 chatData = {198 title: 'Chat sur un nuage de liconre',199 description: "Chevaucher un dragon rose à pois. C'est en fait une fée pour piéger Peter Pan",200 url: 'https://chat.licorne.ovh',201 logo: 'https://rocket.chat/images/default/logo--dark.svg',202 categories: [],203 team: 'Dijon',204 usage: 'Discuter en Troubadour',205 screenshots: [],206 content: "<div>c'est un service de fou</div>",207 state: 0,208 structure: '',209 };210 });211 describe('createService', function () {212 it('does create a service with admin user', function () {213 createService._execute({ userId: adminId }, chatData);214 const service = Services.findOne({ title: chatData.title });215 assert.typeOf(service, 'object');216 });217 it("does not create a service if you're not admin", function () {218 // Throws if non admin user, or logged out user, tries to create a service219 assert.throws(220 () => {221 createService._execute({ userId }, chatData);222 },223 Meteor.Error,224 /api.services.createService.notPermitted/,225 );226 assert.throws(227 () => {228 createService._execute({}, chatData);229 },230 Meteor.Error,231 /api.services.createService.notPermitted/,232 );233 });234 it('does create a structure specific service with adminStructure user', function () {235 createService._execute({ userId: adminStructureId }, { ...chatData, structure: 'maStructure' });236 const service = Services.findOne({ title: chatData.title });237 assert.typeOf(service, 'object');238 });239 it('does create a structure specific service with adminStructure user', function () {240 createService._execute({ userId: adminId }, { ...chatData, structure: 'uneStructure' });241 const service = Services.findOne({ title: chatData.title });242 assert.typeOf(service, 'object');243 });244 it("does not create a structure specific service if you're not adminStructure or admin", function () {245 // Throws if non admin user, or logged out user, tries to create a service246 assert.throws(247 () => {248 createService._execute({ userId }, { ...chatData, structure: 'maStructure' });249 },250 Meteor.Error,251 /api.services.createService.notPermitted/,252 );253 assert.throws(254 () => {255 createService._execute({}, { ...chatData, structure: 'maStructure' });256 },257 Meteor.Error,258 /api.services.createService.notPermitted/,259 );260 });261 it('does not create a structure specific service for another structure', function () {262 // Throws if non admin user, or logged out user, tries to create a service263 assert.throws(264 () => {265 createService._execute({ userId: adminStructureId }, { ...chatData, structure: 'autreStructure' });266 },267 Meteor.Error,268 /api.services.createService.notPermitted/,269 );270 });271 });272 describe('removeService', function () {273 it('does delete a service with admin user', function () {274 removeService._execute({ userId: adminId }, { serviceId });275 assert.equal(Services.findOne(serviceId), undefined);276 // check that service has been removed from userId favorites277 assert.equal(Meteor.users.findOne({ favServices: { $all: [serviceId] } }), undefined);278 });279 it('does delete a structure specific service with adminStructure user', function () {280 removeService._execute({ userId: adminStructureId }, { serviceId: structureServiceId });281 assert.equal(Services.findOne(structureServiceId), undefined);282 // check that service has been removed from userId favorites283 assert.equal(Meteor.users.findOne({ favServices: { $all: [structureServiceId] } }), undefined);284 });285 it("does not delete a service if you're not admin", function () {286 // Throws if non admin user, or logged out user, tries to delete the service287 assert.throws(288 () => {289 removeService._execute({ userId }, { serviceId });290 },291 Meteor.Error,292 /api.services.removeService.notPermitted/,293 );294 assert.throws(295 () => {296 removeService._execute({ userId }, { serviceId: structureServiceId });297 },298 Meteor.Error,299 /api.services.removeService.notPermitted/,300 );301 assert.throws(302 () => {303 removeService._execute({}, { serviceId });304 },305 Meteor.Error,306 /api.services.removeService.notPermitted/,307 );308 assert.throws(309 () => {310 removeService._execute({}, { serviceId: structureServiceId });311 },312 Meteor.Error,313 /api.services.removeService.notPermitted/,314 );315 });316 it("does not delete service for another structure if you're adminStructure", function () {317 assert.throws(318 () => {319 removeService._execute({ userId: adminStructureId }, { serviceId: otherStructureServiceId });320 },321 Meteor.Error,322 /api.services.removeService.notPermitted/,323 );324 });325 });326 describe('updateService', function () {327 const data = {328 title: 'Chat sur MIMOSA',329 description: "Chevaucher un dragon rose à pois. C'est en fait une fée pour piéger Peter Pan",330 usage: 'Discuter en Troubadour',331 url: 'https://chat.licorne.ovh',332 logo: 'https://rocket.chat/images/default/logo--dark.svg',333 categories: [],334 team: 'Dijon',335 screenshots: ['https://rocket.chat/images/default/logo--dark.svg'],336 content: "<div>c'est un service de fou</div>",337 state: 0,338 };339 it('does update a service with admin user', function () {340 updateService._execute({ userId: adminId }, { serviceId, data: { ...data } });341 const service = Services.findOne(serviceId);342 assert.equal(service.title, data.title);343 assert.equal(service.description, data.description);344 assert.equal(service.url, data.url);345 assert.equal(service.logo, data.logo);346 assert.equal(service.team, data.team);347 assert.equal(service.usage, data.usage);348 assert.deepEqual(service.screenshots, data.screenshots);349 assert.equal(service.content, data.content);350 });351 it('does update a structure specific service with adminStructure user', function () {352 updateService._execute({ userId: adminStructureId }, { serviceId: structureServiceId, data: { ...data } });353 const service = Services.findOne(structureServiceId);354 assert.equal(service.title, data.title);355 assert.equal(service.description, data.description);356 assert.equal(service.url, data.url);357 assert.equal(service.logo, data.logo);358 assert.equal(service.team, data.team);359 assert.equal(service.usage, data.usage);360 assert.deepEqual(service.screenshots, data.screenshots);361 assert.equal(service.content, data.content);362 });363 it("does not update a service if you're not admin or structureAdmin", function () {364 // Throws if non admin user, or logged out user, tries to delete the service365 assert.throws(366 () => {367 updateService._execute({ userId }, { serviceId, data });368 },369 Meteor.Error,370 /api.services.updateService.notPermitted/,371 );372 assert.throws(373 () => {374 updateService._execute({ userId }, { serviceId: structureServiceId, data });375 },376 Meteor.Error,377 /api.services.updateService.notPermitted/,378 );379 assert.throws(380 () => {381 updateService._execute({}, { serviceId, data });382 },383 Meteor.Error,384 /api.services.updateService.notPermitted/,385 );386 });387 it("does not update a global ot other structure service if you're structureAdmin", function () {388 // Throws if non admin user, or logged out user, tries to delete the service389 assert.throws(390 () => {391 updateService._execute({ userId: adminStructureId }, { serviceId, data });392 },393 Meteor.Error,394 /api.services.updateService.notPermitted/,395 );396 assert.throws(397 () => {398 updateService._execute({ userId: adminStructureId }, { serviceId: otherStructureServiceId, data });399 },400 Meteor.Error,401 /api.services.updateService.notPermitted/,402 );403 });404 });405 describe('(un)favService', function () {406 it('does (un)set a service as favorite', function () {407 favService._execute({ userId }, { serviceId });408 let user = Meteor.users.findOne(userId);409 assert.include(user.favServices, serviceId, 'favorite service list contains serviceId');410 assert.equal(pspaceHasService(userId, serviceId), true, 'service is in personal space');411 unfavService._execute({ userId }, { serviceId });412 user = Meteor.users.findOne(userId);413 assert.notInclude(user.favServices, serviceId, 'favorite service list does not contains serviceId');414 assert.equal(pspaceHasService(userId, serviceId), false, 'service is no longer in personal space');415 });416 it('does not set a service as favorite if not logged in', function () {417 assert.throws(418 () => {419 favService._execute({}, { serviceId });420 },421 Meteor.Error,422 /api.services.favService.notPermitted/,423 );424 });425 it('does not unset a service as favorite if not logged in', function () {426 assert.throws(427 () => {428 unfavService._execute({}, { serviceId });429 },430 Meteor.Error,431 /api.services.unfavService.notPermitted/,432 );433 });434 });435 });...

Full Screen

Full Screen

methods.js

Source:methods.js Github

copy

Full Screen

1import { Meteor } from 'meteor/meteor';2import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';3import { _ } from 'meteor/underscore';4import SimpleSchema from 'simpl-schema';5import { ValidatedMethod } from 'meteor/mdg:validated-method';6import i18n from 'meteor/universe:i18n';7import { isActive } from '../utils';8import PersonalSpaces from './personalspaces';9import Groups from '../groups/groups';10import Services from '../services/services';11import logServer from '../logging';12import UserBookmarks from '../userBookmarks/userBookmarks';13const addItem = (userId, item) => {14 const currentPersonalSpace = PersonalSpaces.findOne({ userId });15 let alreadyExists = false;16 if (currentPersonalSpace === undefined) {17 // create personalSpace if not existing18 PersonalSpaces.insert({ userId, unsorted: [], sorted: [] });19 } else {20 // check that item is not already present21 alreadyExists =22 PersonalSpaces.findOne({23 $and: [24 { userId },25 {26 $or: [27 {28 unsorted: { $elemMatch: { type: item.type, element_id: item.element_id } },29 },30 { 'sorted.elements': { $elemMatch: { type: item.type, element_id: item.element_id } } },31 ],32 },33 ],34 }) !== undefined;35 }36 if (!alreadyExists) PersonalSpaces.update({ userId }, { $push: { unsorted: item } });37};38export const removeElement = new ValidatedMethod({39 name: 'personalspaces.removeElement',40 validate: new SimpleSchema({41 elementId: { type: String, regEx: SimpleSchema.RegEx.Id },42 type: String,43 }).validator(),44 run({ elementId, type }) {45 // check if active and logged in46 if (!isActive(this.userId)) {47 throw new Meteor.Error('api.personalspaces.addService.notPermitted', i18n.__('api.users.notPermitted'));48 }49 // remove all entries matching item type and element_id50 PersonalSpaces.update(51 { userId: this.userId },52 {53 $pull: {54 unsorted: { type, element_id: elementId },55 'sorted.$[].elements': { type, element_id: elementId },56 },57 },58 );59 },60});61export const addService = new ValidatedMethod({62 name: 'personalspaces.addService',63 validate: new SimpleSchema({64 serviceId: { type: String, regEx: SimpleSchema.RegEx.Id },65 }).validator(),66 run({ serviceId }) {67 // check if active and logged in68 if (!isActive(this.userId)) {69 throw new Meteor.Error('api.personalspaces.addService.notPermitted', i18n.__('api.users.notPermitted'));70 }71 const service = Services.findOne(serviceId);72 if (service === undefined) {73 throw new Meteor.Error('api.personalspaces.addService.unknownService', i18n.__('api.services.unknownService'));74 }75 addItem(this.userId, { type: 'service', element_id: serviceId });76 },77});78export const addGroup = new ValidatedMethod({79 name: 'personalspaces.addGroup',80 validate: new SimpleSchema({81 groupId: { type: String, regEx: SimpleSchema.RegEx.Id },82 }).validator(),83 run({ groupId }) {84 // check if active and logged in85 if (!isActive(this.userId)) {86 throw new Meteor.Error('api.personalspaces.addGroup.notPermitted', i18n.__('api.users.notPermitted'));87 }88 const group = Groups.findOne(groupId);89 if (group === undefined) {90 throw new Meteor.Error('api.personalspaces.addGroup.unknownGroup', i18n.__('api.groups.unknownGroup'));91 }92 addItem(this.userId, { type: 'group', element_id: groupId });93 },94});95export const addUserBookmark = new ValidatedMethod({96 name: 'personalspaces.addBookmark',97 validate: new SimpleSchema({98 bookmarkId: { type: String, regEx: SimpleSchema.RegEx.Id },99 }).validator(),100 run({ bookmarkId }) {101 // check if active and logged in102 if (!isActive(this.userId)) {103 throw new Meteor.Error('api.personalspaces.addBookmark.notPermitted', i18n.__('api.users.notPermitted'));104 }105 const bookmark = UserBookmarks.findOne(bookmarkId);106 if (bookmark === undefined) {107 throw new Meteor.Error(108 'api.personalspaces.addBookmark.unknownBookmark',109 i18n.__('api.bookmarks.unknownBookmark'),110 );111 }112 addItem(this.userId, { type: 'link', element_id: bookmarkId });113 },114});115export const updatePersonalSpace = new ValidatedMethod({116 name: 'personalspaces.updatePersonalSpace',117 validate: new SimpleSchema({118 data: PersonalSpaces.schema.omit('userId'),119 }).validator({ clean: true }),120 run({ data }) {121 // check if active and logged in122 if (!isActive(this.userId)) {123 throw new Meteor.Error('api.personalspaces.updatePersonalSpace.notPermitted', i18n.__('api.users.notPermitted'));124 }125 const currentPersonalSpace = PersonalSpaces.findOne({ userId: this.userId });126 if (currentPersonalSpace === undefined) {127 // create personalSpace if not existing128 PersonalSpaces.insert({ ...data, userId: this.userId });129 } else {130 PersonalSpaces.update({ _id: currentPersonalSpace._id }, { $set: data });131 }132 },133});134export const checkPersonalSpace = new ValidatedMethod({135 name: 'personalspaces.checkPersonalSpace',136 validate: null,137 run() {138 // check integrity of personal space datas (no duplicate card and check if groups still exists)139 if (!isActive(this.userId)) {140 throw new Meteor.Error('api.personalspaces.updatePersonalSpace.notPermitted', i18n.__('api.users.notPermitted'));141 }142 const currentPersonalSpace = PersonalSpaces.findOne({ userId: this.userId });143 const u = Meteor.users.findOne(144 { _id: this.userId },145 { fields: { username: 1, favServices: 1, favGroups: 1, favUserBookmarks: 1 } },146 );147 if (currentPersonalSpace === undefined) {148 logServer(`Regen Personalspace (not found) for ${u.username}...`);149 const unsorted = [];150 u.favServices.forEach((s) => {151 unsorted.push({152 element_id: s,153 type: 'service',154 });155 });156 u.favGroups.forEach((g) => {157 unsorted.push({158 element_id: g,159 type: 'group',160 });161 });162 u.favUserBookmarks.forEach((b) => {163 unsorted.push({164 element_id: b,165 type: 'link',166 });167 });168 updatePersonalSpace._execute({ userId: this.userId }, { data: { userId: this.userId, unsorted, sorted: [] } });169 return; // No need to go further170 }171 let changeMade = false;172 const elementIds = { service: [], group: [], link: [] };173 const checkZone = (zone) => {174 // Loop zone elements backward so we can delete items by index175 for (let index = zone.length - 1; index >= 0; index -= 1) {176 const elem = zone[index];177 if (elementIds[elem.type].indexOf(elem.element_id) !== -1) {178 // We have a duplicate card to delete179 zone.splice(index, 1);180 changeMade = true;181 // eslint-disable-next-line182 continue; // continue to next element183 }184 if (elem.type === 'group') {185 // Check if group still exists186 const group = Groups.findOne(elem.element_id);187 if (group === undefined) {188 // group no more exists so delete element189 zone.splice(index, 1);190 changeMade = true;191 // eslint-disable-next-line192 continue; // continue to next element193 }194 } else if (elem.type === 'link') {195 // Check if link still exists196 const link = UserBookmarks.findOne(elem.element_id);197 if (link === undefined) {198 // link no more exists so delete element199 zone.splice(index, 1);200 changeMade = true;201 // eslint-disable-next-line202 continue; // continue to next element203 }204 } else if (elem.type === 'service') {205 // Check if service still exists206 const service = Services.findOne(elem.element_id);207 if (service === undefined) {208 // service no more exists so delete element209 zone.splice(index, 1);210 changeMade = true;211 // eslint-disable-next-line212 continue; // continue to next element213 }214 }215 elementIds[elem.type].push(elem.element_id);216 }217 };218 currentPersonalSpace.sorted.forEach((zone) => {219 checkZone(zone.elements);220 });221 checkZone(currentPersonalSpace.unsorted);222 // Save modified PS if necessary223 if (changeMade) {224 updatePersonalSpace._execute({ userId: this.userId }, { data: currentPersonalSpace }, (err) => {225 if (err) {226 logServer(err.reason, 'error');227 }228 });229 }230 },231});232export const backToDefaultElement = new ValidatedMethod({233 name: 'personalspaces.backToDefaultElement',234 validate: new SimpleSchema({235 elementId: { type: String, regEx: SimpleSchema.RegEx.Id },236 type: String,237 }).validator(),238 run({ elementId, type }) {239 // check if active and logged in240 if (!isActive(this.userId)) {241 throw new Meteor.Error('api.personalspaces.backToDefaultElement.notPermitted', i18n.__('api.users.notPermitted'));242 }243 // remove all entries matching item type and element_id244 PersonalSpaces.update(245 { userId: this.userId },246 {247 $pull: {248 unsorted: { type, element_id: elementId },249 'sorted.$[].elements': { type, element_id: elementId },250 },251 },252 );253 // add element in default zone according to element type254 switch (type) {255 case 'service':256 addService._execute({ userId: this.userId }, { serviceId: elementId });257 break;258 case 'group':259 addGroup._execute({ userId: this.userId }, { groupId: elementId });260 break;261 case 'link':262 addUserBookmark._execute({ userId: this.userId }, { bookmarkId: elementId });263 break;264 default:265 throw new Meteor.Error('api.personalspaces.backToDefaultElement.unknownType');266 }267 },268});269// Get list of all method names on User270const LISTS_METHODS = _.pluck(271 [updatePersonalSpace, removeElement, addService, addGroup, addUserBookmark, checkPersonalSpace, backToDefaultElement],272 'name',273);274if (Meteor.isServer) {275 // Only allow 5 list operations per connection per second276 DDPRateLimiter.addRule(277 {278 name(name) {279 return _.contains(LISTS_METHODS, name);280 },281 // Rate limit per connection ID282 connectionId() {283 return true;284 },285 },286 5,287 1000,288 );...

Full Screen

Full Screen

menuItems.js

Source:menuItems.js Github

copy

Full Screen

1import { lazy } from 'react';2import {3 // Assignment,4 // Home as HomeIcon,5 // HowToVote,6 Fingerprint,7 // People,8 // Settings,9 Schedule,10 TableChart,11} from '@material-ui/icons';12const Superpower = lazy(() => import('../Superpower'));13// const UserPermissions = lazy(() => import('../UserPermissions'));14const NotPermitted = lazy(() => import('../NotPermitted'));15const Definitions = lazy(() => import('../Definitions'));16const Schedules = lazy(() => import('../Schedules'));17const EditDefinition = lazy(() => import('../EditDefinition'));18// const Home = lazy(() => import('../Home'));19// const Branch = lazy(() => import('../Branch'));20// const Configuration = lazy(() => import('../Configuration'));21const getMenuItems = ({ permissions: perms }) => {22 const menuItems = [23 {24 path: process.env.API_URL,25 to: process.env.API_URL,26 name: 'Reports',27 icon: TableChart,28 component: Definitions,29 exact: true,30 },31 {32 path: `${process.env.API_URL}schedules`,33 to: `${process.env.API_URL}schedules`,34 name: 'Schedules',35 icon: Schedule,36 component: Schedules,37 // exact: true,38 },39 {40 path: `${process.env.API_URL}editDefinition/:_id`,41 // to: `${process.env.API_URL}editDefinition/:_id`,42 name: 'EditDefinition',43 // icon: TableChart,44 component: EditDefinition,45 // exact: true,46 },47 {48 // path: `${process.env.API_URL}br/:branchName/:itemType?/:itemName?/:reviewId?`,49 // // to: `${process.env.API_URL}br/${branch.name}/forms/Liability`,50 // name: 'branch.name',51 // icon: Assignment,52 // component: Branch,53 // exact: false,54 // }, {55 // path: `${process.env.API_URL}requests`,56 // to: `${process.env.API_URL}requests`,57 // name: 'Feature Request',58 // icon: HowToVote,59 // component: Requests,60 // }, {61 path: `${process.env.API_URL}notPermitted`,62 // to: `${process.env.API_URL}notPermitted`,63 name: 'Not Permitted',64 component: NotPermitted,65 },66 ];67 // if (perms.sitewide && perms.sitewide.includes('Create/Edit/Delete Branches')) {68 // menuItems.push({69 // path: `${process.env.API_URL}config`,70 // to: `${process.env.API_URL}config`,71 // name: 'Configuration',72 // icon: Settings,73 // component: Configuration,74 // divider: true,75 // });76 // }77 if (perms.sitewide && perms.sitewide.includes('Superpower')) {78 menuItems.push({79 path: `${process.env.API_URL}superpower`,80 to: `${process.env.API_URL}superpower`,81 name: 'Superpower',82 icon: Fingerprint,83 divider: true,84 component: Superpower,85 });86 }87 // if (perms.sitewide && perms.sitewide.includes('Edit User Permissions')) {88 // menuItems.push({89 // path: `${process.env.API_URL}userPermissions`,90 // to: `${process.env.API_URL}userPermissions`,91 // name: 'User Permissions',92 // icon: People,93 // divider: true,94 // component: UserPermissions,95 // });96 // }97 return menuItems;98};...

Full Screen

Full Screen

ipcMainEvent.js

Source:ipcMainEvent.js Github

copy

Full Screen

1import { ipcMain, shell } from 'electron';2import { getAppDataInfo } from './util';3import path from 'path';4import fs from 'fs';5const { readdir } = require('fs/promises');6function registerIpcMainEvent() {7 // 刚打开应用,开始遍历 AppData 所有文件8 ipcMain.handle('get-app-data-info', async (event) => {9 const result = await getAppDataInfo();10 return result;11 });12 // 在系统资源管理器中打开指定目录13 ipcMain.on('open-explorer', (event, data) => {14 console.log(data, 'open-explorer');15 shell.showItemInFolder(data);16 });17 // 获取指定目录下的数据信息18 ipcMain.handle('get-folder-content', async (event, folderPath) => {19 console.log(folderPath, 'folderPath', global.alreadyPath);20 if (global.alreadyPath[folderPath] || Object.keys(global.alreadyPath).some(i => global.alreadyPath[i] && folderPath.startsWith(i))) {21 const filesData = [];22 const foldersData = [];23 const files = await readdir(folderPath);24 for (const file of files) {25 const p = path.join(folderPath, file);26 const stat = fs.statSync(p);27 let size = 0;28 if (stat.isFile()) {29 size = stat.size;30 const notPermitted = size === 'not permitted';31 filesData.push({32 name: file,33 path: p,34 notPermitted: notPermitted,35 size: !notPermitted && size,36 ksize: !notPermitted && (size / 1024),37 msize: !notPermitted && (size / 1024 / 1024),38 gsize: !notPermitted && (size / 1024 / 1024 / 1024),39 isDir: stat.isDirectory(),40 isFile: stat.isFile(),41 });42 }43 44 if (stat.isDirectory()) {45 size = global.sizeMap[p];46 const notPermitted = size === 'not permitted';47 foldersData.push({48 name: file,49 path: p,50 notPermitted: notPermitted,51 size: !notPermitted && size,52 ksize: !notPermitted && (size / 1024),53 msize: !notPermitted && (size / 1024 / 1024),54 gsize: !notPermitted && (size / 1024 / 1024 / 1024),55 isDir: stat.isDirectory(),56 isFile: stat.isFile(),57 });58 }59 }60 61 filesData.sort((a, b) => {62 if (a.name > b.name) return 1;63 if (a.name < b.name) return -1;64 return 0;65 });66 foldersData.sort((a, b) => {67 if (a.name > b.name) return 1;68 if (a.name < b.name) return -1;69 return 0;70 });71 return [...foldersData, ...filesData];72 } else {73 return null74 }75 });76}...

Full Screen

Full Screen

bbbMethods.js

Source:bbbMethods.js Github

copy

Full Screen

1import { Meteor } from 'meteor/meteor';2import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';3import { _ } from 'meteor/underscore';4import SimpleSchema from 'simpl-schema';5import { ValidatedMethod } from 'meteor/mdg:validated-method';6import { Roles } from 'meteor/alanning:roles';7import i18n from 'meteor/universe:i18n';8import { isActive, getLabel } from '../../utils';9import Groups from '../groups';10import BBBClient from '../../appclients/bbbClient';11export const getMeetingURL = new ValidatedMethod({12 name: 'groups.getMeetingURL',13 validate: new SimpleSchema({14 groupId: { type: String, regEx: SimpleSchema.RegEx.Id, label: getLabel('api.groups.labels.id') },15 }).validator(),16 async run({ groupId }) {17 if (!isActive(this.userId)) {18 throw new Meteor.Error('api.groups.getMeetingURL.notPermitted', i18n.__('api.users.mustBeLoggedIn'));19 }20 // check group existence and membership21 const group = Groups.findOne(groupId);22 if (group === undefined) {23 throw new Meteor.Error('api.groups.favGroup.unknownService', i18n.__('api.groups.unknownGroup'));24 }25 if (!Roles.userIsInRole(this.userId, ['admin', 'animator', 'member'], groupId)) {26 throw new Meteor.Error('api.groups.getMeetingURL.notPermitted', i18n.__('api.users.notPermitted'));27 }28 const promisedResult = await BBBClient.createMeeting(group.slug, this.userId);29 return promisedResult;30 },31});32export const checkMeeting = new ValidatedMethod({33 name: 'groups.checkMeeting',34 validate: new SimpleSchema({35 groupId: { type: String, regEx: SimpleSchema.RegEx.Id, label: getLabel('api.groups.labels.id') },36 }).validator(),37 async run({ groupId }) {38 if (!isActive(this.userId)) {39 throw new Meteor.Error('api.groups.getMeetingURL.notPermitted', i18n.__('api.users.mustBeLoggedIn'));40 }41 // check group existence and membership42 const group = Groups.findOne(groupId);43 if (group === undefined) {44 throw new Meteor.Error('api.groups.favGroup.unknownService', i18n.__('api.groups.unknownGroup'));45 }46 if (!Roles.userIsInRole(this.userId, ['admin', 'animator', 'member'], groupId)) {47 throw new Meteor.Error('api.groups.getMeetingURL.notPermitted', i18n.__('api.users.notPermitted'));48 }49 const promisedResult = await BBBClient.checkRunning(group._id, group.slug);50 return promisedResult;51 },52});53// Get list of all method names on User54const LISTS_METHODS = _.pluck([getMeetingURL, checkMeeting], 'name');55// Only allow 5 list operations per connection per second56DDPRateLimiter.addRule(57 {58 name(name) {59 return _.contains(LISTS_METHODS, name);60 },61 // Rate limit per connection ID62 connectionId() {63 return true;64 },65 },66 5,67 1000,...

Full Screen

Full Screen

create-expenditure.js

Source:create-expenditure.js Github

copy

Full Screen

1module.exports = {2 friendlyName: 'Create income category',3 description: 'Create new income category for user.',4 inputs: {5 sum: {6 type: 'number',7 required: true8 },9 billId: {10 type: 'number',11 required: true12 },13 categoryId: {14 type: 'number',15 required: true16 },17 },18 exits: {19 success: {20 description: 'New transaction created.',21 responseType: 'created'22 },23 notFound: {24 description: 'No user with the specified ID was found in the database.',25 responseType: 'notFound',26 },27 notPermitted: {28 description: 'You are not permitted to see this record.',29 responseType: 'notpermitted'30 },31 wrongCategory: {32 description: 'You entered wrong catagory.',33 responseType: 'notpermitted'34 }35 },36 fn: async function ({ sum, billId, categoryId }) {37 var classification = 'EXP';38 var userId = this.req.session.userId;39 var bill = await Bill.findOne({ id: billId });40 if (!bill) { throw 'notFound'; }41 if (bill.userOwner !== this.req.session.userId) {42 throw 'notPermitted';43 }44 var category = await Category.findOne({ id: categoryId });45 if (!category) { throw 'notFound'; }46 if (category.expenditureTypes !== bill.id) {47 throw 'notPermitted';48 }49 await Transaction.create({50 sum: sum,51 classification: classification,52 belongs: billId,53 user: userId,54 category: categoryId55 });56 await Bill.update({ id: billId }) // add money on bill57 .set({58 sum: bill.sum - sum59 });60 }...

Full Screen

Full Screen

permissions.js

Source:permissions.js Github

copy

Full Screen

1var _u = require("underscore");2var notPermitted = "You do not have permission to do that.";3var unauthorized = "You must be logged in.";4function checkLogin(session) {5 if(typeof session.auth === "undefined") {6 return false;7 }8 return true;9}10function checkPermission(permission, session) {11 if(typeof session.auth !== "undefined") {12 if(typeof(session.auth.permissions !== "undefined")) {13 // Underscore's indexOf returns -1 if the item is not in the array14 // http://documentcloud.github.com/underscore/#indexOf15 if(_u.indexOf(session.auth.permissions, permission) !== -1) {16 return true;17 }18 }19 }20 return false;21}22exports.checkLogin = function() {23 return function(req, res, next) {24 if(checkLogin(req.session)) {25 next();26 } else {27 req.flash("error", unauthorized);28 res.redirect("/login");29 }30 };31};32exports.checkPermission = function(permission) {33 return function(req, res, next) {34 if(checkPermission(permission, req.session)) {35 next();36 } else {37 req.flash("error", notPermitted);38 res.redirect("home");39 }40 };41};42exports.checkLoginAndPermission = function(permission) {43 return function(req, res, next) {44 if(checkLogin(req.session)) {45 if(checkPermission(permission, req.session)) {46 next();47 } else {48 req.flash("error", notPermitted);49 res.redirect("home");50 }51 } else {52 req.flash("error", unauthorized);53 res.redirect("/login");54 }55 };...

Full Screen

Full Screen

delete.js

Source:delete.js Github

copy

Full Screen

1module.exports = {2 friendlyName: 'Delete category',3 description: 'Delete category by id.',4 inputs: {5 categoryId: {6 type: 'number',7 required: true8 }9 },10 exits: {11 success: {12 description: 'Category was successfully deleted.'13 },14 notFound: {15 description: 'No category with the specified ID was found in the database.',16 responseType: 'notFound'17 },18 notPermitted: {19 description: 'You are not permitted to see this record.',20 responseType: 'notpermitted'21 }22 },23 fn: async function ({ categoryId }) {24 var category = await Category.findOne({ id: categoryId });25 if (!category) { throw 'notFound'; }26 if (category.incomeTypes !== this.req.session.userId && category.incomeTypes !== null) {27 throw 'notPermitted';28 }29 var bill = await Bill.findOne({ id: category.expenditureTypes }); // this is bill id to which category belongs is category.expenditureTypes30 if (bill && bill.userOwner !== this.req.session.userId) {31 throw 'notPermitted';32 }33 await Category.destroy({ id: categoryId });34 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2describe('Array', function() {3 describe('#indexOf()', function() {4 it('should return -1 when the value is not present', function() {5 assert.equal(-1, [1,2,3].indexOf(4));6 });7 });8});9var assert = require('assert');10describe('Array', function() {11 describe('#indexOf()', function() {12 it('should return -1 when the value is not present', function() {13 assert.notEqual(-1, [1,2,3].indexOf(4));14 });15 });16});17var assert = require('assert');18describe('Array', function() {19 describe('#indexOf()', function() {20 it('should return -1 when the value is not present', function() {21 assert.notEqual(-1, [1,2,3].indexOf(4));22 });23 });24});25var assert = require('assert');26describe('Array', function() {27 describe('#indexOf()', function() {28 it('should return -1 when the value is not present', function() {29 assert.notEqual(-1, [1,2,3].indexOf(4));30 });31 });32});33var assert = require('assert');34describe('Array', function() {35 describe('#indexOf()', function() {36 it('should return -1 when the value is not present', function() {37 assert.notEqual(-1, [1,2,3].indexOf(4));38 });39 });40});41var assert = require('assert');42describe('Array', function() {43 describe('#indexOf()', function() {44 it('should return -1 when the value is not present', function() {45 assert.notEqual(-1, [1,2,3].indexOf(4));46 });47 });48});49var assert = require('assert');50describe('Array', function() {51 describe('#indexOf()', function() {52 it('should return -1 when the value is not present', function() {53 assert.notEqual(-1, [1,2,3].indexOf(

Full Screen

Using AI Code Generation

copy

Full Screen

1var notPermitted = require('mocha').notPermitted;2var permitted = require('mocha').permitted;3var isPermitted = require('mocha').isPermitted;4var isNotPermitted = require('mocha').isNotPermitted;5var isPermitted = require('mocha').isPermitted;6var isNotPermitted = require('mocha').isNotPermitted;7var permitted = require('mocha').permitted;8var isPermitted = require('mocha').isPermitted;9var isNotPermitted = require('mocha').isNotPermitted;10var isPermitted = require('mocha').isPermitted;11var isNotPermitted = require('mocha').isNotPermitted;12var permitted = require('mocha').permitted;13var isPermitted = require('mocha').isPermitted;14var isNotPermitted = require('mocha').isNotPermitted;15var isPermitted = require('mocha').isPermitted;16var isNotPermitted = require('mocha').isNotPermitted;17var permitted = require('mocha').permitted;18var isPermitted = require('mocha').isPermitted;19var isNotPermitted = require('mocha').isNotPermitted;

Full Screen

Using AI Code Generation

copy

Full Screen

1var notPermitted = require('mocha').notPermitted;2var permitted = require('mocha').permitted;3notPermitted('test', function () {4});5permitted('test', function () {6});

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var test = require('selenium-webdriver/testing');3var webdriver = require('selenium-webdriver');4var By = webdriver.By;5var until = webdriver.until;6test.describe('Test Suite 1', function() {7 var driver;8 test.before(function() {9 driver = new webdriver.Builder()10 .forBrowser('chrome')11 .build();12 });13 test.it('Test Case 1', function() {14 driver.findElement(By.name('q')).sendKeys('webdriver');15 driver.findElement(By.name('btnG')).click();16 driver.wait(until.titleIs('webdriver - Google Search'), 1000);17 });18 test.after(function() {19 driver.quit();20 });21});

Full Screen

Using AI Code Generation

copy

Full Screen

1var notPermitted = require('mocha').notPermitted;2var context = require('mocha').context;3var it = require('mocha').it;4var describe = require('mocha').describe;5var before = require('mocha').before;6var beforeEach = require('mocha').beforeEach;7var after = require('mocha').after;8var afterEach = require('mocha').afterEach;9var xit = require('mocha').xit;10var xdescribe = require('mocha').xdescribe;11var specify = require('mocha').specify;12var xspecify = require('mocha').xspecify;13var itOnly = require('mocha').it.only;14var itSkip = require('mocha').it.skip;15var describeOnly = require('mocha').describe.only;16var describeSkip = require('mocha').describe.skip;17var specifyOnly = require('mocha').specify.only;18var specifySkip = require('mocha').specify.skip;19var before = require('mocha').before;20var beforeEach = require('mocha').beforeEach;21var after = require('mocha').after;22var afterEach = require('mocha').afterEach;23var setup = require('mocha').setup;24var teardown = require('mocha').teardown;

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var notPermitted = require('mocha').notPermitted;3describe('notPermitted', function() {4 it('should return true if the string contains not permitted characters', function() {5 assert.equal(true, notPermitted('!@#$%^&*()'));6 });7});8module.exports = function(str) {9 var regex = /[!@#$%^&*()+=\-\[\]\\\';,/{}|\\":<>\?]/g;10 return regex.test(str);11};12at Context.it (test.js:8:12)13at callFn (node_modules/mocha/lib/runnable.js:334:21)14at Test.Runnable.run (node_modules/mocha/lib/runnable.js:327:7)15at Runner.runTest (node_modules/mocha/lib/runner.js:429:10)16at next (node_modules/mocha/lib/runner.js:349:14)17at next (node_modules/mocha/lib/runner.js:295:14)18at Immediate._onImmediate (node_modules/mocha/lib/runner.js:339:5)19at runCallback (timers.js:637:20)20at tryOnImmediate (timers.js:610:5)21at processImmediate [as _immediateCallback] (timers.js:582:5)22module.exports = function(str) {23 var regex = /[!@#$%^&*()+=\-\[\]\\\';,/{}|\\":<>\?]/g;24 return !regex.test(str);25};

Full Screen

Using AI Code Generation

copy

Full Screen

1var should = require('chai').should();2var notPermitted = require('chai').notPermitted;3var notPermitted = should.notPermitted;4var notPermitted = require('chai').notPermitted;5var notPermitted = should.notPermitted;6describe('notPermitted', function() {7 it('does not throw an error when the given value is not a number', function() {8 (function() {9 notPermitted('foo');10 }).should.not.throw();11 });12 it('throws an error when the given value is a number', function() {13 (function() {14 notPermitted(123);15 }).should.throw();16 });17});

Full Screen

Using AI Code Generation

copy

Full Screen

1var notPermitted = require('mocha').notPermitted;2describe('test', function() {3 it('should not be permitted', function() {4 notPermitted();5 });6});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mocha automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful