users.js 72 KB

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