users.js 69 KB

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