users.js 74 KB

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