users.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619
  1. //var nodemailer = require('nodemailer');
  2. import { SyncedCron } from 'meteor/percolate:synced-cron';
  3. import { TAPi18n } from '/imports/i18n';
  4. import ImpersonatedUsers from './impersonatedUsers';
  5. import { Index, MongoDBEngine } from 'meteor/easy:search';
  6. // Sandstorm context is detected using the METEOR_SETTINGS environment variable
  7. // in the package definition.
  8. const isSandstorm =
  9. Meteor.settings && Meteor.settings.public && Meteor.settings.public.sandstorm;
  10. Users = Meteor.users;
  11. const allowedSortValues = [
  12. '-modifiedAt',
  13. 'modifiedAt',
  14. '-title',
  15. 'title',
  16. '-sort',
  17. 'sort',
  18. ];
  19. const defaultSortBy = allowedSortValues[0];
  20. /**
  21. * A User in wekan
  22. */
  23. Users.attachSchema(
  24. new SimpleSchema({
  25. username: {
  26. /**
  27. * the username of the user
  28. */
  29. type: String,
  30. optional: true,
  31. // eslint-disable-next-line consistent-return
  32. autoValue() {
  33. if (this.isInsert && !this.isSet) {
  34. const name = this.field('profile.fullname');
  35. if (name.isSet) {
  36. return name.value.toLowerCase().replace(/\s/g, '');
  37. }
  38. }
  39. },
  40. },
  41. orgs: {
  42. /**
  43. * the list of organizations that a user belongs to
  44. */
  45. type: [Object],
  46. optional: true,
  47. },
  48. 'orgs.$.orgId': {
  49. /**
  50. * The uniq ID of the organization
  51. */
  52. type: String,
  53. },
  54. 'orgs.$.orgDisplayName': {
  55. /**
  56. * The display name of the organization
  57. */
  58. type: String,
  59. },
  60. teams: {
  61. /**
  62. * the list of teams that a user belongs to
  63. */
  64. type: [Object],
  65. optional: true,
  66. },
  67. 'teams.$.teamId': {
  68. /**
  69. * The uniq ID of the team
  70. */
  71. type: String,
  72. },
  73. 'teams.$.teamDisplayName': {
  74. /**
  75. * The display name of the team
  76. */
  77. type: String,
  78. },
  79. emails: {
  80. /**
  81. * the list of emails attached to a user
  82. */
  83. type: [Object],
  84. optional: true,
  85. },
  86. 'emails.$.address': {
  87. /**
  88. * The email address
  89. */
  90. type: String,
  91. regEx: SimpleSchema.RegEx.Email,
  92. },
  93. 'emails.$.verified': {
  94. /**
  95. * Has the email been verified
  96. */
  97. type: Boolean,
  98. },
  99. createdAt: {
  100. /**
  101. * creation date of the user
  102. */
  103. type: Date,
  104. // eslint-disable-next-line consistent-return
  105. autoValue() {
  106. if (this.isInsert) {
  107. return new Date();
  108. } else if (this.isUpsert) {
  109. return {
  110. $setOnInsert: new Date(),
  111. };
  112. } else {
  113. this.unset();
  114. }
  115. },
  116. },
  117. modifiedAt: {
  118. type: Date,
  119. denyUpdate: false,
  120. // eslint-disable-next-line consistent-return
  121. autoValue() {
  122. if (this.isInsert || this.isUpsert || this.isUpdate) {
  123. return new Date();
  124. } else {
  125. this.unset();
  126. }
  127. },
  128. },
  129. profile: {
  130. /**
  131. * profile settings
  132. */
  133. type: Object,
  134. optional: true,
  135. // eslint-disable-next-line consistent-return
  136. autoValue() {
  137. if (this.isInsert && !this.isSet) {
  138. return {
  139. boardView: 'board-view-swimlanes',
  140. };
  141. }
  142. },
  143. },
  144. 'profile.avatarUrl': {
  145. /**
  146. * URL of the avatar of the user
  147. */
  148. type: String,
  149. optional: true,
  150. },
  151. 'profile.emailBuffer': {
  152. /**
  153. * list of email buffers of the user
  154. */
  155. type: [String],
  156. optional: true,
  157. },
  158. 'profile.fullname': {
  159. /**
  160. * full name of the user
  161. */
  162. type: String,
  163. optional: true,
  164. },
  165. 'profile.showDesktopDragHandles': {
  166. /**
  167. * does the user want to show desktop drag handles?
  168. */
  169. type: Boolean,
  170. optional: true,
  171. },
  172. 'profile.hideCheckedItems': {
  173. /**
  174. * does the user want to hide checked checklist items?
  175. */
  176. type: Boolean,
  177. optional: true,
  178. },
  179. 'profile.cardMaximized': {
  180. /**
  181. * has user clicked maximize card?
  182. */
  183. type: Boolean,
  184. optional: true,
  185. },
  186. 'profile.customFieldsGrid': {
  187. /**
  188. * has user at card Custom Fields have Grid (false) or one per row (true) layout?
  189. */
  190. type: Boolean,
  191. optional: true,
  192. },
  193. 'profile.hiddenSystemMessages': {
  194. /**
  195. * does the user want to hide system messages?
  196. */
  197. type: Boolean,
  198. optional: true,
  199. },
  200. 'profile.hiddenMinicardLabelText': {
  201. /**
  202. * does the user want to hide minicard label texts?
  203. */
  204. type: Boolean,
  205. optional: true,
  206. },
  207. 'profile.initials': {
  208. /**
  209. * initials of the user
  210. */
  211. type: String,
  212. optional: true,
  213. },
  214. 'profile.invitedBoards': {
  215. /**
  216. * board IDs the user has been invited to
  217. */
  218. type: [String],
  219. optional: true,
  220. },
  221. 'profile.language': {
  222. /**
  223. * language of the user
  224. */
  225. type: String,
  226. optional: true,
  227. },
  228. 'profile.moveAndCopyDialog': {
  229. /**
  230. * move and copy card dialog
  231. */
  232. type: Object,
  233. optional: true,
  234. blackbox: true,
  235. },
  236. 'profile.moveAndCopyDialog.$.boardId': {
  237. /**
  238. * last selected board id
  239. */
  240. type: String,
  241. },
  242. 'profile.moveAndCopyDialog.$.swimlaneId': {
  243. /**
  244. * last selected swimlane id
  245. */
  246. type: String,
  247. },
  248. 'profile.moveAndCopyDialog.$.listId': {
  249. /**
  250. * last selected list id
  251. */
  252. type: String,
  253. },
  254. 'profile.moveChecklistDialog': {
  255. /**
  256. * move checklist dialog
  257. */
  258. type: Object,
  259. optional: true,
  260. blackbox: true,
  261. },
  262. 'profile.moveChecklistDialog.$.boardId': {
  263. /**
  264. * last selected board id
  265. */
  266. type: String,
  267. },
  268. 'profile.moveChecklistDialog.$.swimlaneId': {
  269. /**
  270. * last selected swimlane id
  271. */
  272. type: String,
  273. },
  274. 'profile.moveChecklistDialog.$.listId': {
  275. /**
  276. * last selected list id
  277. */
  278. type: String,
  279. },
  280. 'profile.moveChecklistDialog.$.cardId': {
  281. /**
  282. * last selected card id
  283. */
  284. type: String,
  285. },
  286. 'profile.copyChecklistDialog': {
  287. /**
  288. * copy checklist dialog
  289. */
  290. type: Object,
  291. optional: true,
  292. blackbox: true,
  293. },
  294. 'profile.copyChecklistDialog.$.boardId': {
  295. /**
  296. * last selected board id
  297. */
  298. type: String,
  299. },
  300. 'profile.copyChecklistDialog.$.swimlaneId': {
  301. /**
  302. * last selected swimlane id
  303. */
  304. type: String,
  305. },
  306. 'profile.copyChecklistDialog.$.listId': {
  307. /**
  308. * last selected list id
  309. */
  310. type: String,
  311. },
  312. 'profile.copyChecklistDialog.$.cardId': {
  313. /**
  314. * last selected card id
  315. */
  316. type: String,
  317. },
  318. 'profile.notifications': {
  319. /**
  320. * enabled notifications for the user
  321. */
  322. type: [Object],
  323. optional: true,
  324. },
  325. 'profile.notifications.$.activity': {
  326. /**
  327. * The id of the activity this notification references
  328. */
  329. type: String,
  330. },
  331. 'profile.notifications.$.read': {
  332. /**
  333. * the date on which this notification was read
  334. */
  335. type: Date,
  336. optional: true,
  337. },
  338. 'profile.rescueCardDescription': {
  339. /**
  340. * show dialog for saving card description on unintentional card closing
  341. */
  342. type: Boolean,
  343. optional: true,
  344. },
  345. 'profile.showCardsCountAt': {
  346. /**
  347. * showCardCountAt field of the user
  348. */
  349. type: Number,
  350. optional: true,
  351. },
  352. 'profile.startDayOfWeek': {
  353. /**
  354. * startDayOfWeek field of the user
  355. */
  356. type: Number,
  357. optional: true,
  358. },
  359. 'profile.starredBoards': {
  360. /**
  361. * list of starred board IDs
  362. */
  363. type: [String],
  364. optional: true,
  365. },
  366. 'profile.icode': {
  367. /**
  368. * icode
  369. */
  370. type: String,
  371. optional: true,
  372. },
  373. 'profile.boardView': {
  374. /**
  375. * boardView field of the user
  376. */
  377. type: String,
  378. optional: true,
  379. allowedValues: [
  380. 'board-view-swimlanes',
  381. 'board-view-lists',
  382. 'board-view-cal',
  383. ],
  384. },
  385. 'profile.listSortBy': {
  386. /**
  387. * default sort list for user
  388. */
  389. type: String,
  390. optional: true,
  391. defaultValue: defaultSortBy,
  392. allowedValues: allowedSortValues,
  393. },
  394. 'profile.templatesBoardId': {
  395. /**
  396. * Reference to the templates board
  397. */
  398. type: String,
  399. defaultValue: '',
  400. },
  401. 'profile.cardTemplatesSwimlaneId': {
  402. /**
  403. * Reference to the card templates swimlane Id
  404. */
  405. type: String,
  406. defaultValue: '',
  407. },
  408. 'profile.listTemplatesSwimlaneId': {
  409. /**
  410. * Reference to the list templates swimlane Id
  411. */
  412. type: String,
  413. defaultValue: '',
  414. },
  415. 'profile.boardTemplatesSwimlaneId': {
  416. /**
  417. * Reference to the board templates swimlane Id
  418. */
  419. type: String,
  420. defaultValue: '',
  421. },
  422. 'profile.listWidths': {
  423. /**
  424. * User-specified width of each list (or nothing if default).
  425. * profile[boardId][listId] = width;
  426. */
  427. type: Object,
  428. defaultValue: {},
  429. blackbox: true,
  430. },
  431. 'profile.swimlaneHeights': {
  432. /**
  433. * User-specified heights of each swimlane (or nothing if default).
  434. * profile[boardId][swimlaneId] = height;
  435. */
  436. type: Object,
  437. defaultValue: {},
  438. blackbox: true,
  439. },
  440. services: {
  441. /**
  442. * services field of the user
  443. */
  444. type: Object,
  445. optional: true,
  446. blackbox: true,
  447. },
  448. heartbeat: {
  449. /**
  450. * last time the user has been seen
  451. */
  452. type: Date,
  453. optional: true,
  454. },
  455. isAdmin: {
  456. /**
  457. * is the user an admin of the board?
  458. */
  459. type: Boolean,
  460. optional: true,
  461. },
  462. createdThroughApi: {
  463. /**
  464. * was the user created through the API?
  465. */
  466. type: Boolean,
  467. optional: true,
  468. },
  469. loginDisabled: {
  470. /**
  471. * loginDisabled field of the user
  472. */
  473. type: Boolean,
  474. optional: true,
  475. },
  476. authenticationMethod: {
  477. /**
  478. * authentication method of the user
  479. */
  480. type: String,
  481. optional: false,
  482. defaultValue: 'password',
  483. },
  484. sessionData: {
  485. /**
  486. * profile settings
  487. */
  488. type: Object,
  489. optional: true,
  490. // eslint-disable-next-line consistent-return
  491. autoValue() {
  492. if (this.isInsert && !this.isSet) {
  493. return {};
  494. }
  495. },
  496. },
  497. 'sessionData.totalHits': {
  498. /**
  499. * Total hits from last searchquery['members.userId'] = Meteor.userId();
  500. * last hit that was returned
  501. */
  502. type: Number,
  503. optional: true,
  504. },
  505. importUsernames: {
  506. /**
  507. * username for imported
  508. */
  509. type: [String],
  510. optional: true,
  511. },
  512. lastConnectionDate: {
  513. type: Date,
  514. optional: true,
  515. },
  516. }),
  517. );
  518. Users.allow({
  519. update(userId, doc) {
  520. const user = Users.findOne({
  521. _id: userId,
  522. });
  523. if ((user && user.isAdmin) || (Meteor.user() && Meteor.user().isAdmin))
  524. return true;
  525. if (!user) {
  526. return false;
  527. }
  528. return doc._id === userId;
  529. },
  530. remove(userId, doc) {
  531. const adminsNumber = Users.find({
  532. isAdmin: true,
  533. }).count();
  534. const { isAdmin } = Users.findOne(
  535. {
  536. _id: userId,
  537. },
  538. {
  539. fields: {
  540. isAdmin: 1,
  541. },
  542. },
  543. );
  544. // Prevents remove of the only one administrator
  545. if (adminsNumber === 1 && isAdmin && userId === doc._id) {
  546. return false;
  547. }
  548. // If it's the user or an admin
  549. return userId === doc._id || isAdmin;
  550. },
  551. fetch: [],
  552. });
  553. // Non-Admin users can not change to Admin
  554. Users.deny({
  555. update(userId, board, fieldNames) {
  556. return _.contains(fieldNames, 'isAdmin') && !Meteor.user().isAdmin;
  557. },
  558. fetch: [],
  559. });
  560. // Search a user in the complete server database by its name, username or emails adress. This
  561. // is used for instance to add a new user to a board.
  562. UserSearchIndex = new Index({
  563. collection: Users,
  564. fields: ['username', 'profile.fullname', 'profile.avatarUrl'],
  565. allowedFields: ['username', 'profile.fullname', 'profile.avatarUrl'],
  566. engine: new MongoDBEngine({
  567. fields: function (searchObject, options) {
  568. return {
  569. username: 1,
  570. 'profile.fullname': 1,
  571. 'profile.avatarUrl': 1,
  572. };
  573. },
  574. }),
  575. });
  576. Users.safeFields = {
  577. _id: 1,
  578. username: 1,
  579. 'profile.fullname': 1,
  580. 'profile.avatarUrl': 1,
  581. 'profile.initials': 1,
  582. orgs: 1,
  583. teams: 1,
  584. authenticationMethod: 1,
  585. lastConnectionDate: 1,
  586. };
  587. if (Meteor.isClient) {
  588. Users.helpers({
  589. isBoardMember() {
  590. const board = Utils.getCurrentBoard();
  591. return board && board.hasMember(this._id);
  592. },
  593. isNotNoComments() {
  594. const board = Utils.getCurrentBoard();
  595. return (
  596. board && board.hasMember(this._id) && !board.hasNoComments(this._id)
  597. );
  598. },
  599. isNoComments() {
  600. const board = Utils.getCurrentBoard();
  601. return board && board.hasNoComments(this._id);
  602. },
  603. isNotCommentOnly() {
  604. const board = Utils.getCurrentBoard();
  605. return (
  606. board && board.hasMember(this._id) && !board.hasCommentOnly(this._id)
  607. );
  608. },
  609. isCommentOnly() {
  610. const board = Utils.getCurrentBoard();
  611. return board && board.hasCommentOnly(this._id);
  612. },
  613. isNotWorker() {
  614. const board = Utils.getCurrentBoard();
  615. return board && board.hasMember(this._id) && !board.hasWorker(this._id);
  616. },
  617. isWorker() {
  618. const board = Utils.getCurrentBoard();
  619. return board && board.hasWorker(this._id);
  620. },
  621. isBoardAdmin(boardId) {
  622. let board;
  623. if (boardId) {
  624. board = Boards.findOne(boardId);
  625. } else {
  626. board = Utils.getCurrentBoard();
  627. }
  628. return board && board.hasAdmin(this._id);
  629. },
  630. });
  631. }
  632. Users.parseImportUsernames = (usernamesString) => {
  633. return usernamesString.trim().split(new RegExp('\\s*[,;]\\s*'));
  634. };
  635. Users.helpers({
  636. importUsernamesString() {
  637. if (this.importUsernames) {
  638. return this.importUsernames.join(', ');
  639. }
  640. return '';
  641. },
  642. teamIds() {
  643. if (this.teams) {
  644. // TODO: Should the Team collection be queried to determine if the team isActive?
  645. return this.teams.map((team) => {
  646. return team.teamId;
  647. });
  648. }
  649. return [];
  650. },
  651. orgIds() {
  652. if (this.orgs) {
  653. // TODO: Should the Org collection be queried to determine if the organization isActive?
  654. return this.orgs.map((org) => {
  655. return org.orgId;
  656. });
  657. }
  658. return [];
  659. },
  660. orgsUserBelongs() {
  661. if (this.orgs) {
  662. return this.orgs
  663. .map(function (org) {
  664. return org.orgDisplayName;
  665. })
  666. .sort()
  667. .join(',');
  668. }
  669. return '';
  670. },
  671. orgIdsUserBelongs() {
  672. if (this.orgs) {
  673. return this.orgs
  674. .map(function (org) {
  675. return org.orgId;
  676. })
  677. .join(',');
  678. }
  679. return '';
  680. },
  681. teamsUserBelongs() {
  682. if (this.teams) {
  683. return this.teams
  684. .map(function (team) {
  685. return team.teamDisplayName;
  686. })
  687. .sort()
  688. .join(',');
  689. }
  690. return '';
  691. },
  692. teamIdsUserBelongs() {
  693. if (this.teams) {
  694. return this.teams
  695. .map(function (team) {
  696. return team.teamId;
  697. })
  698. .join(',');
  699. }
  700. return '';
  701. },
  702. boards() {
  703. return Boards.userBoards(this._id, null, {}, { sort: { sort: 1 } });
  704. },
  705. starredBoards() {
  706. const { starredBoards = [] } = this.profile || {};
  707. return Boards.userBoards(
  708. this._id,
  709. false,
  710. { _id: { $in: starredBoards } },
  711. { sort: { sort: 1 } },
  712. );
  713. },
  714. hasStarred(boardId) {
  715. const { starredBoards = [] } = this.profile || {};
  716. return _.contains(starredBoards, boardId);
  717. },
  718. invitedBoards() {
  719. const { invitedBoards = [] } = this.profile || {};
  720. return Boards.userBoards(
  721. this._id,
  722. false,
  723. { _id: { $in: invitedBoards } },
  724. { sort: { sort: 1 } },
  725. );
  726. },
  727. isInvitedTo(boardId) {
  728. const { invitedBoards = [] } = this.profile || {};
  729. return _.contains(invitedBoards, boardId);
  730. },
  731. _getListSortBy() {
  732. const profile = this.profile || {};
  733. const sortBy = profile.listSortBy || defaultSortBy;
  734. const keyPattern = /^(-{0,1})(.*$)/;
  735. const ret = [];
  736. if (keyPattern.exec(sortBy)) {
  737. ret[0] = RegExp.$2;
  738. ret[1] = RegExp.$1 ? -1 : 1;
  739. }
  740. return ret;
  741. },
  742. hasSortBy() {
  743. // if use doesn't have dragHandle, then we can let user to choose sort list by different order
  744. return !this.hasShowDesktopDragHandles();
  745. },
  746. getListSortBy() {
  747. return this._getListSortBy()[0];
  748. },
  749. getListSortTypes() {
  750. return allowedSortValues;
  751. },
  752. getListSortByDirection() {
  753. return this._getListSortBy()[1];
  754. },
  755. getListWidths() {
  756. const { listWidths = {} } = this.profile || {};
  757. return listWidths;
  758. },
  759. getListWidth(boardId, listId) {
  760. const listWidths = this.getListWidths();
  761. if (listWidths[boardId] && listWidths[boardId][listId]) {
  762. return listWidths[boardId][listId];
  763. } else {
  764. return 270; //TODO(mark-i-m): default?
  765. }
  766. },
  767. getSwimlaneHeights() {
  768. const { swimlaneHeights = {} } = this.profile || {};
  769. return swimlaneHeights;
  770. },
  771. getSwimlaneHeight(boardId, listId) {
  772. const swimlaneHeights = this.getSwimlaneHeights();
  773. if (swimlaneHeights[boardId] && swimlaneHeights[boardId][listId]) {
  774. return swimlaneHeights[boardId][listId];
  775. } else {
  776. return 270; //TODO(mark-i-m): default?
  777. }
  778. },
  779. /** returns all confirmed move and copy dialog field values
  780. * <li> the board, swimlane and list id is stored for each board
  781. */
  782. getMoveAndCopyDialogOptions() {
  783. let _ret = {};
  784. if (this.profile && this.profile.moveAndCopyDialog) {
  785. _ret = this.profile.moveAndCopyDialog;
  786. }
  787. return _ret;
  788. },
  789. /** returns all confirmed move checklist dialog field values
  790. * <li> the board, swimlane, list and card id is stored for each board
  791. */
  792. getMoveChecklistDialogOptions() {
  793. let _ret = {};
  794. if (this.profile && this.profile.moveChecklistDialog) {
  795. _ret = this.profile.moveChecklistDialog;
  796. }
  797. return _ret;
  798. },
  799. /** returns all confirmed copy checklist dialog field values
  800. * <li> the board, swimlane, list and card id is stored for each board
  801. */
  802. getCopyChecklistDialogOptions() {
  803. let _ret = {};
  804. if (this.profile && this.profile.copyChecklistDialog) {
  805. _ret = this.profile.copyChecklistDialog;
  806. }
  807. return _ret;
  808. },
  809. hasTag(tag) {
  810. const { tags = [] } = this.profile || {};
  811. return _.contains(tags, tag);
  812. },
  813. hasNotification(activityId) {
  814. const { notifications = [] } = this.profile || {};
  815. return _.contains(notifications, activityId);
  816. },
  817. notifications() {
  818. const { notifications = [] } = this.profile || {};
  819. for (const index in notifications) {
  820. if (!notifications.hasOwnProperty(index)) continue;
  821. const notification = notifications[index];
  822. // this preserves their db sort order for editing
  823. notification.dbIndex = index;
  824. notification.activity = Activities.findOne(notification.activity);
  825. }
  826. // this sorts them newest to oldest to match Trello's behavior
  827. notifications.reverse();
  828. return notifications;
  829. },
  830. hasShowDesktopDragHandles() {
  831. const profile = this.profile || {};
  832. return profile.showDesktopDragHandles || false;
  833. },
  834. hasHideCheckedItems() {
  835. const profile = this.profile || {};
  836. return profile.hideCheckedItems || false;
  837. },
  838. hasHiddenSystemMessages() {
  839. const profile = this.profile || {};
  840. return profile.hiddenSystemMessages || false;
  841. },
  842. hasCustomFieldsGrid() {
  843. const profile = this.profile || {};
  844. return profile.customFieldsGrid || false;
  845. },
  846. hasCardMaximized() {
  847. const profile = this.profile || {};
  848. return profile.cardMaximized || false;
  849. },
  850. hasHiddenMinicardLabelText() {
  851. const profile = this.profile || {};
  852. return profile.hiddenMinicardLabelText || false;
  853. },
  854. hasRescuedCardDescription() {
  855. const profile = this.profile || {};
  856. return profile.rescueCardDescription || false;
  857. },
  858. getEmailBuffer() {
  859. const { emailBuffer = [] } = this.profile || {};
  860. return emailBuffer;
  861. },
  862. getInitials() {
  863. const profile = this.profile || {};
  864. if (profile.initials) return profile.initials;
  865. else if (profile.fullname) {
  866. return profile.fullname
  867. .split(/\s+/)
  868. .reduce((memo, word) => {
  869. return memo + word[0];
  870. }, '')
  871. .toUpperCase();
  872. } else {
  873. return this.username[0].toUpperCase();
  874. }
  875. },
  876. getLimitToShowCardsCount() {
  877. const profile = this.profile || {};
  878. return profile.showCardsCountAt;
  879. },
  880. getName() {
  881. const profile = this.profile || {};
  882. return profile.fullname || this.username;
  883. },
  884. getLanguage() {
  885. const profile = this.profile || {};
  886. return profile.language || 'en';
  887. },
  888. getStartDayOfWeek() {
  889. const profile = this.profile || {};
  890. if (typeof profile.startDayOfWeek === 'undefined') {
  891. // default is 'Monday' (1)
  892. return 1;
  893. }
  894. return profile.startDayOfWeek;
  895. },
  896. getTemplatesBoardId() {
  897. return (this.profile || {}).templatesBoardId;
  898. },
  899. getTemplatesBoardSlug() {
  900. //return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  901. return 'templates';
  902. },
  903. remove() {
  904. User.remove({
  905. _id: this._id,
  906. });
  907. },
  908. });
  909. Users.mutations({
  910. /** set the confirmed board id/swimlane id/list id of a board
  911. * @param boardId the current board id
  912. * @param options an object with the confirmed field values
  913. */
  914. setMoveAndCopyDialogOption(boardId, options) {
  915. let currentOptions = this.getMoveAndCopyDialogOptions();
  916. currentOptions[boardId] = options;
  917. return {
  918. $set: {
  919. 'profile.moveAndCopyDialog': currentOptions,
  920. },
  921. };
  922. },
  923. /** set the confirmed board id/swimlane id/list id/card id of a board (move checklist)
  924. * @param boardId the current board id
  925. * @param options an object with the confirmed field values
  926. */
  927. setMoveChecklistDialogOption(boardId, options) {
  928. let currentOptions = this.getMoveChecklistDialogOptions();
  929. currentOptions[boardId] = options;
  930. return {
  931. $set: {
  932. 'profile.moveChecklistDialog': currentOptions,
  933. },
  934. };
  935. },
  936. /** set the confirmed board id/swimlane id/list id/card id of a board (copy checklist)
  937. * @param boardId the current board id
  938. * @param options an object with the confirmed field values
  939. */
  940. setCopyChecklistDialogOption(boardId, options) {
  941. let currentOptions = this.getCopyChecklistDialogOptions();
  942. currentOptions[boardId] = options;
  943. return {
  944. $set: {
  945. 'profile.copyChecklistDialog': currentOptions,
  946. },
  947. };
  948. },
  949. toggleBoardStar(boardId) {
  950. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  951. return {
  952. [queryKind]: {
  953. 'profile.starredBoards': boardId,
  954. },
  955. };
  956. },
  957. addInvite(boardId) {
  958. return {
  959. $addToSet: {
  960. 'profile.invitedBoards': boardId,
  961. },
  962. };
  963. },
  964. removeInvite(boardId) {
  965. return {
  966. $pull: {
  967. 'profile.invitedBoards': boardId,
  968. },
  969. };
  970. },
  971. addTag(tag) {
  972. return {
  973. $addToSet: {
  974. 'profile.tags': tag,
  975. },
  976. };
  977. },
  978. removeTag(tag) {
  979. return {
  980. $pull: {
  981. 'profile.tags': tag,
  982. },
  983. };
  984. },
  985. toggleTag(tag) {
  986. if (this.hasTag(tag)) this.removeTag(tag);
  987. else this.addTag(tag);
  988. },
  989. setListSortBy(value) {
  990. return {
  991. $set: {
  992. 'profile.listSortBy': value,
  993. },
  994. };
  995. },
  996. setName(value) {
  997. return {
  998. $set: {
  999. 'profile.fullname': value,
  1000. },
  1001. };
  1002. },
  1003. toggleDesktopHandles(value = false) {
  1004. return {
  1005. $set: {
  1006. 'profile.showDesktopDragHandles': !value,
  1007. },
  1008. };
  1009. },
  1010. toggleHideCheckedItems() {
  1011. const value = this.hasHideCheckedItems();
  1012. return {
  1013. $set: {
  1014. 'profile.hideCheckedItems': !value,
  1015. },
  1016. };
  1017. },
  1018. toggleSystem(value = false) {
  1019. return {
  1020. $set: {
  1021. 'profile.hiddenSystemMessages': !value,
  1022. },
  1023. };
  1024. },
  1025. toggleFieldsGrid(value = false) {
  1026. return {
  1027. $set: {
  1028. 'profile.customFieldsGrid': !value,
  1029. },
  1030. };
  1031. },
  1032. toggleCardMaximized(value = false) {
  1033. return {
  1034. $set: {
  1035. 'profile.cardMaximized': !value,
  1036. },
  1037. };
  1038. },
  1039. toggleLabelText(value = false) {
  1040. return {
  1041. $set: {
  1042. 'profile.hiddenMinicardLabelText': !value,
  1043. },
  1044. };
  1045. },
  1046. toggleRescueCardDescription(value = false) {
  1047. return {
  1048. $set: {
  1049. 'profile.rescueCardDescription': !value,
  1050. },
  1051. };
  1052. },
  1053. addNotification(activityId) {
  1054. return {
  1055. $addToSet: {
  1056. 'profile.notifications': {
  1057. activity: activityId,
  1058. },
  1059. },
  1060. };
  1061. },
  1062. removeNotification(activityId) {
  1063. return {
  1064. $pull: {
  1065. 'profile.notifications': {
  1066. activity: activityId,
  1067. },
  1068. },
  1069. };
  1070. },
  1071. addEmailBuffer(text) {
  1072. return {
  1073. $addToSet: {
  1074. 'profile.emailBuffer': text,
  1075. },
  1076. };
  1077. },
  1078. clearEmailBuffer() {
  1079. return {
  1080. $set: {
  1081. 'profile.emailBuffer': [],
  1082. },
  1083. };
  1084. },
  1085. setAvatarUrl(avatarUrl) {
  1086. return {
  1087. $set: {
  1088. 'profile.avatarUrl': avatarUrl,
  1089. },
  1090. };
  1091. },
  1092. setShowCardsCountAt(limit) {
  1093. return {
  1094. $set: {
  1095. 'profile.showCardsCountAt': limit,
  1096. },
  1097. };
  1098. },
  1099. setStartDayOfWeek(startDay) {
  1100. return {
  1101. $set: {
  1102. 'profile.startDayOfWeek': startDay,
  1103. },
  1104. };
  1105. },
  1106. setBoardView(view) {
  1107. return {
  1108. $set: {
  1109. 'profile.boardView': view,
  1110. },
  1111. };
  1112. },
  1113. setListWidth(boardId, listId, width) {
  1114. let currentWidths = this.getListWidths();
  1115. if (!currentWidths[boardId]) {
  1116. currentWidths[boardId] = {};
  1117. }
  1118. currentWidths[boardId][listId] = width;
  1119. return {
  1120. $set: {
  1121. 'profile.listWidths': currentWidths,
  1122. },
  1123. };
  1124. },
  1125. setSwimlaneHeight(boardId, swimlaneId, height) {
  1126. let currentHeights = this.getSwimlaneHeights();
  1127. if (!currentHeights[boardId]) {
  1128. currentHeights[boardId] = {};
  1129. }
  1130. currentHeights[boardId][swimlaneId] = height;
  1131. return {
  1132. $set: {
  1133. 'profile.swimlaneHeights': currentHeights,
  1134. },
  1135. };
  1136. },
  1137. });
  1138. Meteor.methods({
  1139. setListSortBy(value) {
  1140. check(value, String);
  1141. Meteor.user().setListSortBy(value);
  1142. },
  1143. toggleDesktopDragHandles() {
  1144. const user = Meteor.user();
  1145. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  1146. },
  1147. toggleHideCheckedItems() {
  1148. const user = Meteor.user();
  1149. user.toggleHideCheckedItems();
  1150. },
  1151. toggleSystemMessages() {
  1152. const user = Meteor.user();
  1153. user.toggleSystem(user.hasHiddenSystemMessages());
  1154. },
  1155. toggleCustomFieldsGrid() {
  1156. const user = Meteor.user();
  1157. user.toggleFieldsGrid(user.hasCustomFieldsGrid());
  1158. },
  1159. toggleCardMaximized() {
  1160. const user = Meteor.user();
  1161. user.toggleCardMaximized(user.hasCardMaximized());
  1162. },
  1163. toggleMinicardLabelText() {
  1164. const user = Meteor.user();
  1165. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  1166. },
  1167. toggleRescueCardDescription() {
  1168. const user = Meteor.user();
  1169. user.toggleRescueCardDescription(user.hasRescuedCardDescription());
  1170. },
  1171. changeLimitToShowCardsCount(limit) {
  1172. check(limit, Number);
  1173. Meteor.user().setShowCardsCountAt(limit);
  1174. },
  1175. changeStartDayOfWeek(startDay) {
  1176. check(startDay, Number);
  1177. Meteor.user().setStartDayOfWeek(startDay);
  1178. },
  1179. applyListWidth(boardId, listId, width) {
  1180. check(boardId, String);
  1181. check(listId, String);
  1182. check(width, Number);
  1183. const user = Meteor.user();
  1184. user.setListWidth(boardId, listId, width);
  1185. },
  1186. applySwimlaneHeight(boardId, swimlaneId, height) {
  1187. check(boardId, String);
  1188. check(swimlaneId, String);
  1189. check(height, Number);
  1190. const user = Meteor.user();
  1191. user.setSwimlaneHeight(boardId, swimlaneId, height);
  1192. },
  1193. });
  1194. if (Meteor.isServer) {
  1195. Meteor.methods({
  1196. setAllUsersHideSystemMessages() {
  1197. if (Meteor.user() && Meteor.user().isAdmin) {
  1198. // If setting is missing, add it
  1199. Users.update(
  1200. {
  1201. 'profile.hiddenSystemMessages': {
  1202. $exists: false,
  1203. },
  1204. },
  1205. {
  1206. $set: {
  1207. 'profile.hiddenSystemMessages': true,
  1208. },
  1209. },
  1210. {
  1211. multi: true,
  1212. },
  1213. );
  1214. // If setting is false, set it to true
  1215. Users.update(
  1216. {
  1217. 'profile.hiddenSystemMessages': false,
  1218. },
  1219. {
  1220. $set: {
  1221. 'profile.hiddenSystemMessages': true,
  1222. },
  1223. },
  1224. {
  1225. multi: true,
  1226. },
  1227. );
  1228. return true;
  1229. } else {
  1230. return false;
  1231. }
  1232. },
  1233. setCreateUser(
  1234. fullname,
  1235. username,
  1236. initials,
  1237. password,
  1238. isAdmin,
  1239. isActive,
  1240. email,
  1241. importUsernames,
  1242. userOrgsArray,
  1243. userTeamsArray,
  1244. ) {
  1245. check(fullname, String);
  1246. check(username, String);
  1247. check(initials, String);
  1248. check(password, String);
  1249. check(isAdmin, String);
  1250. check(isActive, String);
  1251. check(email, String);
  1252. check(importUsernames, Array);
  1253. check(userOrgsArray, Array);
  1254. check(userTeamsArray, Array);
  1255. if (Meteor.user() && Meteor.user().isAdmin) {
  1256. const nUsersWithUsername = Users.find({
  1257. username,
  1258. }).count();
  1259. const nUsersWithEmail = Users.find({
  1260. email,
  1261. }).count();
  1262. if (nUsersWithUsername > 0) {
  1263. throw new Meteor.Error('username-already-taken');
  1264. } else if (nUsersWithEmail > 0) {
  1265. throw new Meteor.Error('email-already-taken');
  1266. } else {
  1267. Accounts.createUser({
  1268. username,
  1269. password,
  1270. isAdmin,
  1271. isActive,
  1272. email: email.toLowerCase(),
  1273. from: 'admin',
  1274. });
  1275. const user =
  1276. Users.findOne(username) ||
  1277. Users.findOne({
  1278. username,
  1279. });
  1280. if (user) {
  1281. Users.update(user._id, {
  1282. $set: {
  1283. 'profile.fullname': fullname,
  1284. importUsernames,
  1285. 'profile.initials': initials,
  1286. orgs: userOrgsArray,
  1287. teams: userTeamsArray,
  1288. },
  1289. });
  1290. }
  1291. }
  1292. }
  1293. },
  1294. setUsername(username, userId) {
  1295. check(username, String);
  1296. check(userId, String);
  1297. if (Meteor.user() && Meteor.user().isAdmin) {
  1298. const nUsersWithUsername = Users.find({
  1299. username,
  1300. }).count();
  1301. if (nUsersWithUsername > 0) {
  1302. throw new Meteor.Error('username-already-taken');
  1303. } else {
  1304. Users.update(userId, {
  1305. $set: {
  1306. username,
  1307. },
  1308. });
  1309. }
  1310. }
  1311. },
  1312. setEmail(email, userId) {
  1313. check(email, String);
  1314. check(username, String);
  1315. if (Meteor.user() && Meteor.user().isAdmin) {
  1316. if (Array.isArray(email)) {
  1317. email = email.shift();
  1318. }
  1319. const existingUser = Users.findOne(
  1320. {
  1321. 'emails.address': email,
  1322. },
  1323. {
  1324. fields: {
  1325. _id: 1,
  1326. },
  1327. },
  1328. );
  1329. if (existingUser) {
  1330. throw new Meteor.Error('email-already-taken');
  1331. } else {
  1332. Users.update(userId, {
  1333. $set: {
  1334. emails: [
  1335. {
  1336. address: email,
  1337. verified: false,
  1338. },
  1339. ],
  1340. },
  1341. });
  1342. }
  1343. }
  1344. },
  1345. setUsernameAndEmail(username, email, userId) {
  1346. check(username, String);
  1347. check(email, String);
  1348. check(userId, String);
  1349. if (Meteor.user() && Meteor.user().isAdmin) {
  1350. if (Array.isArray(email)) {
  1351. email = email.shift();
  1352. }
  1353. Meteor.call('setUsername', username, userId);
  1354. Meteor.call('setEmail', email, userId);
  1355. }
  1356. },
  1357. setPassword(newPassword, userId) {
  1358. check(userId, String);
  1359. check(newPassword, String);
  1360. if (Meteor.user() && Meteor.user().isAdmin) {
  1361. if (Meteor.user().isAdmin) {
  1362. Accounts.setPassword(userId, newPassword);
  1363. }
  1364. }
  1365. },
  1366. setEmailVerified(email, verified, userId) {
  1367. check(email, String);
  1368. check(verified, Boolean);
  1369. check(userId, String);
  1370. if (Meteor.user() && Meteor.user().isAdmin) {
  1371. Users.update(userId, {
  1372. $set: {
  1373. emails: [
  1374. {
  1375. address: email,
  1376. verified,
  1377. },
  1378. ],
  1379. },
  1380. });
  1381. }
  1382. },
  1383. setInitials(initials, userId) {
  1384. check(initials, String);
  1385. check(userId, String);
  1386. if (Meteor.user() && Meteor.user().isAdmin) {
  1387. Users.update(userId, {
  1388. $set: {
  1389. 'profile.initials': initials,
  1390. },
  1391. });
  1392. }
  1393. },
  1394. // we accept userId, username, email
  1395. inviteUserToBoard(username, boardId) {
  1396. check(username, String);
  1397. check(boardId, String);
  1398. const inviter = Meteor.user();
  1399. const board = Boards.findOne(boardId);
  1400. const allowInvite =
  1401. inviter &&
  1402. board &&
  1403. board.members &&
  1404. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  1405. _.where(board.members, {
  1406. userId: inviter._id,
  1407. })[0].isActive;
  1408. // GitHub issue 2060
  1409. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  1410. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  1411. this.unblock();
  1412. const posAt = username.indexOf('@');
  1413. let user = null;
  1414. if (posAt >= 0) {
  1415. user = Users.findOne({
  1416. emails: {
  1417. $elemMatch: {
  1418. address: username,
  1419. },
  1420. },
  1421. });
  1422. } else {
  1423. user =
  1424. Users.findOne(username) ||
  1425. Users.findOne({
  1426. username,
  1427. });
  1428. }
  1429. if (user) {
  1430. if (user._id === inviter._id)
  1431. throw new Meteor.Error('error-user-notAllowSelf');
  1432. } else {
  1433. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  1434. if (
  1435. Settings.findOne({
  1436. disableRegistration: true,
  1437. })
  1438. ) {
  1439. throw new Meteor.Error('error-user-notCreated');
  1440. }
  1441. // Set in lowercase email before creating account
  1442. const email = username.toLowerCase();
  1443. username = email.substring(0, posAt);
  1444. const newUserId = Accounts.createUser({
  1445. username,
  1446. email,
  1447. });
  1448. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  1449. // assume new user speak same language with inviter
  1450. if (inviter.profile && inviter.profile.language) {
  1451. Users.update(newUserId, {
  1452. $set: {
  1453. 'profile.language': inviter.profile.language,
  1454. },
  1455. });
  1456. }
  1457. Accounts.sendEnrollmentEmail(newUserId);
  1458. user = Users.findOne(newUserId);
  1459. }
  1460. board.addMember(user._id);
  1461. user.addInvite(boardId);
  1462. //Check if there is a subtasks board
  1463. if (board.subtasksDefaultBoardId) {
  1464. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  1465. //If there is, also add user to that board
  1466. if (subBoard) {
  1467. subBoard.addMember(user._id);
  1468. user.addInvite(subBoard._id);
  1469. }
  1470. }
  1471. try {
  1472. const fullName =
  1473. inviter.profile !== undefined &&
  1474. inviter.profile.fullname !== undefined
  1475. ? inviter.profile.fullname
  1476. : '';
  1477. const userFullName =
  1478. user.profile !== undefined && user.profile.fullname !== undefined
  1479. ? user.profile.fullname
  1480. : '';
  1481. const params = {
  1482. user:
  1483. userFullName != ''
  1484. ? userFullName + ' (' + user.username + ' )'
  1485. : user.username,
  1486. inviter:
  1487. fullName != ''
  1488. ? fullName + ' (' + inviter.username + ' )'
  1489. : inviter.username,
  1490. board: board.title,
  1491. url: board.absoluteUrl(),
  1492. };
  1493. const lang = user.getLanguage();
  1494. /*
  1495. if (process.env.MAIL_SERVICE !== '') {
  1496. let transporter = nodemailer.createTransport({
  1497. service: process.env.MAIL_SERVICE,
  1498. auth: {
  1499. user: process.env.MAIL_SERVICE_USER,
  1500. pass: process.env.MAIL_SERVICE_PASSWORD
  1501. },
  1502. })
  1503. let info = transporter.sendMail({
  1504. to: user.emails[0].address.toLowerCase(),
  1505. from: Accounts.emailTemplates.from,
  1506. subject: TAPi18n.__('email-invite-subject', params, lang),
  1507. text: TAPi18n.__('email-invite-text', params, lang),
  1508. })
  1509. } else {
  1510. Email.send({
  1511. to: user.emails[0].address.toLowerCase(),
  1512. from: Accounts.emailTemplates.from,
  1513. subject: TAPi18n.__('email-invite-subject', params, lang),
  1514. text: TAPi18n.__('email-invite-text', params, lang),
  1515. });
  1516. }
  1517. */
  1518. Email.send({
  1519. to: user.emails[0].address.toLowerCase(),
  1520. from: Accounts.emailTemplates.from,
  1521. subject: TAPi18n.__('email-invite-subject', params, lang),
  1522. text: TAPi18n.__('email-invite-text', params, lang),
  1523. });
  1524. } catch (e) {
  1525. throw new Meteor.Error('email-fail', e.message);
  1526. }
  1527. return {
  1528. username: user.username,
  1529. email: user.emails[0].address,
  1530. };
  1531. },
  1532. impersonate(userId) {
  1533. check(userId, String);
  1534. if (!Meteor.users.findOne(userId))
  1535. throw new Meteor.Error(404, 'User not found');
  1536. if (!Meteor.user().isAdmin)
  1537. throw new Meteor.Error(403, 'Permission denied');
  1538. ImpersonatedUsers.insert({
  1539. adminId: Meteor.user()._id,
  1540. userId: userId,
  1541. reason: 'clickedImpersonate',
  1542. });
  1543. this.setUserId(userId);
  1544. },
  1545. isImpersonated(userId) {
  1546. check(userId, String);
  1547. const isImpersonated = ImpersonatedUsers.findOne({
  1548. userId: userId,
  1549. });
  1550. return isImpersonated;
  1551. },
  1552. setUsersTeamsTeamDisplayName(teamId, teamDisplayName) {
  1553. check(teamId, String);
  1554. check(teamDisplayName, String);
  1555. if (Meteor.user() && Meteor.user().isAdmin) {
  1556. Users.find({
  1557. teams: {
  1558. $elemMatch: { teamId: teamId },
  1559. },
  1560. }).forEach((user) => {
  1561. Users.update(
  1562. {
  1563. _id: user._id,
  1564. teams: {
  1565. $elemMatch: { teamId: teamId },
  1566. },
  1567. },
  1568. {
  1569. $set: {
  1570. 'teams.$.teamDisplayName': teamDisplayName,
  1571. },
  1572. },
  1573. );
  1574. });
  1575. }
  1576. },
  1577. setUsersOrgsOrgDisplayName(orgId, orgDisplayName) {
  1578. check(orgId, String);
  1579. check(orgDisplayName, String);
  1580. if (Meteor.user() && Meteor.user().isAdmin) {
  1581. Users.find({
  1582. orgs: {
  1583. $elemMatch: { orgId: orgId },
  1584. },
  1585. }).forEach((user) => {
  1586. Users.update(
  1587. {
  1588. _id: user._id,
  1589. orgs: {
  1590. $elemMatch: { orgId: orgId },
  1591. },
  1592. },
  1593. {
  1594. $set: {
  1595. 'orgs.$.orgDisplayName': orgDisplayName,
  1596. },
  1597. },
  1598. );
  1599. });
  1600. }
  1601. },
  1602. });
  1603. Accounts.onCreateUser((options, user) => {
  1604. const userCount = Users.find().count();
  1605. if (userCount === 0) {
  1606. user.isAdmin = true;
  1607. }
  1608. if (user.services.oidc) {
  1609. let email = user.services.oidc.email;
  1610. if (Array.isArray(email)) {
  1611. email = email.shift();
  1612. }
  1613. email = email.toLowerCase();
  1614. user.username = user.services.oidc.username;
  1615. user.emails = [
  1616. {
  1617. address: email,
  1618. verified: true,
  1619. },
  1620. ];
  1621. const initials = user.services.oidc.fullname
  1622. .split(/\s+/)
  1623. .reduce((memo, word) => {
  1624. return memo + word[0];
  1625. }, '')
  1626. .toUpperCase();
  1627. user.profile = {
  1628. initials,
  1629. fullname: user.services.oidc.fullname,
  1630. boardView: 'board-view-swimlanes',
  1631. };
  1632. user.authenticationMethod = 'oauth2';
  1633. // see if any existing user has this email address or username, otherwise create new
  1634. const existingUser = Meteor.users.findOne({
  1635. $or: [
  1636. {
  1637. 'emails.address': email,
  1638. },
  1639. {
  1640. username: user.username,
  1641. },
  1642. ],
  1643. });
  1644. if (!existingUser) return user;
  1645. // copy across new service info
  1646. const service = _.keys(user.services)[0];
  1647. existingUser.services[service] = user.services[service];
  1648. existingUser.emails = user.emails;
  1649. existingUser.username = user.username;
  1650. existingUser.profile = user.profile;
  1651. existingUser.authenticationMethod = user.authenticationMethod;
  1652. Meteor.users.remove({
  1653. _id: user._id,
  1654. });
  1655. Meteor.users.remove({
  1656. _id: existingUser._id,
  1657. }); // is going to be created again
  1658. return existingUser;
  1659. }
  1660. if (options.from === 'admin') {
  1661. user.createdThroughApi = true;
  1662. return user;
  1663. }
  1664. const disableRegistration = Settings.findOne().disableRegistration;
  1665. // If this is the first Authentication by the ldap and self registration disabled
  1666. if (disableRegistration && options && options.ldap) {
  1667. user.authenticationMethod = 'ldap';
  1668. return user;
  1669. }
  1670. // If self registration enabled
  1671. if (!disableRegistration) {
  1672. return user;
  1673. }
  1674. if (!options || !options.profile) {
  1675. throw new Meteor.Error(
  1676. 'error-invitation-code-blank',
  1677. 'The invitation code is required',
  1678. );
  1679. }
  1680. const invitationCode = InvitationCodes.findOne({
  1681. code: options.profile.invitationcode,
  1682. email: options.email,
  1683. valid: true,
  1684. });
  1685. if (!invitationCode) {
  1686. throw new Meteor.Error(
  1687. 'error-invitation-code-not-exist',
  1688. // eslint-disable-next-line quotes
  1689. "The invitation code doesn't exist",
  1690. );
  1691. } else {
  1692. user.profile = {
  1693. icode: options.profile.invitationcode,
  1694. };
  1695. user.profile.boardView = 'board-view-swimlanes';
  1696. // Deletes the invitation code after the user was created successfully.
  1697. setTimeout(
  1698. Meteor.bindEnvironment(() => {
  1699. InvitationCodes.remove({
  1700. _id: invitationCode._id,
  1701. });
  1702. }),
  1703. 200,
  1704. );
  1705. return user;
  1706. }
  1707. });
  1708. }
  1709. const addCronJob = _.debounce(
  1710. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  1711. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  1712. const envRemoveAge =
  1713. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  1714. // default notifications will be removed 2 days after they are read
  1715. const defaultRemoveAge = 2;
  1716. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  1717. SyncedCron.add({
  1718. name: 'notification_cleanup',
  1719. schedule: (parser) => parser.text('every 1 days'),
  1720. job: () => {
  1721. for (const user of Users.find()) {
  1722. if (!user.profile || !user.profile.notifications) continue;
  1723. for (const notification of user.profile.notifications) {
  1724. if (notification.read) {
  1725. const removeDate = new Date(notification.read);
  1726. removeDate.setDate(removeDate.getDate() + removeAge);
  1727. if (removeDate <= new Date()) {
  1728. user.removeNotification(notification.activity);
  1729. }
  1730. }
  1731. }
  1732. }
  1733. },
  1734. });
  1735. SyncedCron.start();
  1736. }),
  1737. 500,
  1738. );
  1739. if (Meteor.isServer) {
  1740. // Let mongoDB ensure username unicity
  1741. Meteor.startup(() => {
  1742. allowedSortValues.forEach((value) => {
  1743. Lists._collection.createIndex(value);
  1744. });
  1745. Users._collection.createIndex({
  1746. modifiedAt: -1,
  1747. });
  1748. /* Commented out extra index because of IndexOptionsConflict.
  1749. Users._collection.createIndex(
  1750. {
  1751. username: 1,
  1752. },
  1753. {
  1754. unique: true,
  1755. },
  1756. );
  1757. */
  1758. Meteor.defer(() => {
  1759. addCronJob();
  1760. });
  1761. });
  1762. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  1763. // if admin is removed, board is removed.
  1764. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  1765. // to use that board, and not have board deleted.
  1766. // Someone can be later changed to be admin of board, by making change to database.
  1767. // TODO: Add UI for changing someone as board admin.
  1768. //Users.before.remove((userId, doc) => {
  1769. // Boards
  1770. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  1771. // .forEach((board) => {
  1772. // // If only one admin for the board
  1773. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  1774. // Boards.remove(board._id);
  1775. // }
  1776. // });
  1777. //});
  1778. // Each board document contains the de-normalized number of users that have
  1779. // starred it. If the user star or unstar a board, we need to update this
  1780. // counter.
  1781. // We need to run this code on the server only, otherwise the incrementation
  1782. // will be done twice.
  1783. Users.after.update(function (userId, user, fieldNames) {
  1784. // The `starredBoards` list is hosted on the `profile` field. If this
  1785. // field hasn't been modificated we don't need to run this hook.
  1786. if (!_.contains(fieldNames, 'profile')) return;
  1787. // To calculate a diff of board starred ids, we get both the previous
  1788. // and the newly board ids list
  1789. function getStarredBoardsIds(doc) {
  1790. return doc.profile && doc.profile.starredBoards;
  1791. }
  1792. const oldIds = getStarredBoardsIds(this.previous);
  1793. const newIds = getStarredBoardsIds(user);
  1794. // The _.difference(a, b) method returns the values from a that are not in
  1795. // b. We use it to find deleted and newly inserted ids by using it in one
  1796. // direction and then in the other.
  1797. function incrementBoards(boardsIds, inc) {
  1798. boardsIds.forEach((boardId) => {
  1799. Boards.update(boardId, {
  1800. $inc: {
  1801. stars: inc,
  1802. },
  1803. });
  1804. });
  1805. }
  1806. incrementBoards(_.difference(oldIds, newIds), -1);
  1807. incrementBoards(_.difference(newIds, oldIds), +1);
  1808. });
  1809. // Override getUserId so that we can TODO get the current userId
  1810. const fakeUserId = new Meteor.EnvironmentVariable();
  1811. const getUserId = CollectionHooks.getUserId;
  1812. CollectionHooks.getUserId = () => {
  1813. return fakeUserId.get() || getUserId();
  1814. };
  1815. if (!isSandstorm) {
  1816. Users.after.insert((userId, doc) => {
  1817. const fakeUser = {
  1818. extendAutoValueContext: {
  1819. userId: doc._id,
  1820. },
  1821. };
  1822. fakeUserId.withValue(doc._id, () => {
  1823. /*
  1824. // Insert the Welcome Board
  1825. Boards.insert({
  1826. title: TAPi18n.__('welcome-board'),
  1827. permission: 'private',
  1828. }, fakeUser, (err, boardId) => {
  1829. Swimlanes.insert({
  1830. title: TAPi18n.__('welcome-swimlane'),
  1831. boardId,
  1832. sort: 1,
  1833. }, fakeUser);
  1834. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1835. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1836. });
  1837. });
  1838. */
  1839. // Insert Template Container
  1840. const Future = require('fibers/future');
  1841. const future1 = new Future();
  1842. const future2 = new Future();
  1843. const future3 = new Future();
  1844. Boards.insert(
  1845. {
  1846. title: TAPi18n.__('templates'),
  1847. permission: 'private',
  1848. type: 'template-container',
  1849. },
  1850. fakeUser,
  1851. (err, boardId) => {
  1852. // Insert the reference to our templates board
  1853. Users.update(fakeUserId.get(), {
  1854. $set: {
  1855. 'profile.templatesBoardId': boardId,
  1856. },
  1857. });
  1858. // Insert the card templates swimlane
  1859. Swimlanes.insert(
  1860. {
  1861. title: TAPi18n.__('card-templates-swimlane'),
  1862. boardId,
  1863. sort: 1,
  1864. type: 'template-container',
  1865. },
  1866. fakeUser,
  1867. (err, swimlaneId) => {
  1868. // Insert the reference to out card templates swimlane
  1869. Users.update(fakeUserId.get(), {
  1870. $set: {
  1871. 'profile.cardTemplatesSwimlaneId': swimlaneId,
  1872. },
  1873. });
  1874. future1.return();
  1875. },
  1876. );
  1877. // Insert the list templates swimlane
  1878. Swimlanes.insert(
  1879. {
  1880. title: TAPi18n.__('list-templates-swimlane'),
  1881. boardId,
  1882. sort: 2,
  1883. type: 'template-container',
  1884. },
  1885. fakeUser,
  1886. (err, swimlaneId) => {
  1887. // Insert the reference to out list templates swimlane
  1888. Users.update(fakeUserId.get(), {
  1889. $set: {
  1890. 'profile.listTemplatesSwimlaneId': swimlaneId,
  1891. },
  1892. });
  1893. future2.return();
  1894. },
  1895. );
  1896. // Insert the board templates swimlane
  1897. Swimlanes.insert(
  1898. {
  1899. title: TAPi18n.__('board-templates-swimlane'),
  1900. boardId,
  1901. sort: 3,
  1902. type: 'template-container',
  1903. },
  1904. fakeUser,
  1905. (err, swimlaneId) => {
  1906. // Insert the reference to out board templates swimlane
  1907. Users.update(fakeUserId.get(), {
  1908. $set: {
  1909. 'profile.boardTemplatesSwimlaneId': swimlaneId,
  1910. },
  1911. });
  1912. future3.return();
  1913. },
  1914. );
  1915. },
  1916. );
  1917. // HACK
  1918. future1.wait();
  1919. future2.wait();
  1920. future3.wait();
  1921. // End of Insert Template Container
  1922. });
  1923. });
  1924. }
  1925. Users.after.insert((userId, doc) => {
  1926. // HACK
  1927. doc = Users.findOne({
  1928. _id: doc._id,
  1929. });
  1930. if (doc.createdThroughApi) {
  1931. // The admin user should be able to create a user despite disabling registration because
  1932. // it is two different things (registration and creation).
  1933. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1934. // the disableRegistration check.
  1935. // Issue : https://github.com/wekan/wekan/issues/1232
  1936. // PR : https://github.com/wekan/wekan/pull/1251
  1937. Users.update(doc._id, {
  1938. $set: {
  1939. createdThroughApi: '',
  1940. },
  1941. });
  1942. return;
  1943. }
  1944. //invite user to corresponding boards
  1945. const disableRegistration = Settings.findOne().disableRegistration;
  1946. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1947. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1948. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1949. let invitationCode = null;
  1950. if (doc.authenticationMethod.toLowerCase() == 'oauth2') {
  1951. // OIDC authentication mode
  1952. invitationCode = InvitationCodes.findOne({
  1953. email: doc.emails[0].address.toLowerCase(),
  1954. valid: true,
  1955. });
  1956. } else {
  1957. invitationCode = InvitationCodes.findOne({
  1958. code: doc.profile.icode,
  1959. valid: true,
  1960. });
  1961. }
  1962. if (!invitationCode) {
  1963. throw new Meteor.Error('error-invitation-code-not-exist');
  1964. } else {
  1965. invitationCode.boardsToBeInvited.forEach((boardId) => {
  1966. const board = Boards.findOne(boardId);
  1967. board.addMember(doc._id);
  1968. });
  1969. if (!doc.profile) {
  1970. doc.profile = {};
  1971. }
  1972. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1973. Users.update(doc._id, {
  1974. $set: {
  1975. profile: doc.profile,
  1976. },
  1977. });
  1978. InvitationCodes.update(invitationCode._id, {
  1979. $set: {
  1980. valid: false,
  1981. },
  1982. });
  1983. }
  1984. }
  1985. });
  1986. }
  1987. // USERS REST API
  1988. if (Meteor.isServer) {
  1989. // Middleware which checks that API is enabled.
  1990. JsonRoutes.Middleware.use(function (req, res, next) {
  1991. const api = req.url.startsWith('/api');
  1992. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1993. return next();
  1994. } else {
  1995. res.writeHead(301, {
  1996. Location: '/',
  1997. });
  1998. return res.end();
  1999. }
  2000. });
  2001. /**
  2002. * @operation get_current_user
  2003. *
  2004. * @summary returns the current user
  2005. * @return_type Users
  2006. */
  2007. JsonRoutes.add('GET', '/api/user', function (req, res) {
  2008. try {
  2009. Authentication.checkLoggedIn(req.userId);
  2010. const data = Meteor.users.findOne({
  2011. _id: req.userId,
  2012. });
  2013. delete data.services;
  2014. // get all boards where the user is member of
  2015. let boards = Boards.find(
  2016. {
  2017. type: 'board',
  2018. 'members.userId': req.userId,
  2019. },
  2020. {
  2021. fields: {
  2022. _id: 1,
  2023. members: 1,
  2024. },
  2025. },
  2026. );
  2027. boards = boards.map((b) => {
  2028. const u = b.members.find((m) => m.userId === req.userId);
  2029. delete u.userId;
  2030. u.boardId = b._id;
  2031. return u;
  2032. });
  2033. data.boards = boards;
  2034. JsonRoutes.sendResult(res, {
  2035. code: 200,
  2036. data,
  2037. });
  2038. } catch (error) {
  2039. JsonRoutes.sendResult(res, {
  2040. code: 200,
  2041. data: error,
  2042. });
  2043. }
  2044. });
  2045. /**
  2046. * @operation get_all_users
  2047. *
  2048. * @summary return all the users
  2049. *
  2050. * @description Only the admin user (the first user) can call the REST API.
  2051. * @return_type [{ _id: string,
  2052. * username: string}]
  2053. */
  2054. JsonRoutes.add('GET', '/api/users', function (req, res) {
  2055. try {
  2056. Authentication.checkUserId(req.userId);
  2057. JsonRoutes.sendResult(res, {
  2058. code: 200,
  2059. data: Meteor.users.find({}).map(function (doc) {
  2060. return {
  2061. _id: doc._id,
  2062. username: doc.username,
  2063. };
  2064. }),
  2065. });
  2066. } catch (error) {
  2067. JsonRoutes.sendResult(res, {
  2068. code: 200,
  2069. data: error,
  2070. });
  2071. }
  2072. });
  2073. /**
  2074. * @operation get_user
  2075. *
  2076. * @summary get a given user
  2077. *
  2078. * @description Only the admin user (the first user) can call the REST API.
  2079. *
  2080. * @param {string} userId the user ID or username
  2081. * @return_type Users
  2082. */
  2083. JsonRoutes.add('GET', '/api/users/:userId', function (req, res) {
  2084. try {
  2085. Authentication.checkUserId(req.userId);
  2086. let id = req.params.userId;
  2087. let user = Meteor.users.findOne({
  2088. _id: id,
  2089. });
  2090. if (!user) {
  2091. user = Meteor.users.findOne({
  2092. username: id,
  2093. });
  2094. id = user._id;
  2095. }
  2096. // get all boards where the user is member of
  2097. let boards = Boards.find(
  2098. {
  2099. type: 'board',
  2100. 'members.userId': id,
  2101. },
  2102. {
  2103. fields: {
  2104. _id: 1,
  2105. members: 1,
  2106. },
  2107. },
  2108. );
  2109. boards = boards.map((b) => {
  2110. const u = b.members.find((m) => m.userId === id);
  2111. delete u.userId;
  2112. u.boardId = b._id;
  2113. return u;
  2114. });
  2115. user.boards = boards;
  2116. JsonRoutes.sendResult(res, {
  2117. code: 200,
  2118. data: user,
  2119. });
  2120. } catch (error) {
  2121. JsonRoutes.sendResult(res, {
  2122. code: 200,
  2123. data: error,
  2124. });
  2125. }
  2126. });
  2127. /**
  2128. * @operation edit_user
  2129. *
  2130. * @summary edit a given user
  2131. *
  2132. * @description Only the admin user (the first user) can call the REST API.
  2133. *
  2134. * Possible values for *action*:
  2135. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  2136. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  2137. * - `enableLogin`: Enable a user
  2138. *
  2139. * @param {string} userId the user ID
  2140. * @param {string} action the action
  2141. * @return_type {_id: string,
  2142. * title: string}
  2143. */
  2144. JsonRoutes.add('PUT', '/api/users/:userId', function (req, res) {
  2145. try {
  2146. Authentication.checkUserId(req.userId);
  2147. const id = req.params.userId;
  2148. const action = req.body.action;
  2149. let data = Meteor.users.findOne({
  2150. _id: id,
  2151. });
  2152. if (data !== undefined) {
  2153. if (action === 'takeOwnership') {
  2154. data = Boards.find(
  2155. {
  2156. 'members.userId': id,
  2157. 'members.isAdmin': true,
  2158. },
  2159. {
  2160. sort: {
  2161. sort: 1 /* boards default sorting */,
  2162. },
  2163. },
  2164. ).map(function (board) {
  2165. if (board.hasMember(req.userId)) {
  2166. board.removeMember(req.userId);
  2167. }
  2168. board.changeOwnership(id, req.userId);
  2169. return {
  2170. _id: board._id,
  2171. title: board.title,
  2172. };
  2173. });
  2174. } else {
  2175. if (action === 'disableLogin' && id !== req.userId) {
  2176. Users.update(
  2177. {
  2178. _id: id,
  2179. },
  2180. {
  2181. $set: {
  2182. loginDisabled: true,
  2183. 'services.resume.loginTokens': '',
  2184. },
  2185. },
  2186. );
  2187. } else if (action === 'enableLogin') {
  2188. Users.update(
  2189. {
  2190. _id: id,
  2191. },
  2192. {
  2193. $set: {
  2194. loginDisabled: '',
  2195. },
  2196. },
  2197. );
  2198. }
  2199. data = Meteor.users.findOne({
  2200. _id: id,
  2201. });
  2202. }
  2203. }
  2204. JsonRoutes.sendResult(res, {
  2205. code: 200,
  2206. data,
  2207. });
  2208. } catch (error) {
  2209. JsonRoutes.sendResult(res, {
  2210. code: 200,
  2211. data: error,
  2212. });
  2213. }
  2214. });
  2215. /**
  2216. * @operation add_board_member
  2217. * @tag Boards
  2218. *
  2219. * @summary Add New Board Member with Role
  2220. *
  2221. * @description Only the admin user (the first user) can call the REST API.
  2222. *
  2223. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  2224. * to later change the permissions.
  2225. *
  2226. * @param {string} boardId the board ID
  2227. * @param {string} userId the user ID
  2228. * @param {string} action the action (needs to be `add`)
  2229. * @param {boolean} isAdmin is the user an admin of the board
  2230. * @param {boolean} isNoComments disable comments
  2231. * @param {boolean} isCommentOnly only enable comments
  2232. * @param {boolean} isWorker is the user a board worker
  2233. * @return_type {_id: string,
  2234. * title: string}
  2235. */
  2236. JsonRoutes.add(
  2237. 'POST',
  2238. '/api/boards/:boardId/members/:userId/add',
  2239. function (req, res) {
  2240. try {
  2241. Authentication.checkUserId(req.userId);
  2242. const userId = req.params.userId;
  2243. const boardId = req.params.boardId;
  2244. const action = req.body.action;
  2245. const { isAdmin, isNoComments, isCommentOnly, isWorker } = req.body;
  2246. let data = Meteor.users.findOne({
  2247. _id: userId,
  2248. });
  2249. if (data !== undefined) {
  2250. if (action === 'add') {
  2251. data = Boards.find({
  2252. _id: boardId,
  2253. }).map(function (board) {
  2254. if (!board.hasMember(userId)) {
  2255. board.addMember(userId);
  2256. function isTrue(data) {
  2257. return data.toLowerCase() === 'true';
  2258. }
  2259. board.setMemberPermission(
  2260. userId,
  2261. isTrue(isAdmin),
  2262. isTrue(isNoComments),
  2263. isTrue(isCommentOnly),
  2264. isTrue(isWorker),
  2265. userId,
  2266. );
  2267. }
  2268. return {
  2269. _id: board._id,
  2270. title: board.title,
  2271. };
  2272. });
  2273. }
  2274. }
  2275. JsonRoutes.sendResult(res, { code: 200, data });
  2276. } catch (error) {
  2277. JsonRoutes.sendResult(res, {
  2278. code: 200,
  2279. data: error,
  2280. });
  2281. }
  2282. },
  2283. );
  2284. /**
  2285. * @operation remove_board_member
  2286. * @tag Boards
  2287. *
  2288. * @summary Remove Member from Board
  2289. *
  2290. * @description Only the admin user (the first user) can call the REST API.
  2291. *
  2292. * @param {string} boardId the board ID
  2293. * @param {string} userId the user ID
  2294. * @param {string} action the action (needs to be `remove`)
  2295. * @return_type {_id: string,
  2296. * title: string}
  2297. */
  2298. JsonRoutes.add(
  2299. 'POST',
  2300. '/api/boards/:boardId/members/:userId/remove',
  2301. function (req, res) {
  2302. try {
  2303. Authentication.checkUserId(req.userId);
  2304. const userId = req.params.userId;
  2305. const boardId = req.params.boardId;
  2306. const action = req.body.action;
  2307. let data = Meteor.users.findOne({
  2308. _id: userId,
  2309. });
  2310. if (data !== undefined) {
  2311. if (action === 'remove') {
  2312. data = Boards.find({
  2313. _id: boardId,
  2314. }).map(function (board) {
  2315. if (board.hasMember(userId)) {
  2316. board.removeMember(userId);
  2317. }
  2318. return {
  2319. _id: board._id,
  2320. title: board.title,
  2321. };
  2322. });
  2323. }
  2324. }
  2325. JsonRoutes.sendResult(res, { code: 200, data });
  2326. } catch (error) {
  2327. JsonRoutes.sendResult(res, {
  2328. code: 200,
  2329. data: error,
  2330. });
  2331. }
  2332. },
  2333. );
  2334. /**
  2335. * @operation new_user
  2336. *
  2337. * @summary Create a new user
  2338. *
  2339. * @description Only the admin user (the first user) can call the REST API.
  2340. *
  2341. * @param {string} username the new username
  2342. * @param {string} email the email of the new user
  2343. * @param {string} password the password of the new user
  2344. * @return_type {_id: string}
  2345. */
  2346. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  2347. try {
  2348. Authentication.checkUserId(req.userId);
  2349. const id = Accounts.createUser({
  2350. username: req.body.username,
  2351. email: req.body.email,
  2352. password: req.body.password,
  2353. from: 'admin',
  2354. });
  2355. JsonRoutes.sendResult(res, {
  2356. code: 200,
  2357. data: {
  2358. _id: id,
  2359. },
  2360. });
  2361. } catch (error) {
  2362. JsonRoutes.sendResult(res, {
  2363. code: 200,
  2364. data: error,
  2365. });
  2366. }
  2367. });
  2368. /**
  2369. * @operation delete_user
  2370. *
  2371. * @summary Delete a user
  2372. *
  2373. * @description Only the admin user (the first user) can call the REST API.
  2374. *
  2375. * @param {string} userId the ID of the user to delete
  2376. * @return_type {_id: string}
  2377. */
  2378. JsonRoutes.add('DELETE', '/api/users/:userId', function (req, res) {
  2379. try {
  2380. Authentication.checkUserId(req.userId);
  2381. const id = req.params.userId;
  2382. // Delete user is enabled, but is still has bug of leaving empty user avatars
  2383. // to boards: boards members, card members and assignees have
  2384. // empty users. So it would be better to delete user from all boards before
  2385. // deleting user.
  2386. // See:
  2387. // - wekan/client/components/settings/peopleBody.jade deleteButton
  2388. // - wekan/client/components/settings/peopleBody.js deleteButton
  2389. // - wekan/client/components/sidebar/sidebar.js Popup.afterConfirm('removeMember'
  2390. // that does now remove member from board, card members and assignees correctly,
  2391. // but that should be used to remove user from all boards similarly
  2392. // - wekan/models/users.js Delete is not enabled
  2393. Meteor.users.remove({ _id: id });
  2394. JsonRoutes.sendResult(res, {
  2395. code: 200,
  2396. data: {
  2397. _id: id,
  2398. },
  2399. });
  2400. } catch (error) {
  2401. JsonRoutes.sendResult(res, {
  2402. code: 200,
  2403. data: error,
  2404. });
  2405. }
  2406. });
  2407. /**
  2408. * @operation create_user_token
  2409. *
  2410. * @summary Create a user token
  2411. *
  2412. * @description Only the admin user (the first user) can call the REST API.
  2413. *
  2414. * @param {string} userId the ID of the user to create token for.
  2415. * @return_type {_id: string}
  2416. */
  2417. JsonRoutes.add('POST', '/api/createtoken/:userId', function (req, res) {
  2418. try {
  2419. Authentication.checkUserId(req.userId);
  2420. const id = req.params.userId;
  2421. const token = Accounts._generateStampedLoginToken();
  2422. Accounts._insertLoginToken(id, token);
  2423. JsonRoutes.sendResult(res, {
  2424. code: 200,
  2425. data: {
  2426. _id: id,
  2427. authToken: token.token,
  2428. },
  2429. });
  2430. } catch (error) {
  2431. JsonRoutes.sendResult(res, {
  2432. code: 200,
  2433. data: error,
  2434. });
  2435. }
  2436. });
  2437. /**
  2438. * @operation delete_user_token
  2439. *
  2440. * @summary Delete one or all user token.
  2441. *
  2442. * @description Only the admin user (the first user) can call the REST API.
  2443. *
  2444. * @param {string} userId the user ID
  2445. * @param {string} token the user hashedToken
  2446. * @return_type {message: string}
  2447. */
  2448. JsonRoutes.add('POST', '/api/deletetoken', function (req, res) {
  2449. try {
  2450. const { userId, token } = req.body;
  2451. Authentication.checkUserId(req.userId);
  2452. let data = {
  2453. message: 'Expected a userId to be set but received none.',
  2454. };
  2455. if (token && userId) {
  2456. Accounts.destroyToken(userId, token);
  2457. data.message = 'Delete token: [' + token + '] from user: ' + userId;
  2458. } else if (userId) {
  2459. check(userId, String);
  2460. Users.update(
  2461. {
  2462. _id: userId,
  2463. },
  2464. {
  2465. $set: {
  2466. 'services.resume.loginTokens': '',
  2467. },
  2468. },
  2469. );
  2470. data.message = 'Delete all token from user: ' + userId;
  2471. }
  2472. JsonRoutes.sendResult(res, {
  2473. code: 200,
  2474. data,
  2475. });
  2476. } catch (error) {
  2477. JsonRoutes.sendResult(res, {
  2478. code: 200,
  2479. data: error,
  2480. });
  2481. }
  2482. });
  2483. }
  2484. export default Users;