2
0

users.js 63 KB

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