users.js 81 KB

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