users.js 69 KB

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