users.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  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. // default is 'Monday' (1)
  501. return profile.startDayOfWeek || 1;
  502. },
  503. getTemplatesBoardId() {
  504. return (this.profile || {}).templatesBoardId;
  505. },
  506. getTemplatesBoardSlug() {
  507. return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  508. },
  509. remove() {
  510. User.remove({ _id: this._id });
  511. },
  512. });
  513. Users.mutations({
  514. toggleBoardStar(boardId) {
  515. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  516. return {
  517. [queryKind]: {
  518. 'profile.starredBoards': boardId,
  519. },
  520. };
  521. },
  522. addInvite(boardId) {
  523. return {
  524. $addToSet: {
  525. 'profile.invitedBoards': boardId,
  526. },
  527. };
  528. },
  529. removeInvite(boardId) {
  530. return {
  531. $pull: {
  532. 'profile.invitedBoards': boardId,
  533. },
  534. };
  535. },
  536. addTag(tag) {
  537. return {
  538. $addToSet: {
  539. 'profile.tags': tag,
  540. },
  541. };
  542. },
  543. removeTag(tag) {
  544. return {
  545. $pull: {
  546. 'profile.tags': tag,
  547. },
  548. };
  549. },
  550. toggleTag(tag) {
  551. if (this.hasTag(tag)) this.removeTag(tag);
  552. else this.addTag(tag);
  553. },
  554. setListSortBy(value) {
  555. return {
  556. $set: {
  557. 'profile.listSortBy': value,
  558. },
  559. };
  560. },
  561. toggleDesktopHandles(value = false) {
  562. return {
  563. $set: {
  564. 'profile.showDesktopDragHandles': !value,
  565. },
  566. };
  567. },
  568. toggleSystem(value = false) {
  569. return {
  570. $set: {
  571. 'profile.hiddenSystemMessages': !value,
  572. },
  573. };
  574. },
  575. toggleLabelText(value = false) {
  576. return {
  577. $set: {
  578. 'profile.hiddenMinicardLabelText': !value,
  579. },
  580. };
  581. },
  582. addNotification(activityId) {
  583. return {
  584. $addToSet: {
  585. 'profile.notifications': { activity: activityId },
  586. },
  587. };
  588. },
  589. removeNotification(activityId) {
  590. return {
  591. $pull: {
  592. 'profile.notifications': { activity: activityId },
  593. },
  594. };
  595. },
  596. addEmailBuffer(text) {
  597. return {
  598. $addToSet: {
  599. 'profile.emailBuffer': text,
  600. },
  601. };
  602. },
  603. clearEmailBuffer() {
  604. return {
  605. $set: {
  606. 'profile.emailBuffer': [],
  607. },
  608. };
  609. },
  610. setAvatarUrl(avatarUrl) {
  611. return { $set: { 'profile.avatarUrl': avatarUrl } };
  612. },
  613. setShowCardsCountAt(limit) {
  614. return { $set: { 'profile.showCardsCountAt': limit } };
  615. },
  616. setStartDayOfWeek(startDay) {
  617. return { $set: { 'profile.startDayOfWeek': startDay } };
  618. },
  619. setBoardView(view) {
  620. return {
  621. $set: {
  622. 'profile.boardView': view,
  623. },
  624. };
  625. },
  626. });
  627. Meteor.methods({
  628. setListSortBy(value) {
  629. check(value, String);
  630. Meteor.user().setListSortBy(value);
  631. },
  632. toggleDesktopDragHandles() {
  633. const user = Meteor.user();
  634. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  635. },
  636. toggleSystemMessages() {
  637. const user = Meteor.user();
  638. user.toggleSystem(user.hasHiddenSystemMessages());
  639. },
  640. toggleMinicardLabelText() {
  641. const user = Meteor.user();
  642. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  643. },
  644. changeLimitToShowCardsCount(limit) {
  645. check(limit, Number);
  646. Meteor.user().setShowCardsCountAt(limit);
  647. },
  648. changeStartDayOfWeek(startDay) {
  649. check(startDay, Number);
  650. Meteor.user().setStartDayOfWeek(startDay);
  651. },
  652. });
  653. if (Meteor.isServer) {
  654. Meteor.methods({
  655. setCreateUser(fullname, username, password, isAdmin, isActive, email) {
  656. if (Meteor.user() && Meteor.user().isAdmin) {
  657. check(fullname, String);
  658. check(username, String);
  659. check(password, String);
  660. check(isAdmin, String);
  661. check(isActive, String);
  662. check(email, String);
  663. const nUsersWithUsername = Users.find({ username }).count();
  664. const nUsersWithEmail = Users.find({ email }).count();
  665. if (nUsersWithUsername > 0) {
  666. throw new Meteor.Error('username-already-taken');
  667. } else if (nUsersWithEmail > 0) {
  668. throw new Meteor.Error('email-already-taken');
  669. } else {
  670. Accounts.createUser({
  671. fullname,
  672. username,
  673. password,
  674. isAdmin,
  675. isActive,
  676. email: email.toLowerCase(),
  677. from: 'admin',
  678. });
  679. }
  680. }
  681. },
  682. setUsername(username, userId) {
  683. if (Meteor.user() && Meteor.user().isAdmin) {
  684. check(username, String);
  685. check(userId, String);
  686. const nUsersWithUsername = Users.find({ username }).count();
  687. if (nUsersWithUsername > 0) {
  688. throw new Meteor.Error('username-already-taken');
  689. } else {
  690. Users.update(userId, { $set: { username } });
  691. }
  692. }
  693. },
  694. setEmail(email, userId) {
  695. if (Meteor.user() && Meteor.user().isAdmin) {
  696. if (Array.isArray(email)) {
  697. email = email.shift();
  698. }
  699. check(email, String);
  700. const existingUser = Users.findOne(
  701. { 'emails.address': email },
  702. { fields: { _id: 1 } },
  703. );
  704. if (existingUser) {
  705. throw new Meteor.Error('email-already-taken');
  706. } else {
  707. Users.update(userId, {
  708. $set: {
  709. emails: [
  710. {
  711. address: email,
  712. verified: false,
  713. },
  714. ],
  715. },
  716. });
  717. }
  718. }
  719. },
  720. setUsernameAndEmail(username, email, userId) {
  721. if (Meteor.user() && Meteor.user().isAdmin) {
  722. check(username, String);
  723. if (Array.isArray(email)) {
  724. email = email.shift();
  725. }
  726. check(email, String);
  727. check(userId, String);
  728. Meteor.call('setUsername', username, userId);
  729. Meteor.call('setEmail', email, userId);
  730. }
  731. },
  732. setPassword(newPassword, userId) {
  733. if (Meteor.user() && Meteor.user().isAdmin) {
  734. check(userId, String);
  735. check(newPassword, String);
  736. if (Meteor.user().isAdmin) {
  737. Accounts.setPassword(userId, newPassword);
  738. }
  739. }
  740. },
  741. // we accept userId, username, email
  742. inviteUserToBoard(username, boardId) {
  743. check(username, String);
  744. check(boardId, String);
  745. const inviter = Meteor.user();
  746. const board = Boards.findOne(boardId);
  747. const allowInvite =
  748. inviter &&
  749. board &&
  750. board.members &&
  751. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  752. _.where(board.members, { userId: inviter._id })[0].isActive;
  753. // GitHub issue 2060
  754. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  755. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  756. this.unblock();
  757. const posAt = username.indexOf('@');
  758. let user = null;
  759. if (posAt >= 0) {
  760. user = Users.findOne({ emails: { $elemMatch: { address: username } } });
  761. } else {
  762. user = Users.findOne(username) || Users.findOne({ username });
  763. }
  764. if (user) {
  765. if (user._id === inviter._id)
  766. throw new Meteor.Error('error-user-notAllowSelf');
  767. } else {
  768. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  769. if (Settings.findOne({ disableRegistration: true })) {
  770. throw new Meteor.Error('error-user-notCreated');
  771. }
  772. // Set in lowercase email before creating account
  773. const email = username.toLowerCase();
  774. username = email.substring(0, posAt);
  775. const newUserId = Accounts.createUser({ username, email });
  776. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  777. // assume new user speak same language with inviter
  778. if (inviter.profile && inviter.profile.language) {
  779. Users.update(newUserId, {
  780. $set: {
  781. 'profile.language': inviter.profile.language,
  782. },
  783. });
  784. }
  785. Accounts.sendEnrollmentEmail(newUserId);
  786. user = Users.findOne(newUserId);
  787. }
  788. board.addMember(user._id);
  789. user.addInvite(boardId);
  790. //Check if there is a subtasks board
  791. if (board.subtasksDefaultBoardId) {
  792. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  793. //If there is, also add user to that board
  794. if (subBoard) {
  795. subBoard.addMember(user._id);
  796. user.addInvite(subBoard._id);
  797. }
  798. }
  799. try {
  800. const params = {
  801. user: user.username,
  802. inviter: inviter.username,
  803. board: board.title,
  804. url: board.absoluteUrl(),
  805. };
  806. const lang = user.getLanguage();
  807. Email.send({
  808. to: user.emails[0].address.toLowerCase(),
  809. from: Accounts.emailTemplates.from,
  810. subject: TAPi18n.__('email-invite-subject', params, lang),
  811. text: TAPi18n.__('email-invite-text', params, lang),
  812. });
  813. } catch (e) {
  814. throw new Meteor.Error('email-fail', e.message);
  815. }
  816. return { username: user.username, email: user.emails[0].address };
  817. },
  818. });
  819. Accounts.onCreateUser((options, user) => {
  820. const userCount = Users.find().count();
  821. if (userCount === 0) {
  822. user.isAdmin = true;
  823. return user;
  824. }
  825. if (user.services.oidc) {
  826. let email = user.services.oidc.email;
  827. if (Array.isArray(email)) {
  828. email = email.shift();
  829. }
  830. email = email.toLowerCase();
  831. user.username = user.services.oidc.username;
  832. user.emails = [{ address: email, verified: true }];
  833. const initials = user.services.oidc.fullname
  834. .match(/\b[a-zA-Z]/g)
  835. .join('')
  836. .toUpperCase();
  837. user.profile = {
  838. initials,
  839. fullname: user.services.oidc.fullname,
  840. boardView: 'board-view-lists',
  841. };
  842. user.authenticationMethod = 'oauth2';
  843. // see if any existing user has this email address or username, otherwise create new
  844. const existingUser = Meteor.users.findOne({
  845. $or: [{ 'emails.address': email }, { username: user.username }],
  846. });
  847. if (!existingUser) return user;
  848. // copy across new service info
  849. const service = _.keys(user.services)[0];
  850. existingUser.services[service] = user.services[service];
  851. existingUser.emails = user.emails;
  852. existingUser.username = user.username;
  853. existingUser.profile = user.profile;
  854. existingUser.authenticationMethod = user.authenticationMethod;
  855. Meteor.users.remove({ _id: existingUser._id }); // remove existing record
  856. return existingUser;
  857. }
  858. if (options.from === 'admin') {
  859. user.createdThroughApi = true;
  860. return user;
  861. }
  862. const disableRegistration = Settings.findOne().disableRegistration;
  863. // If this is the first Authentication by the ldap and self registration disabled
  864. if (disableRegistration && options && options.ldap) {
  865. user.authenticationMethod = 'ldap';
  866. return user;
  867. }
  868. // If self registration enabled
  869. if (!disableRegistration) {
  870. return user;
  871. }
  872. if (!options || !options.profile) {
  873. throw new Meteor.Error(
  874. 'error-invitation-code-blank',
  875. 'The invitation code is required',
  876. );
  877. }
  878. const invitationCode = InvitationCodes.findOne({
  879. code: options.profile.invitationcode,
  880. email: options.email,
  881. valid: true,
  882. });
  883. if (!invitationCode) {
  884. throw new Meteor.Error(
  885. 'error-invitation-code-not-exist',
  886. // eslint-disable-next-line quotes
  887. "The invitation code doesn't exist",
  888. );
  889. } else {
  890. user.profile = { icode: options.profile.invitationcode };
  891. user.profile.boardView = 'board-view-lists';
  892. // Deletes the invitation code after the user was created successfully.
  893. setTimeout(
  894. Meteor.bindEnvironment(() => {
  895. InvitationCodes.remove({ _id: invitationCode._id });
  896. }),
  897. 200,
  898. );
  899. return user;
  900. }
  901. });
  902. }
  903. const addCronJob = _.debounce(
  904. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  905. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  906. const envRemoveAge =
  907. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  908. // default notifications will be removed 2 days after they are read
  909. const defaultRemoveAge = 2;
  910. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  911. SyncedCron.add({
  912. name: 'notification_cleanup',
  913. schedule: parser => parser.text('every 1 days'),
  914. job: () => {
  915. for (const user of Users.find()) {
  916. if (!user.profile || !user.profile.notifications) continue;
  917. for (const notification of user.profile.notifications) {
  918. if (notification.read) {
  919. const removeDate = new Date(notification.read);
  920. removeDate.setDate(removeDate.getDate() + removeAge);
  921. if (removeDate <= new Date()) {
  922. user.removeNotification(notification.activity);
  923. }
  924. }
  925. }
  926. }
  927. },
  928. });
  929. SyncedCron.start();
  930. }),
  931. 500,
  932. );
  933. if (Meteor.isServer) {
  934. // Let mongoDB ensure username unicity
  935. Meteor.startup(() => {
  936. allowedSortValues.forEach(value => {
  937. Lists._collection._ensureIndex(value);
  938. });
  939. Users._collection._ensureIndex({ modifiedAt: -1 });
  940. Users._collection._ensureIndex(
  941. {
  942. username: 1,
  943. },
  944. { unique: true },
  945. );
  946. Meteor.defer(() => {
  947. addCronJob();
  948. });
  949. });
  950. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  951. // if admin is removed, board is removed.
  952. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  953. // to use that board, and not have board deleted.
  954. // Someone can be later changed to be admin of board, by making change to database.
  955. // TODO: Add UI for changing someone as board admin.
  956. //Users.before.remove((userId, doc) => {
  957. // Boards
  958. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  959. // .forEach((board) => {
  960. // // If only one admin for the board
  961. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  962. // Boards.remove(board._id);
  963. // }
  964. // });
  965. //});
  966. // Each board document contains the de-normalized number of users that have
  967. // starred it. If the user star or unstar a board, we need to update this
  968. // counter.
  969. // We need to run this code on the server only, otherwise the incrementation
  970. // will be done twice.
  971. Users.after.update(function(userId, user, fieldNames) {
  972. // The `starredBoards` list is hosted on the `profile` field. If this
  973. // field hasn't been modificated we don't need to run this hook.
  974. if (!_.contains(fieldNames, 'profile')) return;
  975. // To calculate a diff of board starred ids, we get both the previous
  976. // and the newly board ids list
  977. function getStarredBoardsIds(doc) {
  978. return doc.profile && doc.profile.starredBoards;
  979. }
  980. const oldIds = getStarredBoardsIds(this.previous);
  981. const newIds = getStarredBoardsIds(user);
  982. // The _.difference(a, b) method returns the values from a that are not in
  983. // b. We use it to find deleted and newly inserted ids by using it in one
  984. // direction and then in the other.
  985. function incrementBoards(boardsIds, inc) {
  986. boardsIds.forEach(boardId => {
  987. Boards.update(boardId, { $inc: { stars: inc } });
  988. });
  989. }
  990. incrementBoards(_.difference(oldIds, newIds), -1);
  991. incrementBoards(_.difference(newIds, oldIds), +1);
  992. });
  993. const fakeUserId = new Meteor.EnvironmentVariable();
  994. const getUserId = CollectionHooks.getUserId;
  995. CollectionHooks.getUserId = () => {
  996. return fakeUserId.get() || getUserId();
  997. };
  998. if (!isSandstorm) {
  999. Users.after.insert((userId, doc) => {
  1000. const fakeUser = {
  1001. extendAutoValueContext: {
  1002. userId: doc._id,
  1003. },
  1004. };
  1005. fakeUserId.withValue(doc._id, () => {
  1006. /*
  1007. // Insert the Welcome Board
  1008. Boards.insert({
  1009. title: TAPi18n.__('welcome-board'),
  1010. permission: 'private',
  1011. }, fakeUser, (err, boardId) => {
  1012. Swimlanes.insert({
  1013. title: TAPi18n.__('welcome-swimlane'),
  1014. boardId,
  1015. sort: 1,
  1016. }, fakeUser);
  1017. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1018. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1019. });
  1020. });
  1021. */
  1022. Boards.insert(
  1023. {
  1024. title: TAPi18n.__('templates'),
  1025. permission: 'private',
  1026. type: 'template-container',
  1027. },
  1028. fakeUser,
  1029. (err, boardId) => {
  1030. // Insert the reference to our templates board
  1031. Users.update(fakeUserId.get(), {
  1032. $set: { 'profile.templatesBoardId': boardId },
  1033. });
  1034. // Insert the card templates swimlane
  1035. Swimlanes.insert(
  1036. {
  1037. title: TAPi18n.__('card-templates-swimlane'),
  1038. boardId,
  1039. sort: 1,
  1040. type: 'template-container',
  1041. },
  1042. fakeUser,
  1043. (err, swimlaneId) => {
  1044. // Insert the reference to out card templates swimlane
  1045. Users.update(fakeUserId.get(), {
  1046. $set: { 'profile.cardTemplatesSwimlaneId': swimlaneId },
  1047. });
  1048. },
  1049. );
  1050. // Insert the list templates swimlane
  1051. Swimlanes.insert(
  1052. {
  1053. title: TAPi18n.__('list-templates-swimlane'),
  1054. boardId,
  1055. sort: 2,
  1056. type: 'template-container',
  1057. },
  1058. fakeUser,
  1059. (err, swimlaneId) => {
  1060. // Insert the reference to out list templates swimlane
  1061. Users.update(fakeUserId.get(), {
  1062. $set: { 'profile.listTemplatesSwimlaneId': swimlaneId },
  1063. });
  1064. },
  1065. );
  1066. // Insert the board templates swimlane
  1067. Swimlanes.insert(
  1068. {
  1069. title: TAPi18n.__('board-templates-swimlane'),
  1070. boardId,
  1071. sort: 3,
  1072. type: 'template-container',
  1073. },
  1074. fakeUser,
  1075. (err, swimlaneId) => {
  1076. // Insert the reference to out board templates swimlane
  1077. Users.update(fakeUserId.get(), {
  1078. $set: { 'profile.boardTemplatesSwimlaneId': swimlaneId },
  1079. });
  1080. },
  1081. );
  1082. },
  1083. );
  1084. });
  1085. });
  1086. }
  1087. Users.after.insert((userId, doc) => {
  1088. if (doc.createdThroughApi) {
  1089. // The admin user should be able to create a user despite disabling registration because
  1090. // it is two different things (registration and creation).
  1091. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1092. // the disableRegistration check.
  1093. // Issue : https://github.com/wekan/wekan/issues/1232
  1094. // PR : https://github.com/wekan/wekan/pull/1251
  1095. Users.update(doc._id, { $set: { createdThroughApi: '' } });
  1096. return;
  1097. }
  1098. //invite user to corresponding boards
  1099. const disableRegistration = Settings.findOne().disableRegistration;
  1100. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1101. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1102. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1103. const invitationCode = InvitationCodes.findOne({
  1104. code: doc.profile.icode,
  1105. valid: true,
  1106. });
  1107. if (!invitationCode) {
  1108. throw new Meteor.Error('error-invitation-code-not-exist');
  1109. } else {
  1110. invitationCode.boardsToBeInvited.forEach(boardId => {
  1111. const board = Boards.findOne(boardId);
  1112. board.addMember(doc._id);
  1113. });
  1114. if (!doc.profile) {
  1115. doc.profile = {};
  1116. }
  1117. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1118. Users.update(doc._id, { $set: { profile: doc.profile } });
  1119. InvitationCodes.update(invitationCode._id, { $set: { valid: false } });
  1120. }
  1121. }
  1122. });
  1123. }
  1124. // USERS REST API
  1125. if (Meteor.isServer) {
  1126. // Middleware which checks that API is enabled.
  1127. JsonRoutes.Middleware.use(function(req, res, next) {
  1128. const api = req.url.startsWith('/api');
  1129. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1130. return next();
  1131. } else {
  1132. res.writeHead(301, { Location: '/' });
  1133. return res.end();
  1134. }
  1135. });
  1136. /**
  1137. * @operation get_current_user
  1138. *
  1139. * @summary returns the current user
  1140. * @return_type Users
  1141. */
  1142. JsonRoutes.add('GET', '/api/user', function(req, res) {
  1143. try {
  1144. Authentication.checkLoggedIn(req.userId);
  1145. const data = Meteor.users.findOne({ _id: req.userId });
  1146. delete data.services;
  1147. JsonRoutes.sendResult(res, {
  1148. code: 200,
  1149. data,
  1150. });
  1151. } catch (error) {
  1152. JsonRoutes.sendResult(res, {
  1153. code: 200,
  1154. data: error,
  1155. });
  1156. }
  1157. });
  1158. /**
  1159. * @operation get_all_users
  1160. *
  1161. * @summary return all the users
  1162. *
  1163. * @description Only the admin user (the first user) can call the REST API.
  1164. * @return_type [{ _id: string,
  1165. * username: string}]
  1166. */
  1167. JsonRoutes.add('GET', '/api/users', function(req, res) {
  1168. try {
  1169. Authentication.checkUserId(req.userId);
  1170. JsonRoutes.sendResult(res, {
  1171. code: 200,
  1172. data: Meteor.users.find({}).map(function(doc) {
  1173. return { _id: doc._id, username: doc.username };
  1174. }),
  1175. });
  1176. } catch (error) {
  1177. JsonRoutes.sendResult(res, {
  1178. code: 200,
  1179. data: error,
  1180. });
  1181. }
  1182. });
  1183. /**
  1184. * @operation get_user
  1185. *
  1186. * @summary get a given user
  1187. *
  1188. * @description Only the admin user (the first user) can call the REST API.
  1189. *
  1190. * @param {string} userId the user ID
  1191. * @return_type Users
  1192. */
  1193. JsonRoutes.add('GET', '/api/users/:userId', function(req, res) {
  1194. try {
  1195. Authentication.checkUserId(req.userId);
  1196. const id = req.params.userId;
  1197. JsonRoutes.sendResult(res, {
  1198. code: 200,
  1199. data: Meteor.users.findOne({ _id: id }),
  1200. });
  1201. } catch (error) {
  1202. JsonRoutes.sendResult(res, {
  1203. code: 200,
  1204. data: error,
  1205. });
  1206. }
  1207. });
  1208. /**
  1209. * @operation edit_user
  1210. *
  1211. * @summary edit a given user
  1212. *
  1213. * @description Only the admin user (the first user) can call the REST API.
  1214. *
  1215. * Possible values for *action*:
  1216. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1217. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1218. * - `enableLogin`: Enable a user
  1219. *
  1220. * @param {string} userId the user ID
  1221. * @param {string} action the action
  1222. * @return_type {_id: string,
  1223. * title: string}
  1224. */
  1225. JsonRoutes.add('PUT', '/api/users/:userId', function(req, res) {
  1226. try {
  1227. Authentication.checkUserId(req.userId);
  1228. const id = req.params.userId;
  1229. const action = req.body.action;
  1230. let data = Meteor.users.findOne({ _id: id });
  1231. if (data !== undefined) {
  1232. if (action === 'takeOwnership') {
  1233. data = Boards.find(
  1234. {
  1235. 'members.userId': id,
  1236. 'members.isAdmin': true,
  1237. },
  1238. { sort: { sort: 1 /* boards default sorting */ } },
  1239. ).map(function(board) {
  1240. if (board.hasMember(req.userId)) {
  1241. board.removeMember(req.userId);
  1242. }
  1243. board.changeOwnership(id, req.userId);
  1244. return {
  1245. _id: board._id,
  1246. title: board.title,
  1247. };
  1248. });
  1249. } else {
  1250. if (action === 'disableLogin' && id !== req.userId) {
  1251. Users.update(
  1252. { _id: id },
  1253. {
  1254. $set: {
  1255. loginDisabled: true,
  1256. 'services.resume.loginTokens': '',
  1257. },
  1258. },
  1259. );
  1260. } else if (action === 'enableLogin') {
  1261. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  1262. }
  1263. data = Meteor.users.findOne({ _id: id });
  1264. }
  1265. }
  1266. JsonRoutes.sendResult(res, {
  1267. code: 200,
  1268. data,
  1269. });
  1270. } catch (error) {
  1271. JsonRoutes.sendResult(res, {
  1272. code: 200,
  1273. data: error,
  1274. });
  1275. }
  1276. });
  1277. /**
  1278. * @operation add_board_member
  1279. * @tag Boards
  1280. *
  1281. * @summary Add New Board Member with Role
  1282. *
  1283. * @description Only the admin user (the first user) can call the REST API.
  1284. *
  1285. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1286. * to later change the permissions.
  1287. *
  1288. * @param {string} boardId the board ID
  1289. * @param {string} userId the user ID
  1290. * @param {boolean} isAdmin is the user an admin of the board
  1291. * @param {boolean} isNoComments disable comments
  1292. * @param {boolean} isCommentOnly only enable comments
  1293. * @return_type {_id: string,
  1294. * title: string}
  1295. */
  1296. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function(
  1297. req,
  1298. res,
  1299. ) {
  1300. try {
  1301. Authentication.checkUserId(req.userId);
  1302. const userId = req.params.userId;
  1303. const boardId = req.params.boardId;
  1304. const action = req.body.action;
  1305. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1306. let data = Meteor.users.findOne({ _id: userId });
  1307. if (data !== undefined) {
  1308. if (action === 'add') {
  1309. data = Boards.find({
  1310. _id: boardId,
  1311. }).map(function(board) {
  1312. if (!board.hasMember(userId)) {
  1313. board.addMember(userId);
  1314. function isTrue(data) {
  1315. return data.toLowerCase() === 'true';
  1316. }
  1317. board.setMemberPermission(
  1318. userId,
  1319. isTrue(isAdmin),
  1320. isTrue(isNoComments),
  1321. isTrue(isCommentOnly),
  1322. userId,
  1323. );
  1324. }
  1325. return {
  1326. _id: board._id,
  1327. title: board.title,
  1328. };
  1329. });
  1330. }
  1331. }
  1332. JsonRoutes.sendResult(res, {
  1333. code: 200,
  1334. data: query,
  1335. });
  1336. } catch (error) {
  1337. JsonRoutes.sendResult(res, {
  1338. code: 200,
  1339. data: error,
  1340. });
  1341. }
  1342. });
  1343. /**
  1344. * @operation remove_board_member
  1345. * @tag Boards
  1346. *
  1347. * @summary Remove Member from Board
  1348. *
  1349. * @description Only the admin user (the first user) can call the REST API.
  1350. *
  1351. * @param {string} boardId the board ID
  1352. * @param {string} userId the user ID
  1353. * @param {string} action the action (needs to be `remove`)
  1354. * @return_type {_id: string,
  1355. * title: string}
  1356. */
  1357. JsonRoutes.add(
  1358. 'POST',
  1359. '/api/boards/:boardId/members/:userId/remove',
  1360. function(req, res) {
  1361. try {
  1362. Authentication.checkUserId(req.userId);
  1363. const userId = req.params.userId;
  1364. const boardId = req.params.boardId;
  1365. const action = req.body.action;
  1366. let data = Meteor.users.findOne({ _id: userId });
  1367. if (data !== undefined) {
  1368. if (action === 'remove') {
  1369. data = Boards.find({
  1370. _id: boardId,
  1371. }).map(function(board) {
  1372. if (board.hasMember(userId)) {
  1373. board.removeMember(userId);
  1374. }
  1375. return {
  1376. _id: board._id,
  1377. title: board.title,
  1378. };
  1379. });
  1380. }
  1381. }
  1382. JsonRoutes.sendResult(res, {
  1383. code: 200,
  1384. data: query,
  1385. });
  1386. } catch (error) {
  1387. JsonRoutes.sendResult(res, {
  1388. code: 200,
  1389. data: error,
  1390. });
  1391. }
  1392. },
  1393. );
  1394. /**
  1395. * @operation new_user
  1396. *
  1397. * @summary Create a new user
  1398. *
  1399. * @description Only the admin user (the first user) can call the REST API.
  1400. *
  1401. * @param {string} username the new username
  1402. * @param {string} email the email of the new user
  1403. * @param {string} password the password of the new user
  1404. * @return_type {_id: string}
  1405. */
  1406. JsonRoutes.add('POST', '/api/users/', function(req, res) {
  1407. try {
  1408. Authentication.checkUserId(req.userId);
  1409. const id = Accounts.createUser({
  1410. username: req.body.username,
  1411. email: req.body.email,
  1412. password: req.body.password,
  1413. from: 'admin',
  1414. });
  1415. JsonRoutes.sendResult(res, {
  1416. code: 200,
  1417. data: {
  1418. _id: id,
  1419. },
  1420. });
  1421. } catch (error) {
  1422. JsonRoutes.sendResult(res, {
  1423. code: 200,
  1424. data: error,
  1425. });
  1426. }
  1427. });
  1428. /**
  1429. * @operation delete_user
  1430. *
  1431. * @summary Delete a user
  1432. *
  1433. * @description Only the admin user (the first user) can call the REST API.
  1434. *
  1435. * @param {string} userId the ID of the user to delete
  1436. * @return_type {_id: string}
  1437. */
  1438. JsonRoutes.add('DELETE', '/api/users/:userId', function(req, res) {
  1439. try {
  1440. Authentication.checkUserId(req.userId);
  1441. const id = req.params.userId;
  1442. Meteor.users.remove({ _id: id });
  1443. JsonRoutes.sendResult(res, {
  1444. code: 200,
  1445. data: {
  1446. _id: id,
  1447. },
  1448. });
  1449. } catch (error) {
  1450. JsonRoutes.sendResult(res, {
  1451. code: 200,
  1452. data: error,
  1453. });
  1454. }
  1455. });
  1456. }
  1457. export default Users;