users.js 84 KB

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