users.js 70 KB

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