users.js 70 KB

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