users.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601
  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. // Override getUserId so that we can TODO get the current userId
  997. const fakeUserId = new Meteor.EnvironmentVariable();
  998. const getUserId = CollectionHooks.getUserId;
  999. CollectionHooks.getUserId = () => {
  1000. return fakeUserId.get() || getUserId();
  1001. };
  1002. if (!isSandstorm) {
  1003. Users.after.insert((userId, doc) => {
  1004. const fakeUser = {
  1005. extendAutoValueContext: {
  1006. userId: doc._id,
  1007. },
  1008. };
  1009. fakeUserId.withValue(doc._id, () => {
  1010. /*
  1011. // Insert the Welcome Board
  1012. Boards.insert({
  1013. title: TAPi18n.__('welcome-board'),
  1014. permission: 'private',
  1015. }, fakeUser, (err, boardId) => {
  1016. Swimlanes.insert({
  1017. title: TAPi18n.__('welcome-swimlane'),
  1018. boardId,
  1019. sort: 1,
  1020. }, fakeUser);
  1021. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1022. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1023. });
  1024. });
  1025. */
  1026. Boards.insert(
  1027. {
  1028. title: TAPi18n.__('templates'),
  1029. permission: 'private',
  1030. type: 'template-container',
  1031. },
  1032. fakeUser,
  1033. (err, boardId) => {
  1034. // Insert the reference to our templates board
  1035. Users.update(fakeUserId.get(), {
  1036. $set: { 'profile.templatesBoardId': boardId },
  1037. });
  1038. // Insert the card templates swimlane
  1039. Swimlanes.insert(
  1040. {
  1041. title: TAPi18n.__('card-templates-swimlane'),
  1042. boardId,
  1043. sort: 1,
  1044. type: 'template-container',
  1045. },
  1046. fakeUser,
  1047. (err, swimlaneId) => {
  1048. // Insert the reference to out card templates swimlane
  1049. Users.update(fakeUserId.get(), {
  1050. $set: { 'profile.cardTemplatesSwimlaneId': swimlaneId },
  1051. });
  1052. },
  1053. );
  1054. // Insert the list templates swimlane
  1055. Swimlanes.insert(
  1056. {
  1057. title: TAPi18n.__('list-templates-swimlane'),
  1058. boardId,
  1059. sort: 2,
  1060. type: 'template-container',
  1061. },
  1062. fakeUser,
  1063. (err, swimlaneId) => {
  1064. // Insert the reference to out list templates swimlane
  1065. Users.update(fakeUserId.get(), {
  1066. $set: { 'profile.listTemplatesSwimlaneId': swimlaneId },
  1067. });
  1068. },
  1069. );
  1070. // Insert the board templates swimlane
  1071. Swimlanes.insert(
  1072. {
  1073. title: TAPi18n.__('board-templates-swimlane'),
  1074. boardId,
  1075. sort: 3,
  1076. type: 'template-container',
  1077. },
  1078. fakeUser,
  1079. (err, swimlaneId) => {
  1080. // Insert the reference to out board templates swimlane
  1081. Users.update(fakeUserId.get(), {
  1082. $set: { 'profile.boardTemplatesSwimlaneId': swimlaneId },
  1083. });
  1084. },
  1085. );
  1086. },
  1087. );
  1088. });
  1089. });
  1090. }
  1091. Users.after.insert((userId, doc) => {
  1092. if (doc.createdThroughApi) {
  1093. // The admin user should be able to create a user despite disabling registration because
  1094. // it is two different things (registration and creation).
  1095. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1096. // the disableRegistration check.
  1097. // Issue : https://github.com/wekan/wekan/issues/1232
  1098. // PR : https://github.com/wekan/wekan/pull/1251
  1099. Users.update(doc._id, { $set: { createdThroughApi: '' } });
  1100. return;
  1101. }
  1102. //invite user to corresponding boards
  1103. const disableRegistration = Settings.findOne().disableRegistration;
  1104. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1105. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1106. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1107. const invitationCode = InvitationCodes.findOne({
  1108. code: doc.profile.icode,
  1109. valid: true,
  1110. });
  1111. if (!invitationCode) {
  1112. throw new Meteor.Error('error-invitation-code-not-exist');
  1113. } else {
  1114. invitationCode.boardsToBeInvited.forEach(boardId => {
  1115. const board = Boards.findOne(boardId);
  1116. board.addMember(doc._id);
  1117. });
  1118. if (!doc.profile) {
  1119. doc.profile = {};
  1120. }
  1121. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1122. Users.update(doc._id, { $set: { profile: doc.profile } });
  1123. InvitationCodes.update(invitationCode._id, { $set: { valid: false } });
  1124. }
  1125. }
  1126. });
  1127. }
  1128. // USERS REST API
  1129. if (Meteor.isServer) {
  1130. // Middleware which checks that API is enabled.
  1131. JsonRoutes.Middleware.use(function(req, res, next) {
  1132. const api = req.url.startsWith('/api');
  1133. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1134. return next();
  1135. } else {
  1136. res.writeHead(301, { Location: '/' });
  1137. return res.end();
  1138. }
  1139. });
  1140. /**
  1141. * @operation get_current_user
  1142. *
  1143. * @summary returns the current user
  1144. * @return_type Users
  1145. */
  1146. JsonRoutes.add('GET', '/api/user', function(req, res) {
  1147. try {
  1148. Authentication.checkLoggedIn(req.userId);
  1149. const data = Meteor.users.findOne({ _id: req.userId });
  1150. delete data.services;
  1151. // get all boards where the user is member of
  1152. let boards = Boards.find(
  1153. {
  1154. type: 'board',
  1155. 'members.userId': req.userId,
  1156. },
  1157. {
  1158. fields: { _id: 1, members: 1 },
  1159. },
  1160. );
  1161. boards = boards.map(b => {
  1162. const u = b.members.find(m => m.userId === req.userId);
  1163. delete u.userId;
  1164. u.boardId = b._id;
  1165. return u;
  1166. });
  1167. data.boards = boards;
  1168. JsonRoutes.sendResult(res, {
  1169. code: 200,
  1170. data,
  1171. });
  1172. } catch (error) {
  1173. JsonRoutes.sendResult(res, {
  1174. code: 200,
  1175. data: error,
  1176. });
  1177. }
  1178. });
  1179. /**
  1180. * @operation get_all_users
  1181. *
  1182. * @summary return all the users
  1183. *
  1184. * @description Only the admin user (the first user) can call the REST API.
  1185. * @return_type [{ _id: string,
  1186. * username: string}]
  1187. */
  1188. JsonRoutes.add('GET', '/api/users', function(req, res) {
  1189. try {
  1190. Authentication.checkUserId(req.userId);
  1191. JsonRoutes.sendResult(res, {
  1192. code: 200,
  1193. data: Meteor.users.find({}).map(function(doc) {
  1194. return { _id: doc._id, username: doc.username };
  1195. }),
  1196. });
  1197. } catch (error) {
  1198. JsonRoutes.sendResult(res, {
  1199. code: 200,
  1200. data: error,
  1201. });
  1202. }
  1203. });
  1204. /**
  1205. * @operation get_user
  1206. *
  1207. * @summary get a given user
  1208. *
  1209. * @description Only the admin user (the first user) can call the REST API.
  1210. *
  1211. * @param {string} userId the user ID
  1212. * @return_type Users
  1213. */
  1214. JsonRoutes.add('GET', '/api/users/:userId', function(req, res) {
  1215. try {
  1216. Authentication.checkUserId(req.userId);
  1217. const id = req.params.userId;
  1218. // get all boards where the user is member of
  1219. let boards = Boards.find(
  1220. {
  1221. type: 'board',
  1222. 'members.userId': id,
  1223. },
  1224. {
  1225. fields: { _id: 1, members: 1 },
  1226. },
  1227. );
  1228. boards = boards.map(b => {
  1229. const u = b.members.find(m => m.userId === id);
  1230. delete u.userId;
  1231. u.boardId = b._id;
  1232. return u;
  1233. });
  1234. const user = Meteor.users.findOne({ _id: id });
  1235. user.boards = boards;
  1236. JsonRoutes.sendResult(res, {
  1237. code: 200,
  1238. data: user,
  1239. });
  1240. } catch (error) {
  1241. JsonRoutes.sendResult(res, {
  1242. code: 200,
  1243. data: error,
  1244. });
  1245. }
  1246. });
  1247. /**
  1248. * @operation edit_user
  1249. *
  1250. * @summary edit a given user
  1251. *
  1252. * @description Only the admin user (the first user) can call the REST API.
  1253. *
  1254. * Possible values for *action*:
  1255. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1256. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1257. * - `enableLogin`: Enable a user
  1258. *
  1259. * @param {string} userId the user ID
  1260. * @param {string} action the action
  1261. * @return_type {_id: string,
  1262. * title: string}
  1263. */
  1264. JsonRoutes.add('PUT', '/api/users/:userId', function(req, res) {
  1265. try {
  1266. Authentication.checkUserId(req.userId);
  1267. const id = req.params.userId;
  1268. const action = req.body.action;
  1269. let data = Meteor.users.findOne({ _id: id });
  1270. if (data !== undefined) {
  1271. if (action === 'takeOwnership') {
  1272. data = Boards.find(
  1273. {
  1274. 'members.userId': id,
  1275. 'members.isAdmin': true,
  1276. },
  1277. { sort: { sort: 1 /* boards default sorting */ } },
  1278. ).map(function(board) {
  1279. if (board.hasMember(req.userId)) {
  1280. board.removeMember(req.userId);
  1281. }
  1282. board.changeOwnership(id, req.userId);
  1283. return {
  1284. _id: board._id,
  1285. title: board.title,
  1286. };
  1287. });
  1288. } else {
  1289. if (action === 'disableLogin' && id !== req.userId) {
  1290. Users.update(
  1291. { _id: id },
  1292. {
  1293. $set: {
  1294. loginDisabled: true,
  1295. 'services.resume.loginTokens': '',
  1296. },
  1297. },
  1298. );
  1299. } else if (action === 'enableLogin') {
  1300. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  1301. }
  1302. data = Meteor.users.findOne({ _id: id });
  1303. }
  1304. }
  1305. JsonRoutes.sendResult(res, {
  1306. code: 200,
  1307. data,
  1308. });
  1309. } catch (error) {
  1310. JsonRoutes.sendResult(res, {
  1311. code: 200,
  1312. data: error,
  1313. });
  1314. }
  1315. });
  1316. /**
  1317. * @operation add_board_member
  1318. * @tag Boards
  1319. *
  1320. * @summary Add New Board Member with Role
  1321. *
  1322. * @description Only the admin user (the first user) can call the REST API.
  1323. *
  1324. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1325. * to later change the permissions.
  1326. *
  1327. * @param {string} boardId the board ID
  1328. * @param {string} userId the user ID
  1329. * @param {boolean} isAdmin is the user an admin of the board
  1330. * @param {boolean} isNoComments disable comments
  1331. * @param {boolean} isCommentOnly only enable comments
  1332. * @return_type {_id: string,
  1333. * title: string}
  1334. */
  1335. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function(
  1336. req,
  1337. res,
  1338. ) {
  1339. try {
  1340. Authentication.checkUserId(req.userId);
  1341. const userId = req.params.userId;
  1342. const boardId = req.params.boardId;
  1343. const action = req.body.action;
  1344. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1345. let data = Meteor.users.findOne({ _id: userId });
  1346. if (data !== undefined) {
  1347. if (action === 'add') {
  1348. data = Boards.find({
  1349. _id: boardId,
  1350. }).map(function(board) {
  1351. if (!board.hasMember(userId)) {
  1352. board.addMember(userId);
  1353. function isTrue(data) {
  1354. return data.toLowerCase() === 'true';
  1355. }
  1356. board.setMemberPermission(
  1357. userId,
  1358. isTrue(isAdmin),
  1359. isTrue(isNoComments),
  1360. isTrue(isCommentOnly),
  1361. userId,
  1362. );
  1363. }
  1364. return {
  1365. _id: board._id,
  1366. title: board.title,
  1367. };
  1368. });
  1369. }
  1370. }
  1371. JsonRoutes.sendResult(res, {
  1372. code: 200,
  1373. data: query,
  1374. });
  1375. } catch (error) {
  1376. JsonRoutes.sendResult(res, {
  1377. code: 200,
  1378. data: error,
  1379. });
  1380. }
  1381. });
  1382. /**
  1383. * @operation remove_board_member
  1384. * @tag Boards
  1385. *
  1386. * @summary Remove Member from Board
  1387. *
  1388. * @description Only the admin user (the first user) can call the REST API.
  1389. *
  1390. * @param {string} boardId the board ID
  1391. * @param {string} userId the user ID
  1392. * @param {string} action the action (needs to be `remove`)
  1393. * @return_type {_id: string,
  1394. * title: string}
  1395. */
  1396. JsonRoutes.add(
  1397. 'POST',
  1398. '/api/boards/:boardId/members/:userId/remove',
  1399. function(req, res) {
  1400. try {
  1401. Authentication.checkUserId(req.userId);
  1402. const userId = req.params.userId;
  1403. const boardId = req.params.boardId;
  1404. const action = req.body.action;
  1405. let data = Meteor.users.findOne({ _id: userId });
  1406. if (data !== undefined) {
  1407. if (action === 'remove') {
  1408. data = Boards.find({
  1409. _id: boardId,
  1410. }).map(function(board) {
  1411. if (board.hasMember(userId)) {
  1412. board.removeMember(userId);
  1413. }
  1414. return {
  1415. _id: board._id,
  1416. title: board.title,
  1417. };
  1418. });
  1419. }
  1420. }
  1421. JsonRoutes.sendResult(res, {
  1422. code: 200,
  1423. data: query,
  1424. });
  1425. } catch (error) {
  1426. JsonRoutes.sendResult(res, {
  1427. code: 200,
  1428. data: error,
  1429. });
  1430. }
  1431. },
  1432. );
  1433. /**
  1434. * @operation new_user
  1435. *
  1436. * @summary Create a new user
  1437. *
  1438. * @description Only the admin user (the first user) can call the REST API.
  1439. *
  1440. * @param {string} username the new username
  1441. * @param {string} email the email of the new user
  1442. * @param {string} password the password of the new user
  1443. * @return_type {_id: string}
  1444. */
  1445. JsonRoutes.add('POST', '/api/users/', function(req, res) {
  1446. try {
  1447. Authentication.checkUserId(req.userId);
  1448. const id = Accounts.createUser({
  1449. username: req.body.username,
  1450. email: req.body.email,
  1451. password: req.body.password,
  1452. from: 'admin',
  1453. });
  1454. JsonRoutes.sendResult(res, {
  1455. code: 200,
  1456. data: {
  1457. _id: id,
  1458. },
  1459. });
  1460. } catch (error) {
  1461. JsonRoutes.sendResult(res, {
  1462. code: 200,
  1463. data: error,
  1464. });
  1465. }
  1466. });
  1467. /**
  1468. * @operation delete_user
  1469. *
  1470. * @summary Delete a user
  1471. *
  1472. * @description Only the admin user (the first user) can call the REST API.
  1473. *
  1474. * @param {string} userId the ID of the user to delete
  1475. * @return_type {_id: string}
  1476. */
  1477. JsonRoutes.add('DELETE', '/api/users/:userId', function(req, res) {
  1478. try {
  1479. Authentication.checkUserId(req.userId);
  1480. const id = req.params.userId;
  1481. Meteor.users.remove({ _id: id });
  1482. JsonRoutes.sendResult(res, {
  1483. code: 200,
  1484. data: {
  1485. _id: id,
  1486. },
  1487. });
  1488. } catch (error) {
  1489. JsonRoutes.sendResult(res, {
  1490. code: 200,
  1491. data: error,
  1492. });
  1493. }
  1494. });
  1495. }
  1496. export default Users;