users.js 74 KB

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