users.js 42 KB

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