users.js 43 KB

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