users.js 67 KB

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