users.js 82 KB

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