users.js 42 KB

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