users.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  1. import { SyncedCron } from 'meteor/percolate:synced-cron';
  2. // Sandstorm context is detected using the METEOR_SETTINGS environment variable
  3. // in the package definition.
  4. const isSandstorm =
  5. Meteor.settings && Meteor.settings.public && Meteor.settings.public.sandstorm;
  6. Users = Meteor.users;
  7. const allowedSortValues = [
  8. '-modifiedAt',
  9. 'modifiedAt',
  10. '-title',
  11. 'title',
  12. '-sort',
  13. 'sort',
  14. ];
  15. const defaultSortBy = allowedSortValues[0];
  16. /**
  17. * A User in wekan
  18. */
  19. Users.attachSchema(
  20. new SimpleSchema({
  21. username: {
  22. /**
  23. * the username of the user
  24. */
  25. type: String,
  26. optional: true,
  27. // eslint-disable-next-line consistent-return
  28. autoValue() {
  29. if (this.isInsert && !this.isSet) {
  30. const name = this.field('profile.fullname');
  31. if (name.isSet) {
  32. return name.value.toLowerCase().replace(/\s/g, '');
  33. }
  34. }
  35. },
  36. },
  37. emails: {
  38. /**
  39. * the list of emails attached to a user
  40. */
  41. type: [Object],
  42. optional: true,
  43. },
  44. 'emails.$.address': {
  45. /**
  46. * The email address
  47. */
  48. type: String,
  49. regEx: SimpleSchema.RegEx.Email,
  50. },
  51. 'emails.$.verified': {
  52. /**
  53. * Has the email been verified
  54. */
  55. type: Boolean,
  56. },
  57. createdAt: {
  58. /**
  59. * creation date of the user
  60. */
  61. type: Date,
  62. // eslint-disable-next-line consistent-return
  63. autoValue() {
  64. if (this.isInsert) {
  65. return new Date();
  66. } else if (this.isUpsert) {
  67. return { $setOnInsert: new Date() };
  68. } else {
  69. this.unset();
  70. }
  71. },
  72. },
  73. modifiedAt: {
  74. type: Date,
  75. denyUpdate: false,
  76. // eslint-disable-next-line consistent-return
  77. autoValue() {
  78. if (this.isInsert || this.isUpsert || this.isUpdate) {
  79. return new Date();
  80. } else {
  81. this.unset();
  82. }
  83. },
  84. },
  85. profile: {
  86. /**
  87. * profile settings
  88. */
  89. type: Object,
  90. optional: true,
  91. // eslint-disable-next-line consistent-return
  92. autoValue() {
  93. if (this.isInsert && !this.isSet) {
  94. return {
  95. boardView: 'board-view-lists',
  96. };
  97. }
  98. },
  99. },
  100. 'profile.avatarUrl': {
  101. /**
  102. * URL of the avatar of the user
  103. */
  104. type: String,
  105. optional: true,
  106. },
  107. 'profile.emailBuffer': {
  108. /**
  109. * list of email buffers of the user
  110. */
  111. type: [String],
  112. optional: true,
  113. },
  114. 'profile.fullname': {
  115. /**
  116. * full name of the user
  117. */
  118. type: String,
  119. optional: true,
  120. },
  121. 'profile.showDesktopDragHandles': {
  122. /**
  123. * does the user want to hide system messages?
  124. */
  125. type: Boolean,
  126. optional: true,
  127. },
  128. 'profile.hiddenSystemMessages': {
  129. /**
  130. * does the user want to hide system messages?
  131. */
  132. type: Boolean,
  133. optional: true,
  134. },
  135. 'profile.hiddenMinicardLabelText': {
  136. /**
  137. * does the user want to hide minicard label texts?
  138. */
  139. type: Boolean,
  140. optional: true,
  141. },
  142. 'profile.initials': {
  143. /**
  144. * initials of the user
  145. */
  146. type: String,
  147. optional: true,
  148. },
  149. 'profile.invitedBoards': {
  150. /**
  151. * board IDs the user has been invited to
  152. */
  153. type: [String],
  154. optional: true,
  155. },
  156. 'profile.language': {
  157. /**
  158. * language of the user
  159. */
  160. type: String,
  161. optional: true,
  162. },
  163. 'profile.notifications': {
  164. /**
  165. * enabled notifications for the user
  166. */
  167. type: [Object],
  168. optional: true,
  169. },
  170. 'profile.notifications.$.activity': {
  171. /**
  172. * The id of the activity this notification references
  173. */
  174. type: String,
  175. },
  176. 'profile.notifications.$.read': {
  177. /**
  178. * the date on which this notification was read
  179. */
  180. type: Date,
  181. optional: true,
  182. },
  183. 'profile.showCardsCountAt': {
  184. /**
  185. * showCardCountAt field of the user
  186. */
  187. type: Number,
  188. optional: true,
  189. },
  190. 'profile.startDayOfWeek': {
  191. /**
  192. * startDayOfWeek field of the user
  193. */
  194. type: Number,
  195. optional: true,
  196. },
  197. 'profile.starredBoards': {
  198. /**
  199. * list of starred board IDs
  200. */
  201. type: [String],
  202. optional: true,
  203. },
  204. 'profile.icode': {
  205. /**
  206. * icode
  207. */
  208. type: String,
  209. optional: true,
  210. },
  211. 'profile.boardView': {
  212. /**
  213. * boardView field of the user
  214. */
  215. type: String,
  216. optional: true,
  217. allowedValues: [
  218. 'board-view-lists',
  219. 'board-view-swimlanes',
  220. 'board-view-cal',
  221. ],
  222. },
  223. 'profile.listSortBy': {
  224. /**
  225. * default sort list for user
  226. */
  227. type: String,
  228. optional: true,
  229. defaultValue: defaultSortBy,
  230. allowedValues: allowedSortValues,
  231. },
  232. 'profile.templatesBoardId': {
  233. /**
  234. * Reference to the templates board
  235. */
  236. type: String,
  237. defaultValue: '',
  238. },
  239. 'profile.cardTemplatesSwimlaneId': {
  240. /**
  241. * Reference to the card templates swimlane Id
  242. */
  243. type: String,
  244. defaultValue: '',
  245. },
  246. 'profile.listTemplatesSwimlaneId': {
  247. /**
  248. * Reference to the list templates swimlane Id
  249. */
  250. type: String,
  251. defaultValue: '',
  252. },
  253. 'profile.boardTemplatesSwimlaneId': {
  254. /**
  255. * Reference to the board templates swimlane Id
  256. */
  257. type: String,
  258. defaultValue: '',
  259. },
  260. services: {
  261. /**
  262. * services field of the user
  263. */
  264. type: Object,
  265. optional: true,
  266. blackbox: true,
  267. },
  268. heartbeat: {
  269. /**
  270. * last time the user has been seen
  271. */
  272. type: Date,
  273. optional: true,
  274. },
  275. isAdmin: {
  276. /**
  277. * is the user an admin of the board?
  278. */
  279. type: Boolean,
  280. optional: true,
  281. },
  282. createdThroughApi: {
  283. /**
  284. * was the user created through the API?
  285. */
  286. type: Boolean,
  287. optional: true,
  288. },
  289. loginDisabled: {
  290. /**
  291. * loginDisabled field of the user
  292. */
  293. type: Boolean,
  294. optional: true,
  295. },
  296. authenticationMethod: {
  297. /**
  298. * authentication method of the user
  299. */
  300. type: String,
  301. optional: false,
  302. defaultValue: 'password',
  303. },
  304. }),
  305. );
  306. Users.allow({
  307. update(userId, doc) {
  308. const user = Users.findOne({ _id: userId });
  309. if ((user && user.isAdmin) || (Meteor.user() && Meteor.user().isAdmin))
  310. return true;
  311. if (!user) {
  312. return false;
  313. }
  314. return doc._id === userId;
  315. },
  316. remove(userId, doc) {
  317. const adminsNumber = Users.find({ isAdmin: true }).count();
  318. const { isAdmin } = Users.findOne(
  319. { _id: userId },
  320. { fields: { isAdmin: 1 } },
  321. );
  322. // Prevents remove of the only one administrator
  323. if (adminsNumber === 1 && isAdmin && userId === doc._id) {
  324. return false;
  325. }
  326. // If it's the user or an admin
  327. return userId === doc._id || isAdmin;
  328. },
  329. fetch: [],
  330. });
  331. // Search a user in the complete server database by its name or username. This
  332. // is used for instance to add a new user to a board.
  333. const searchInFields = ['username', 'profile.fullname'];
  334. Users.initEasySearch(searchInFields, {
  335. use: 'mongo-db',
  336. returnFields: [...searchInFields, 'profile.avatarUrl'],
  337. });
  338. if (Meteor.isClient) {
  339. Users.helpers({
  340. isBoardMember() {
  341. const board = Boards.findOne(Session.get('currentBoard'));
  342. return board && board.hasMember(this._id);
  343. },
  344. isNotNoComments() {
  345. const board = Boards.findOne(Session.get('currentBoard'));
  346. return (
  347. board && board.hasMember(this._id) && !board.hasNoComments(this._id)
  348. );
  349. },
  350. isNoComments() {
  351. const board = Boards.findOne(Session.get('currentBoard'));
  352. return board && board.hasNoComments(this._id);
  353. },
  354. isNotCommentOnly() {
  355. const board = Boards.findOne(Session.get('currentBoard'));
  356. return (
  357. board && board.hasMember(this._id) && !board.hasCommentOnly(this._id)
  358. );
  359. },
  360. isCommentOnly() {
  361. const board = Boards.findOne(Session.get('currentBoard'));
  362. return board && board.hasCommentOnly(this._id);
  363. },
  364. isNotWorker() {
  365. const board = Boards.findOne(Session.get('currentBoard'));
  366. return board && board.hasMember(this._id) && !board.hasWorker(this._id);
  367. },
  368. isWorker() {
  369. const board = Boards.findOne(Session.get('currentBoard'));
  370. return board && board.hasWorker(this._id);
  371. },
  372. isBoardAdmin(boardId = Session.get('currentBoard')) {
  373. const board = Boards.findOne(boardId);
  374. return board && board.hasAdmin(this._id);
  375. },
  376. });
  377. }
  378. Users.helpers({
  379. boards() {
  380. return Boards.find(
  381. { 'members.userId': this._id },
  382. { sort: { sort: 1 /* boards default sorting */ } },
  383. );
  384. },
  385. starredBoards() {
  386. const { starredBoards = [] } = this.profile || {};
  387. return Boards.find(
  388. { archived: false, _id: { $in: starredBoards } },
  389. {
  390. sort: { sort: 1 /* boards default sorting */ },
  391. },
  392. );
  393. },
  394. hasStarred(boardId) {
  395. const { starredBoards = [] } = this.profile || {};
  396. return _.contains(starredBoards, boardId);
  397. },
  398. invitedBoards() {
  399. const { invitedBoards = [] } = this.profile || {};
  400. return Boards.find(
  401. { archived: false, _id: { $in: invitedBoards } },
  402. {
  403. sort: { sort: 1 /* boards default sorting */ },
  404. },
  405. );
  406. },
  407. isInvitedTo(boardId) {
  408. const { invitedBoards = [] } = this.profile || {};
  409. return _.contains(invitedBoards, boardId);
  410. },
  411. _getListSortBy() {
  412. const profile = this.profile || {};
  413. const sortBy = profile.listSortBy || defaultSortBy;
  414. const keyPattern = /^(-{0,1})(.*$)/;
  415. const ret = [];
  416. if (keyPattern.exec(sortBy)) {
  417. ret[0] = RegExp.$2;
  418. ret[1] = RegExp.$1 ? -1 : 1;
  419. }
  420. return ret;
  421. },
  422. hasSortBy() {
  423. // if use doesn't have dragHandle, then we can let user to choose sort list by different order
  424. return !this.hasShowDesktopDragHandles();
  425. },
  426. getListSortBy() {
  427. return this._getListSortBy()[0];
  428. },
  429. getListSortTypes() {
  430. return allowedSortValues;
  431. },
  432. getListSortByDirection() {
  433. return this._getListSortBy()[1];
  434. },
  435. hasTag(tag) {
  436. const { tags = [] } = this.profile || {};
  437. return _.contains(tags, tag);
  438. },
  439. hasNotification(activityId) {
  440. const { notifications = [] } = this.profile || {};
  441. return _.contains(notifications, activityId);
  442. },
  443. notifications() {
  444. const { notifications = [] } = this.profile || {};
  445. for (const index in notifications) {
  446. if (!notifications.hasOwnProperty(index)) continue;
  447. const notification = notifications[index];
  448. // this preserves their db sort order for editing
  449. notification.dbIndex = index;
  450. notification.activity = Activities.findOne(notification.activity);
  451. }
  452. // this sorts them newest to oldest to match Trello's behavior
  453. notifications.reverse();
  454. return notifications;
  455. },
  456. hasShowDesktopDragHandles() {
  457. const profile = this.profile || {};
  458. return profile.showDesktopDragHandles || false;
  459. },
  460. hasHiddenSystemMessages() {
  461. const profile = this.profile || {};
  462. return profile.hiddenSystemMessages || false;
  463. },
  464. hasHiddenMinicardLabelText() {
  465. const profile = this.profile || {};
  466. return profile.hiddenMinicardLabelText || false;
  467. },
  468. getEmailBuffer() {
  469. const { emailBuffer = [] } = this.profile || {};
  470. return emailBuffer;
  471. },
  472. getInitials() {
  473. const profile = this.profile || {};
  474. if (profile.initials) return profile.initials;
  475. else if (profile.fullname) {
  476. return profile.fullname
  477. .split(/\s+/)
  478. .reduce((memo, word) => {
  479. return memo + word[0];
  480. }, '')
  481. .toUpperCase();
  482. } else {
  483. return this.username[0].toUpperCase();
  484. }
  485. },
  486. getLimitToShowCardsCount() {
  487. const profile = this.profile || {};
  488. return profile.showCardsCountAt;
  489. },
  490. getName() {
  491. const profile = this.profile || {};
  492. return profile.fullname || this.username;
  493. },
  494. getLanguage() {
  495. const profile = this.profile || {};
  496. return profile.language || 'en';
  497. },
  498. getStartDayOfWeek() {
  499. const profile = this.profile || {};
  500. return profile.startDayOfWeek || 1;
  501. },
  502. getTemplatesBoardId() {
  503. return (this.profile || {}).templatesBoardId;
  504. },
  505. getTemplatesBoardSlug() {
  506. return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  507. },
  508. remove() {
  509. User.remove({ _id: this._id });
  510. },
  511. });
  512. Users.mutations({
  513. toggleBoardStar(boardId) {
  514. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  515. return {
  516. [queryKind]: {
  517. 'profile.starredBoards': boardId,
  518. },
  519. };
  520. },
  521. addInvite(boardId) {
  522. return {
  523. $addToSet: {
  524. 'profile.invitedBoards': boardId,
  525. },
  526. };
  527. },
  528. removeInvite(boardId) {
  529. return {
  530. $pull: {
  531. 'profile.invitedBoards': boardId,
  532. },
  533. };
  534. },
  535. addTag(tag) {
  536. return {
  537. $addToSet: {
  538. 'profile.tags': tag,
  539. },
  540. };
  541. },
  542. removeTag(tag) {
  543. return {
  544. $pull: {
  545. 'profile.tags': tag,
  546. },
  547. };
  548. },
  549. toggleTag(tag) {
  550. if (this.hasTag(tag)) this.removeTag(tag);
  551. else this.addTag(tag);
  552. },
  553. setListSortBy(value) {
  554. return {
  555. $set: {
  556. 'profile.listSortBy': value,
  557. },
  558. };
  559. },
  560. toggleDesktopHandles(value = false) {
  561. return {
  562. $set: {
  563. 'profile.showDesktopDragHandles': !value,
  564. },
  565. };
  566. },
  567. toggleSystem(value = false) {
  568. return {
  569. $set: {
  570. 'profile.hiddenSystemMessages': !value,
  571. },
  572. };
  573. },
  574. toggleLabelText(value = false) {
  575. return {
  576. $set: {
  577. 'profile.hiddenMinicardLabelText': !value,
  578. },
  579. };
  580. },
  581. addNotification(activityId) {
  582. return {
  583. $addToSet: {
  584. 'profile.notifications': { activity: activityId },
  585. },
  586. };
  587. },
  588. removeNotification(activityId) {
  589. return {
  590. $pull: {
  591. 'profile.notifications': { activity: activityId },
  592. },
  593. };
  594. },
  595. addEmailBuffer(text) {
  596. return {
  597. $addToSet: {
  598. 'profile.emailBuffer': text,
  599. },
  600. };
  601. },
  602. clearEmailBuffer() {
  603. return {
  604. $set: {
  605. 'profile.emailBuffer': [],
  606. },
  607. };
  608. },
  609. setAvatarUrl(avatarUrl) {
  610. return { $set: { 'profile.avatarUrl': avatarUrl } };
  611. },
  612. setShowCardsCountAt(limit) {
  613. return { $set: { 'profile.showCardsCountAt': limit } };
  614. },
  615. setStartDayOfWeek(startDay) {
  616. return { $set: { 'profile.startDayOfWeek': startDay } };
  617. },
  618. setBoardView(view) {
  619. return {
  620. $set: {
  621. 'profile.boardView': view,
  622. },
  623. };
  624. },
  625. });
  626. Meteor.methods({
  627. setListSortBy(value) {
  628. check(value, String);
  629. Meteor.user().setListSortBy(value);
  630. },
  631. toggleDesktopDragHandles() {
  632. const user = Meteor.user();
  633. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  634. },
  635. toggleSystemMessages() {
  636. const user = Meteor.user();
  637. user.toggleSystem(user.hasHiddenSystemMessages());
  638. },
  639. toggleMinicardLabelText() {
  640. const user = Meteor.user();
  641. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  642. },
  643. changeLimitToShowCardsCount(limit) {
  644. check(limit, Number);
  645. Meteor.user().setShowCardsCountAt(limit);
  646. },
  647. changeStartDayOfWeek(startDay) {
  648. check(startDay, Number);
  649. Meteor.user().setStartDayOfWeek(startDay);
  650. },
  651. });
  652. if (Meteor.isServer) {
  653. Meteor.methods({
  654. setCreateUser(fullname, username, password, isAdmin, isActive, email) {
  655. if (Meteor.user() && Meteor.user().isAdmin) {
  656. check(fullname, String);
  657. check(username, String);
  658. check(password, String);
  659. check(isAdmin, String);
  660. check(isActive, String);
  661. check(email, String);
  662. const nUsersWithUsername = Users.find({ username }).count();
  663. const nUsersWithEmail = Users.find({ email }).count();
  664. if (nUsersWithUsername > 0) {
  665. throw new Meteor.Error('username-already-taken');
  666. } else if (nUsersWithEmail > 0) {
  667. throw new Meteor.Error('email-already-taken');
  668. } else {
  669. Accounts.createUser({
  670. fullname,
  671. username,
  672. password,
  673. isAdmin,
  674. isActive,
  675. email: email.toLowerCase(),
  676. from: 'admin',
  677. });
  678. }
  679. }
  680. },
  681. setUsername(username, userId) {
  682. if (Meteor.user() && Meteor.user().isAdmin) {
  683. check(username, String);
  684. check(userId, String);
  685. const nUsersWithUsername = Users.find({ username }).count();
  686. if (nUsersWithUsername > 0) {
  687. throw new Meteor.Error('username-already-taken');
  688. } else {
  689. Users.update(userId, { $set: { username } });
  690. }
  691. }
  692. },
  693. setEmail(email, userId) {
  694. if (Meteor.user() && Meteor.user().isAdmin) {
  695. if (Array.isArray(email)) {
  696. email = email.shift();
  697. }
  698. check(email, String);
  699. const existingUser = Users.findOne(
  700. { 'emails.address': email },
  701. { fields: { _id: 1 } },
  702. );
  703. if (existingUser) {
  704. throw new Meteor.Error('email-already-taken');
  705. } else {
  706. Users.update(userId, {
  707. $set: {
  708. emails: [
  709. {
  710. address: email,
  711. verified: false,
  712. },
  713. ],
  714. },
  715. });
  716. }
  717. }
  718. },
  719. setUsernameAndEmail(username, email, userId) {
  720. if (Meteor.user() && Meteor.user().isAdmin) {
  721. check(username, String);
  722. if (Array.isArray(email)) {
  723. email = email.shift();
  724. }
  725. check(email, String);
  726. check(userId, String);
  727. Meteor.call('setUsername', username, userId);
  728. Meteor.call('setEmail', email, userId);
  729. }
  730. },
  731. setPassword(newPassword, userId) {
  732. if (Meteor.user() && Meteor.user().isAdmin) {
  733. check(userId, String);
  734. check(newPassword, String);
  735. if (Meteor.user().isAdmin) {
  736. Accounts.setPassword(userId, newPassword);
  737. }
  738. }
  739. },
  740. // we accept userId, username, email
  741. inviteUserToBoard(username, boardId) {
  742. check(username, String);
  743. check(boardId, String);
  744. const inviter = Meteor.user();
  745. const board = Boards.findOne(boardId);
  746. const allowInvite =
  747. inviter &&
  748. board &&
  749. board.members &&
  750. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  751. _.where(board.members, { userId: inviter._id })[0].isActive;
  752. // GitHub issue 2060
  753. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  754. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  755. this.unblock();
  756. const posAt = username.indexOf('@');
  757. let user = null;
  758. if (posAt >= 0) {
  759. user = Users.findOne({ emails: { $elemMatch: { address: username } } });
  760. } else {
  761. user = Users.findOne(username) || Users.findOne({ username });
  762. }
  763. if (user) {
  764. if (user._id === inviter._id)
  765. throw new Meteor.Error('error-user-notAllowSelf');
  766. } else {
  767. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  768. if (Settings.findOne({ disableRegistration: true })) {
  769. throw new Meteor.Error('error-user-notCreated');
  770. }
  771. // Set in lowercase email before creating account
  772. const email = username.toLowerCase();
  773. username = email.substring(0, posAt);
  774. const newUserId = Accounts.createUser({ username, email });
  775. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  776. // assume new user speak same language with inviter
  777. if (inviter.profile && inviter.profile.language) {
  778. Users.update(newUserId, {
  779. $set: {
  780. 'profile.language': inviter.profile.language,
  781. },
  782. });
  783. }
  784. Accounts.sendEnrollmentEmail(newUserId);
  785. user = Users.findOne(newUserId);
  786. }
  787. board.addMember(user._id);
  788. user.addInvite(boardId);
  789. //Check if there is a subtasks board
  790. if (board.subtasksDefaultBoardId) {
  791. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  792. //If there is, also add user to that board
  793. if (subBoard) {
  794. subBoard.addMember(user._id);
  795. user.addInvite(subBoard._id);
  796. }
  797. }
  798. try {
  799. const params = {
  800. user: user.username,
  801. inviter: inviter.username,
  802. board: board.title,
  803. url: board.absoluteUrl(),
  804. };
  805. const lang = user.getLanguage();
  806. Email.send({
  807. to: user.emails[0].address.toLowerCase(),
  808. from: Accounts.emailTemplates.from,
  809. subject: TAPi18n.__('email-invite-subject', params, lang),
  810. text: TAPi18n.__('email-invite-text', params, lang),
  811. });
  812. } catch (e) {
  813. throw new Meteor.Error('email-fail', e.message);
  814. }
  815. return { username: user.username, email: user.emails[0].address };
  816. },
  817. });
  818. Accounts.onCreateUser((options, user) => {
  819. const userCount = Users.find().count();
  820. if (userCount === 0) {
  821. user.isAdmin = true;
  822. return user;
  823. }
  824. if (user.services.oidc) {
  825. let email = user.services.oidc.email;
  826. if (Array.isArray(email)) {
  827. email = email.shift();
  828. }
  829. email = email.toLowerCase();
  830. user.username = user.services.oidc.username;
  831. user.emails = [{ address: email, verified: true }];
  832. const initials = user.services.oidc.fullname
  833. .match(/\b[a-zA-Z]/g)
  834. .join('')
  835. .toUpperCase();
  836. user.profile = {
  837. initials,
  838. fullname: user.services.oidc.fullname,
  839. boardView: 'board-view-lists',
  840. };
  841. user.authenticationMethod = 'oauth2';
  842. // see if any existing user has this email address or username, otherwise create new
  843. const existingUser = Meteor.users.findOne({
  844. $or: [{ 'emails.address': email }, { username: user.username }],
  845. });
  846. if (!existingUser) return user;
  847. // copy across new service info
  848. const service = _.keys(user.services)[0];
  849. existingUser.services[service] = user.services[service];
  850. existingUser.emails = user.emails;
  851. existingUser.username = user.username;
  852. existingUser.profile = user.profile;
  853. existingUser.authenticationMethod = user.authenticationMethod;
  854. Meteor.users.remove({ _id: existingUser._id }); // remove existing record
  855. return existingUser;
  856. }
  857. if (options.from === 'admin') {
  858. user.createdThroughApi = true;
  859. return user;
  860. }
  861. const disableRegistration = Settings.findOne().disableRegistration;
  862. // If this is the first Authentication by the ldap and self registration disabled
  863. if (disableRegistration && options && options.ldap) {
  864. user.authenticationMethod = 'ldap';
  865. return user;
  866. }
  867. // If self registration enabled
  868. if (!disableRegistration) {
  869. return user;
  870. }
  871. if (!options || !options.profile) {
  872. throw new Meteor.Error(
  873. 'error-invitation-code-blank',
  874. 'The invitation code is required',
  875. );
  876. }
  877. const invitationCode = InvitationCodes.findOne({
  878. code: options.profile.invitationcode,
  879. email: options.email,
  880. valid: true,
  881. });
  882. if (!invitationCode) {
  883. throw new Meteor.Error(
  884. 'error-invitation-code-not-exist',
  885. // eslint-disable-next-line quotes
  886. "The invitation code doesn't exist",
  887. );
  888. } else {
  889. user.profile = { icode: options.profile.invitationcode };
  890. user.profile.boardView = 'board-view-lists';
  891. // Deletes the invitation code after the user was created successfully.
  892. setTimeout(
  893. Meteor.bindEnvironment(() => {
  894. InvitationCodes.remove({ _id: invitationCode._id });
  895. }),
  896. 200,
  897. );
  898. return user;
  899. }
  900. });
  901. }
  902. const addCronJob = _.debounce(
  903. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  904. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  905. const envRemoveAge =
  906. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  907. // default notifications will be removed 2 days after they are read
  908. const defaultRemoveAge = 2;
  909. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  910. SyncedCron.add({
  911. name: 'notification_cleanup',
  912. schedule: parser => parser.text('every 1 days'),
  913. job: () => {
  914. for (const user of Users.find()) {
  915. if (!user.profile || !user.profile.notifications) continue;
  916. for (const notification of user.profile.notifications) {
  917. if (notification.read) {
  918. const removeDate = new Date(notification.read);
  919. removeDate.setDate(removeDate.getDate() + removeAge);
  920. if (removeDate <= new Date()) {
  921. user.removeNotification(notification.activity);
  922. }
  923. }
  924. }
  925. }
  926. },
  927. });
  928. SyncedCron.start();
  929. }),
  930. 500,
  931. );
  932. if (Meteor.isServer) {
  933. // Let mongoDB ensure username unicity
  934. Meteor.startup(() => {
  935. allowedSortValues.forEach(value => {
  936. Lists._collection._ensureIndex(value);
  937. });
  938. Users._collection._ensureIndex({ modifiedAt: -1 });
  939. Users._collection._ensureIndex(
  940. {
  941. username: 1,
  942. },
  943. { unique: true },
  944. );
  945. Meteor.defer(() => {
  946. addCronJob();
  947. });
  948. });
  949. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  950. // if admin is removed, board is removed.
  951. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  952. // to use that board, and not have board deleted.
  953. // Someone can be later changed to be admin of board, by making change to database.
  954. // TODO: Add UI for changing someone as board admin.
  955. //Users.before.remove((userId, doc) => {
  956. // Boards
  957. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  958. // .forEach((board) => {
  959. // // If only one admin for the board
  960. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  961. // Boards.remove(board._id);
  962. // }
  963. // });
  964. //});
  965. // Each board document contains the de-normalized number of users that have
  966. // starred it. If the user star or unstar a board, we need to update this
  967. // counter.
  968. // We need to run this code on the server only, otherwise the incrementation
  969. // will be done twice.
  970. Users.after.update(function(userId, user, fieldNames) {
  971. // The `starredBoards` list is hosted on the `profile` field. If this
  972. // field hasn't been modificated we don't need to run this hook.
  973. if (!_.contains(fieldNames, 'profile')) return;
  974. // To calculate a diff of board starred ids, we get both the previous
  975. // and the newly board ids list
  976. function getStarredBoardsIds(doc) {
  977. return doc.profile && doc.profile.starredBoards;
  978. }
  979. const oldIds = getStarredBoardsIds(this.previous);
  980. const newIds = getStarredBoardsIds(user);
  981. // The _.difference(a, b) method returns the values from a that are not in
  982. // b. We use it to find deleted and newly inserted ids by using it in one
  983. // direction and then in the other.
  984. function incrementBoards(boardsIds, inc) {
  985. boardsIds.forEach(boardId => {
  986. Boards.update(boardId, { $inc: { stars: inc } });
  987. });
  988. }
  989. incrementBoards(_.difference(oldIds, newIds), -1);
  990. incrementBoards(_.difference(newIds, oldIds), +1);
  991. });
  992. const fakeUserId = new Meteor.EnvironmentVariable();
  993. const getUserId = CollectionHooks.getUserId;
  994. CollectionHooks.getUserId = () => {
  995. return fakeUserId.get() || getUserId();
  996. };
  997. if (!isSandstorm) {
  998. Users.after.insert((userId, doc) => {
  999. const fakeUser = {
  1000. extendAutoValueContext: {
  1001. userId: doc._id,
  1002. },
  1003. };
  1004. fakeUserId.withValue(doc._id, () => {
  1005. /*
  1006. // Insert the Welcome Board
  1007. Boards.insert({
  1008. title: TAPi18n.__('welcome-board'),
  1009. permission: 'private',
  1010. }, fakeUser, (err, boardId) => {
  1011. Swimlanes.insert({
  1012. title: TAPi18n.__('welcome-swimlane'),
  1013. boardId,
  1014. sort: 1,
  1015. }, fakeUser);
  1016. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1017. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1018. });
  1019. });
  1020. */
  1021. Boards.insert(
  1022. {
  1023. title: TAPi18n.__('templates'),
  1024. permission: 'private',
  1025. type: 'template-container',
  1026. },
  1027. fakeUser,
  1028. (err, boardId) => {
  1029. // Insert the reference to our templates board
  1030. Users.update(fakeUserId.get(), {
  1031. $set: { 'profile.templatesBoardId': boardId },
  1032. });
  1033. // Insert the card templates swimlane
  1034. Swimlanes.insert(
  1035. {
  1036. title: TAPi18n.__('card-templates-swimlane'),
  1037. boardId,
  1038. sort: 1,
  1039. type: 'template-container',
  1040. },
  1041. fakeUser,
  1042. (err, swimlaneId) => {
  1043. // Insert the reference to out card templates swimlane
  1044. Users.update(fakeUserId.get(), {
  1045. $set: { 'profile.cardTemplatesSwimlaneId': swimlaneId },
  1046. });
  1047. },
  1048. );
  1049. // Insert the list templates swimlane
  1050. Swimlanes.insert(
  1051. {
  1052. title: TAPi18n.__('list-templates-swimlane'),
  1053. boardId,
  1054. sort: 2,
  1055. type: 'template-container',
  1056. },
  1057. fakeUser,
  1058. (err, swimlaneId) => {
  1059. // Insert the reference to out list templates swimlane
  1060. Users.update(fakeUserId.get(), {
  1061. $set: { 'profile.listTemplatesSwimlaneId': swimlaneId },
  1062. });
  1063. },
  1064. );
  1065. // Insert the board templates swimlane
  1066. Swimlanes.insert(
  1067. {
  1068. title: TAPi18n.__('board-templates-swimlane'),
  1069. boardId,
  1070. sort: 3,
  1071. type: 'template-container',
  1072. },
  1073. fakeUser,
  1074. (err, swimlaneId) => {
  1075. // Insert the reference to out board templates swimlane
  1076. Users.update(fakeUserId.get(), {
  1077. $set: { 'profile.boardTemplatesSwimlaneId': swimlaneId },
  1078. });
  1079. },
  1080. );
  1081. },
  1082. );
  1083. });
  1084. });
  1085. }
  1086. Users.after.insert((userId, doc) => {
  1087. if (doc.createdThroughApi) {
  1088. // The admin user should be able to create a user despite disabling registration because
  1089. // it is two different things (registration and creation).
  1090. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1091. // the disableRegistration check.
  1092. // Issue : https://github.com/wekan/wekan/issues/1232
  1093. // PR : https://github.com/wekan/wekan/pull/1251
  1094. Users.update(doc._id, { $set: { createdThroughApi: '' } });
  1095. return;
  1096. }
  1097. //invite user to corresponding boards
  1098. const disableRegistration = Settings.findOne().disableRegistration;
  1099. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1100. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1101. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1102. const invitationCode = InvitationCodes.findOne({
  1103. code: doc.profile.icode,
  1104. valid: true,
  1105. });
  1106. if (!invitationCode) {
  1107. throw new Meteor.Error('error-invitation-code-not-exist');
  1108. } else {
  1109. invitationCode.boardsToBeInvited.forEach(boardId => {
  1110. const board = Boards.findOne(boardId);
  1111. board.addMember(doc._id);
  1112. });
  1113. if (!doc.profile) {
  1114. doc.profile = {};
  1115. }
  1116. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1117. Users.update(doc._id, { $set: { profile: doc.profile } });
  1118. InvitationCodes.update(invitationCode._id, { $set: { valid: false } });
  1119. }
  1120. }
  1121. });
  1122. }
  1123. // USERS REST API
  1124. if (Meteor.isServer) {
  1125. // Middleware which checks that API is enabled.
  1126. JsonRoutes.Middleware.use(function(req, res, next) {
  1127. const api = req.url.startsWith('/api');
  1128. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1129. return next();
  1130. } else {
  1131. res.writeHead(301, { Location: '/' });
  1132. return res.end();
  1133. }
  1134. });
  1135. /**
  1136. * @operation get_current_user
  1137. *
  1138. * @summary returns the current user
  1139. * @return_type Users
  1140. */
  1141. JsonRoutes.add('GET', '/api/user', function(req, res) {
  1142. try {
  1143. Authentication.checkLoggedIn(req.userId);
  1144. const data = Meteor.users.findOne({ _id: req.userId });
  1145. delete data.services;
  1146. JsonRoutes.sendResult(res, {
  1147. code: 200,
  1148. data,
  1149. });
  1150. } catch (error) {
  1151. JsonRoutes.sendResult(res, {
  1152. code: 200,
  1153. data: error,
  1154. });
  1155. }
  1156. });
  1157. /**
  1158. * @operation get_all_users
  1159. *
  1160. * @summary return all the users
  1161. *
  1162. * @description Only the admin user (the first user) can call the REST API.
  1163. * @return_type [{ _id: string,
  1164. * username: string}]
  1165. */
  1166. JsonRoutes.add('GET', '/api/users', function(req, res) {
  1167. try {
  1168. Authentication.checkUserId(req.userId);
  1169. JsonRoutes.sendResult(res, {
  1170. code: 200,
  1171. data: Meteor.users.find({}).map(function(doc) {
  1172. return { _id: doc._id, username: doc.username };
  1173. }),
  1174. });
  1175. } catch (error) {
  1176. JsonRoutes.sendResult(res, {
  1177. code: 200,
  1178. data: error,
  1179. });
  1180. }
  1181. });
  1182. /**
  1183. * @operation get_user
  1184. *
  1185. * @summary get a given user
  1186. *
  1187. * @description Only the admin user (the first user) can call the REST API.
  1188. *
  1189. * @param {string} userId the user ID
  1190. * @return_type Users
  1191. */
  1192. JsonRoutes.add('GET', '/api/users/:userId', function(req, res) {
  1193. try {
  1194. Authentication.checkUserId(req.userId);
  1195. const id = req.params.userId;
  1196. JsonRoutes.sendResult(res, {
  1197. code: 200,
  1198. data: Meteor.users.findOne({ _id: id }),
  1199. });
  1200. } catch (error) {
  1201. JsonRoutes.sendResult(res, {
  1202. code: 200,
  1203. data: error,
  1204. });
  1205. }
  1206. });
  1207. /**
  1208. * @operation edit_user
  1209. *
  1210. * @summary edit a given user
  1211. *
  1212. * @description Only the admin user (the first user) can call the REST API.
  1213. *
  1214. * Possible values for *action*:
  1215. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1216. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1217. * - `enableLogin`: Enable a user
  1218. *
  1219. * @param {string} userId the user ID
  1220. * @param {string} action the action
  1221. * @return_type {_id: string,
  1222. * title: string}
  1223. */
  1224. JsonRoutes.add('PUT', '/api/users/:userId', function(req, res) {
  1225. try {
  1226. Authentication.checkUserId(req.userId);
  1227. const id = req.params.userId;
  1228. const action = req.body.action;
  1229. let data = Meteor.users.findOne({ _id: id });
  1230. if (data !== undefined) {
  1231. if (action === 'takeOwnership') {
  1232. data = Boards.find(
  1233. {
  1234. 'members.userId': id,
  1235. 'members.isAdmin': true,
  1236. },
  1237. { sort: { sort: 1 /* boards default sorting */ } },
  1238. ).map(function(board) {
  1239. if (board.hasMember(req.userId)) {
  1240. board.removeMember(req.userId);
  1241. }
  1242. board.changeOwnership(id, req.userId);
  1243. return {
  1244. _id: board._id,
  1245. title: board.title,
  1246. };
  1247. });
  1248. } else {
  1249. if (action === 'disableLogin' && id !== req.userId) {
  1250. Users.update(
  1251. { _id: id },
  1252. {
  1253. $set: {
  1254. loginDisabled: true,
  1255. 'services.resume.loginTokens': '',
  1256. },
  1257. },
  1258. );
  1259. } else if (action === 'enableLogin') {
  1260. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  1261. }
  1262. data = Meteor.users.findOne({ _id: id });
  1263. }
  1264. }
  1265. JsonRoutes.sendResult(res, {
  1266. code: 200,
  1267. data,
  1268. });
  1269. } catch (error) {
  1270. JsonRoutes.sendResult(res, {
  1271. code: 200,
  1272. data: error,
  1273. });
  1274. }
  1275. });
  1276. /**
  1277. * @operation add_board_member
  1278. * @tag Boards
  1279. *
  1280. * @summary Add New Board Member with Role
  1281. *
  1282. * @description Only the admin user (the first user) can call the REST API.
  1283. *
  1284. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1285. * to later change the permissions.
  1286. *
  1287. * @param {string} boardId the board ID
  1288. * @param {string} userId the user ID
  1289. * @param {boolean} isAdmin is the user an admin of the board
  1290. * @param {boolean} isNoComments disable comments
  1291. * @param {boolean} isCommentOnly only enable comments
  1292. * @return_type {_id: string,
  1293. * title: string}
  1294. */
  1295. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function(
  1296. req,
  1297. res,
  1298. ) {
  1299. try {
  1300. Authentication.checkUserId(req.userId);
  1301. const userId = req.params.userId;
  1302. const boardId = req.params.boardId;
  1303. const action = req.body.action;
  1304. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1305. let data = Meteor.users.findOne({ _id: userId });
  1306. if (data !== undefined) {
  1307. if (action === 'add') {
  1308. data = Boards.find({
  1309. _id: boardId,
  1310. }).map(function(board) {
  1311. if (!board.hasMember(userId)) {
  1312. board.addMember(userId);
  1313. function isTrue(data) {
  1314. return data.toLowerCase() === 'true';
  1315. }
  1316. board.setMemberPermission(
  1317. userId,
  1318. isTrue(isAdmin),
  1319. isTrue(isNoComments),
  1320. isTrue(isCommentOnly),
  1321. userId,
  1322. );
  1323. }
  1324. return {
  1325. _id: board._id,
  1326. title: board.title,
  1327. };
  1328. });
  1329. }
  1330. }
  1331. JsonRoutes.sendResult(res, {
  1332. code: 200,
  1333. data: query,
  1334. });
  1335. } catch (error) {
  1336. JsonRoutes.sendResult(res, {
  1337. code: 200,
  1338. data: error,
  1339. });
  1340. }
  1341. });
  1342. /**
  1343. * @operation remove_board_member
  1344. * @tag Boards
  1345. *
  1346. * @summary Remove Member from Board
  1347. *
  1348. * @description Only the admin user (the first user) can call the REST API.
  1349. *
  1350. * @param {string} boardId the board ID
  1351. * @param {string} userId the user ID
  1352. * @param {string} action the action (needs to be `remove`)
  1353. * @return_type {_id: string,
  1354. * title: string}
  1355. */
  1356. JsonRoutes.add(
  1357. 'POST',
  1358. '/api/boards/:boardId/members/:userId/remove',
  1359. function(req, res) {
  1360. try {
  1361. Authentication.checkUserId(req.userId);
  1362. const userId = req.params.userId;
  1363. const boardId = req.params.boardId;
  1364. const action = req.body.action;
  1365. let data = Meteor.users.findOne({ _id: userId });
  1366. if (data !== undefined) {
  1367. if (action === 'remove') {
  1368. data = Boards.find({
  1369. _id: boardId,
  1370. }).map(function(board) {
  1371. if (board.hasMember(userId)) {
  1372. board.removeMember(userId);
  1373. }
  1374. return {
  1375. _id: board._id,
  1376. title: board.title,
  1377. };
  1378. });
  1379. }
  1380. }
  1381. JsonRoutes.sendResult(res, {
  1382. code: 200,
  1383. data: query,
  1384. });
  1385. } catch (error) {
  1386. JsonRoutes.sendResult(res, {
  1387. code: 200,
  1388. data: error,
  1389. });
  1390. }
  1391. },
  1392. );
  1393. /**
  1394. * @operation new_user
  1395. *
  1396. * @summary Create a new user
  1397. *
  1398. * @description Only the admin user (the first user) can call the REST API.
  1399. *
  1400. * @param {string} username the new username
  1401. * @param {string} email the email of the new user
  1402. * @param {string} password the password of the new user
  1403. * @return_type {_id: string}
  1404. */
  1405. JsonRoutes.add('POST', '/api/users/', function(req, res) {
  1406. try {
  1407. Authentication.checkUserId(req.userId);
  1408. const id = Accounts.createUser({
  1409. username: req.body.username,
  1410. email: req.body.email,
  1411. password: req.body.password,
  1412. from: 'admin',
  1413. });
  1414. JsonRoutes.sendResult(res, {
  1415. code: 200,
  1416. data: {
  1417. _id: id,
  1418. },
  1419. });
  1420. } catch (error) {
  1421. JsonRoutes.sendResult(res, {
  1422. code: 200,
  1423. data: error,
  1424. });
  1425. }
  1426. });
  1427. /**
  1428. * @operation delete_user
  1429. *
  1430. * @summary Delete a user
  1431. *
  1432. * @description Only the admin user (the first user) can call the REST API.
  1433. *
  1434. * @param {string} userId the ID of the user to delete
  1435. * @return_type {_id: string}
  1436. */
  1437. JsonRoutes.add('DELETE', '/api/users/:userId', function(req, res) {
  1438. try {
  1439. Authentication.checkUserId(req.userId);
  1440. const id = req.params.userId;
  1441. Meteor.users.remove({ _id: id });
  1442. JsonRoutes.sendResult(res, {
  1443. code: 200,
  1444. data: {
  1445. _id: id,
  1446. },
  1447. });
  1448. } catch (error) {
  1449. JsonRoutes.sendResult(res, {
  1450. code: 200,
  1451. data: error,
  1452. });
  1453. }
  1454. });
  1455. }
  1456. export default Users;