users.js 63 KB

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