users.js 63 KB

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