users.js 83 KB

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