users.js 68 KB

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