users.js 71 KB

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