users.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  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. });
  845. Accounts.onCreateUser((options, user) => {
  846. const userCount = Users.find().count();
  847. if (userCount === 0) {
  848. user.isAdmin = true;
  849. return user;
  850. }
  851. if (user.services.oidc) {
  852. let email = user.services.oidc.email;
  853. if (Array.isArray(email)) {
  854. email = email.shift();
  855. }
  856. email = email.toLowerCase();
  857. user.username = user.services.oidc.username;
  858. user.emails = [{ address: email, verified: true }];
  859. const initials = user.services.oidc.fullname
  860. .match(/\b[a-zA-Z]/g)
  861. .join('')
  862. .toUpperCase();
  863. user.profile = {
  864. initials,
  865. fullname: user.services.oidc.fullname,
  866. boardView: 'board-view-swimlanes',
  867. };
  868. user.authenticationMethod = 'oauth2';
  869. // see if any existing user has this email address or username, otherwise create new
  870. const existingUser = Meteor.users.findOne({
  871. $or: [{ 'emails.address': email }, { username: user.username }],
  872. });
  873. if (!existingUser) return user;
  874. // copy across new service info
  875. const service = _.keys(user.services)[0];
  876. existingUser.services[service] = user.services[service];
  877. existingUser.emails = user.emails;
  878. existingUser.username = user.username;
  879. existingUser.profile = user.profile;
  880. existingUser.authenticationMethod = user.authenticationMethod;
  881. Meteor.users.remove({ _id: existingUser._id }); // remove existing record
  882. return existingUser;
  883. }
  884. if (options.from === 'admin') {
  885. user.createdThroughApi = true;
  886. return user;
  887. }
  888. const disableRegistration = Settings.findOne().disableRegistration;
  889. // If this is the first Authentication by the ldap and self registration disabled
  890. if (disableRegistration && options && options.ldap) {
  891. user.authenticationMethod = 'ldap';
  892. return user;
  893. }
  894. // If self registration enabled
  895. if (!disableRegistration) {
  896. return user;
  897. }
  898. if (!options || !options.profile) {
  899. throw new Meteor.Error(
  900. 'error-invitation-code-blank',
  901. 'The invitation code is required',
  902. );
  903. }
  904. const invitationCode = InvitationCodes.findOne({
  905. code: options.profile.invitationcode,
  906. email: options.email,
  907. valid: true,
  908. });
  909. if (!invitationCode) {
  910. throw new Meteor.Error(
  911. 'error-invitation-code-not-exist',
  912. // eslint-disable-next-line quotes
  913. "The invitation code doesn't exist",
  914. );
  915. } else {
  916. user.profile = { icode: options.profile.invitationcode };
  917. user.profile.boardView = 'board-view-swimlanes';
  918. // Deletes the invitation code after the user was created successfully.
  919. setTimeout(
  920. Meteor.bindEnvironment(() => {
  921. InvitationCodes.remove({ _id: invitationCode._id });
  922. }),
  923. 200,
  924. );
  925. return user;
  926. }
  927. });
  928. }
  929. const addCronJob = _.debounce(
  930. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  931. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  932. const envRemoveAge =
  933. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  934. // default notifications will be removed 2 days after they are read
  935. const defaultRemoveAge = 2;
  936. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  937. SyncedCron.add({
  938. name: 'notification_cleanup',
  939. schedule: parser => parser.text('every 1 days'),
  940. job: () => {
  941. for (const user of Users.find()) {
  942. if (!user.profile || !user.profile.notifications) continue;
  943. for (const notification of user.profile.notifications) {
  944. if (notification.read) {
  945. const removeDate = new Date(notification.read);
  946. removeDate.setDate(removeDate.getDate() + removeAge);
  947. if (removeDate <= new Date()) {
  948. user.removeNotification(notification.activity);
  949. }
  950. }
  951. }
  952. }
  953. },
  954. });
  955. SyncedCron.start();
  956. }),
  957. 500,
  958. );
  959. if (Meteor.isServer) {
  960. // Let mongoDB ensure username unicity
  961. Meteor.startup(() => {
  962. allowedSortValues.forEach(value => {
  963. Lists._collection._ensureIndex(value);
  964. });
  965. Users._collection._ensureIndex({ modifiedAt: -1 });
  966. Users._collection._ensureIndex(
  967. {
  968. username: 1,
  969. },
  970. { unique: true },
  971. );
  972. Meteor.defer(() => {
  973. addCronJob();
  974. });
  975. });
  976. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  977. // if admin is removed, board is removed.
  978. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  979. // to use that board, and not have board deleted.
  980. // Someone can be later changed to be admin of board, by making change to database.
  981. // TODO: Add UI for changing someone as board admin.
  982. //Users.before.remove((userId, doc) => {
  983. // Boards
  984. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  985. // .forEach((board) => {
  986. // // If only one admin for the board
  987. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  988. // Boards.remove(board._id);
  989. // }
  990. // });
  991. //});
  992. // Each board document contains the de-normalized number of users that have
  993. // starred it. If the user star or unstar a board, we need to update this
  994. // counter.
  995. // We need to run this code on the server only, otherwise the incrementation
  996. // will be done twice.
  997. Users.after.update(function(userId, user, fieldNames) {
  998. // The `starredBoards` list is hosted on the `profile` field. If this
  999. // field hasn't been modificated we don't need to run this hook.
  1000. if (!_.contains(fieldNames, 'profile')) return;
  1001. // To calculate a diff of board starred ids, we get both the previous
  1002. // and the newly board ids list
  1003. function getStarredBoardsIds(doc) {
  1004. return doc.profile && doc.profile.starredBoards;
  1005. }
  1006. const oldIds = getStarredBoardsIds(this.previous);
  1007. const newIds = getStarredBoardsIds(user);
  1008. // The _.difference(a, b) method returns the values from a that are not in
  1009. // b. We use it to find deleted and newly inserted ids by using it in one
  1010. // direction and then in the other.
  1011. function incrementBoards(boardsIds, inc) {
  1012. boardsIds.forEach(boardId => {
  1013. Boards.update(boardId, { $inc: { stars: inc } });
  1014. });
  1015. }
  1016. incrementBoards(_.difference(oldIds, newIds), -1);
  1017. incrementBoards(_.difference(newIds, oldIds), +1);
  1018. });
  1019. // Override getUserId so that we can TODO get the current userId
  1020. const fakeUserId = new Meteor.EnvironmentVariable();
  1021. const getUserId = CollectionHooks.getUserId;
  1022. CollectionHooks.getUserId = () => {
  1023. return fakeUserId.get() || getUserId();
  1024. };
  1025. if (!isSandstorm) {
  1026. Users.after.insert((userId, doc) => {
  1027. const fakeUser = {
  1028. extendAutoValueContext: {
  1029. userId: doc._id,
  1030. },
  1031. };
  1032. fakeUserId.withValue(doc._id, () => {
  1033. /*
  1034. // Insert the Welcome Board
  1035. Boards.insert({
  1036. title: TAPi18n.__('welcome-board'),
  1037. permission: 'private',
  1038. }, fakeUser, (err, boardId) => {
  1039. Swimlanes.insert({
  1040. title: TAPi18n.__('welcome-swimlane'),
  1041. boardId,
  1042. sort: 1,
  1043. }, fakeUser);
  1044. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1045. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1046. });
  1047. });
  1048. */
  1049. const Future = require('fibers/future');
  1050. let future1 = new Future();
  1051. let future2 = new Future();
  1052. let future3 = new Future();
  1053. Boards.insert(
  1054. {
  1055. title: TAPi18n.__('templates'),
  1056. permission: 'private',
  1057. type: 'template-container',
  1058. },
  1059. fakeUser,
  1060. (err, boardId) => {
  1061. // Insert the reference to our templates board
  1062. Users.update(fakeUserId.get(), {
  1063. $set: { 'profile.templatesBoardId': boardId },
  1064. });
  1065. // Insert the card templates swimlane
  1066. Swimlanes.insert(
  1067. {
  1068. title: TAPi18n.__('card-templates-swimlane'),
  1069. boardId,
  1070. sort: 1,
  1071. type: 'template-container',
  1072. },
  1073. fakeUser,
  1074. (err, swimlaneId) => {
  1075. // Insert the reference to out card templates swimlane
  1076. Users.update(fakeUserId.get(), {
  1077. $set: { 'profile.cardTemplatesSwimlaneId': swimlaneId },
  1078. });
  1079. future1.return();
  1080. },
  1081. );
  1082. // Insert the list templates swimlane
  1083. Swimlanes.insert(
  1084. {
  1085. title: TAPi18n.__('list-templates-swimlane'),
  1086. boardId,
  1087. sort: 2,
  1088. type: 'template-container',
  1089. },
  1090. fakeUser,
  1091. (err, swimlaneId) => {
  1092. // Insert the reference to out list templates swimlane
  1093. Users.update(fakeUserId.get(), {
  1094. $set: { 'profile.listTemplatesSwimlaneId': swimlaneId },
  1095. });
  1096. future2.return();
  1097. },
  1098. );
  1099. // Insert the board templates swimlane
  1100. Swimlanes.insert(
  1101. {
  1102. title: TAPi18n.__('board-templates-swimlane'),
  1103. boardId,
  1104. sort: 3,
  1105. type: 'template-container',
  1106. },
  1107. fakeUser,
  1108. (err, swimlaneId) => {
  1109. // Insert the reference to out board templates swimlane
  1110. Users.update(fakeUserId.get(), {
  1111. $set: { 'profile.boardTemplatesSwimlaneId': swimlaneId },
  1112. });
  1113. future3.return();
  1114. },
  1115. );
  1116. },
  1117. );
  1118. // HACK
  1119. future1.wait();
  1120. future2.wait();
  1121. future3.wait();
  1122. });
  1123. });
  1124. }
  1125. Users.after.insert((userId, doc) => {
  1126. // HACK
  1127. doc = Users.findOne({ _id: doc._id });
  1128. if (doc.createdThroughApi) {
  1129. // The admin user should be able to create a user despite disabling registration because
  1130. // it is two different things (registration and creation).
  1131. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1132. // the disableRegistration check.
  1133. // Issue : https://github.com/wekan/wekan/issues/1232
  1134. // PR : https://github.com/wekan/wekan/pull/1251
  1135. Users.update(doc._id, { $set: { createdThroughApi: '' } });
  1136. return;
  1137. }
  1138. //invite user to corresponding boards
  1139. const disableRegistration = Settings.findOne().disableRegistration;
  1140. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1141. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1142. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1143. const invitationCode = InvitationCodes.findOne({
  1144. code: doc.profile.icode,
  1145. valid: true,
  1146. });
  1147. if (!invitationCode) {
  1148. throw new Meteor.Error('error-invitation-code-not-exist');
  1149. } else {
  1150. invitationCode.boardsToBeInvited.forEach(boardId => {
  1151. const board = Boards.findOne(boardId);
  1152. board.addMember(doc._id);
  1153. });
  1154. if (!doc.profile) {
  1155. doc.profile = {};
  1156. }
  1157. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1158. Users.update(doc._id, { $set: { profile: doc.profile } });
  1159. InvitationCodes.update(invitationCode._id, { $set: { valid: false } });
  1160. }
  1161. }
  1162. });
  1163. }
  1164. // USERS REST API
  1165. if (Meteor.isServer) {
  1166. // Middleware which checks that API is enabled.
  1167. JsonRoutes.Middleware.use(function(req, res, next) {
  1168. const api = req.url.startsWith('/api');
  1169. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1170. return next();
  1171. } else {
  1172. res.writeHead(301, { Location: '/' });
  1173. return res.end();
  1174. }
  1175. });
  1176. /**
  1177. * @operation get_current_user
  1178. *
  1179. * @summary returns the current user
  1180. * @return_type Users
  1181. */
  1182. JsonRoutes.add('GET', '/api/user', function(req, res) {
  1183. try {
  1184. Authentication.checkLoggedIn(req.userId);
  1185. const data = Meteor.users.findOne({ _id: req.userId });
  1186. delete data.services;
  1187. // get all boards where the user is member of
  1188. let boards = Boards.find(
  1189. {
  1190. type: 'board',
  1191. 'members.userId': req.userId,
  1192. },
  1193. {
  1194. fields: { _id: 1, members: 1 },
  1195. },
  1196. );
  1197. boards = boards.map(b => {
  1198. const u = b.members.find(m => m.userId === req.userId);
  1199. delete u.userId;
  1200. u.boardId = b._id;
  1201. return u;
  1202. });
  1203. data.boards = boards;
  1204. JsonRoutes.sendResult(res, {
  1205. code: 200,
  1206. data,
  1207. });
  1208. } catch (error) {
  1209. JsonRoutes.sendResult(res, {
  1210. code: 200,
  1211. data: error,
  1212. });
  1213. }
  1214. });
  1215. /**
  1216. * @operation get_all_users
  1217. *
  1218. * @summary return all the users
  1219. *
  1220. * @description Only the admin user (the first user) can call the REST API.
  1221. * @return_type [{ _id: string,
  1222. * username: string}]
  1223. */
  1224. JsonRoutes.add('GET', '/api/users', function(req, res) {
  1225. try {
  1226. Authentication.checkUserId(req.userId);
  1227. JsonRoutes.sendResult(res, {
  1228. code: 200,
  1229. data: Meteor.users.find({}).map(function(doc) {
  1230. return { _id: doc._id, username: doc.username };
  1231. }),
  1232. });
  1233. } catch (error) {
  1234. JsonRoutes.sendResult(res, {
  1235. code: 200,
  1236. data: error,
  1237. });
  1238. }
  1239. });
  1240. /**
  1241. * @operation get_user
  1242. *
  1243. * @summary get a given user
  1244. *
  1245. * @description Only the admin user (the first user) can call the REST API.
  1246. *
  1247. * @param {string} userId the user ID
  1248. * @return_type Users
  1249. */
  1250. JsonRoutes.add('GET', '/api/users/:userId', function(req, res) {
  1251. try {
  1252. Authentication.checkUserId(req.userId);
  1253. const id = req.params.userId;
  1254. // get all boards where the user is member of
  1255. let boards = Boards.find(
  1256. {
  1257. type: 'board',
  1258. 'members.userId': id,
  1259. },
  1260. {
  1261. fields: { _id: 1, members: 1 },
  1262. },
  1263. );
  1264. boards = boards.map(b => {
  1265. const u = b.members.find(m => m.userId === id);
  1266. delete u.userId;
  1267. u.boardId = b._id;
  1268. return u;
  1269. });
  1270. const user = Meteor.users.findOne({ _id: id });
  1271. user.boards = boards;
  1272. JsonRoutes.sendResult(res, {
  1273. code: 200,
  1274. data: user,
  1275. });
  1276. } catch (error) {
  1277. JsonRoutes.sendResult(res, {
  1278. code: 200,
  1279. data: error,
  1280. });
  1281. }
  1282. });
  1283. /**
  1284. * @operation edit_user
  1285. *
  1286. * @summary edit a given user
  1287. *
  1288. * @description Only the admin user (the first user) can call the REST API.
  1289. *
  1290. * Possible values for *action*:
  1291. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1292. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1293. * - `enableLogin`: Enable a user
  1294. *
  1295. * @param {string} userId the user ID
  1296. * @param {string} action the action
  1297. * @return_type {_id: string,
  1298. * title: string}
  1299. */
  1300. JsonRoutes.add('PUT', '/api/users/:userId', function(req, res) {
  1301. try {
  1302. Authentication.checkUserId(req.userId);
  1303. const id = req.params.userId;
  1304. const action = req.body.action;
  1305. let data = Meteor.users.findOne({ _id: id });
  1306. if (data !== undefined) {
  1307. if (action === 'takeOwnership') {
  1308. data = Boards.find(
  1309. {
  1310. 'members.userId': id,
  1311. 'members.isAdmin': true,
  1312. },
  1313. { sort: { sort: 1 /* boards default sorting */ } },
  1314. ).map(function(board) {
  1315. if (board.hasMember(req.userId)) {
  1316. board.removeMember(req.userId);
  1317. }
  1318. board.changeOwnership(id, req.userId);
  1319. return {
  1320. _id: board._id,
  1321. title: board.title,
  1322. };
  1323. });
  1324. } else {
  1325. if (action === 'disableLogin' && id !== req.userId) {
  1326. Users.update(
  1327. { _id: id },
  1328. {
  1329. $set: {
  1330. loginDisabled: true,
  1331. 'services.resume.loginTokens': '',
  1332. },
  1333. },
  1334. );
  1335. } else if (action === 'enableLogin') {
  1336. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  1337. }
  1338. data = Meteor.users.findOne({ _id: id });
  1339. }
  1340. }
  1341. JsonRoutes.sendResult(res, {
  1342. code: 200,
  1343. data,
  1344. });
  1345. } catch (error) {
  1346. JsonRoutes.sendResult(res, {
  1347. code: 200,
  1348. data: error,
  1349. });
  1350. }
  1351. });
  1352. /**
  1353. * @operation add_board_member
  1354. * @tag Boards
  1355. *
  1356. * @summary Add New Board Member with Role
  1357. *
  1358. * @description Only the admin user (the first user) can call the REST API.
  1359. *
  1360. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1361. * to later change the permissions.
  1362. *
  1363. * @param {string} boardId the board ID
  1364. * @param {string} userId the user ID
  1365. * @param {boolean} isAdmin is the user an admin of the board
  1366. * @param {boolean} isNoComments disable comments
  1367. * @param {boolean} isCommentOnly only enable comments
  1368. * @return_type {_id: string,
  1369. * title: string}
  1370. */
  1371. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function(
  1372. req,
  1373. res,
  1374. ) {
  1375. try {
  1376. Authentication.checkUserId(req.userId);
  1377. const userId = req.params.userId;
  1378. const boardId = req.params.boardId;
  1379. const action = req.body.action;
  1380. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1381. let data = Meteor.users.findOne({ _id: userId });
  1382. if (data !== undefined) {
  1383. if (action === 'add') {
  1384. data = Boards.find({
  1385. _id: boardId,
  1386. }).map(function(board) {
  1387. if (!board.hasMember(userId)) {
  1388. board.addMember(userId);
  1389. function isTrue(data) {
  1390. return data.toLowerCase() === 'true';
  1391. }
  1392. board.setMemberPermission(
  1393. userId,
  1394. isTrue(isAdmin),
  1395. isTrue(isNoComments),
  1396. isTrue(isCommentOnly),
  1397. userId,
  1398. );
  1399. }
  1400. return {
  1401. _id: board._id,
  1402. title: board.title,
  1403. };
  1404. });
  1405. }
  1406. }
  1407. JsonRoutes.sendResult(res, {
  1408. code: 200,
  1409. data: query,
  1410. });
  1411. } catch (error) {
  1412. JsonRoutes.sendResult(res, {
  1413. code: 200,
  1414. data: error,
  1415. });
  1416. }
  1417. });
  1418. /**
  1419. * @operation remove_board_member
  1420. * @tag Boards
  1421. *
  1422. * @summary Remove Member from Board
  1423. *
  1424. * @description Only the admin user (the first user) can call the REST API.
  1425. *
  1426. * @param {string} boardId the board ID
  1427. * @param {string} userId the user ID
  1428. * @param {string} action the action (needs to be `remove`)
  1429. * @return_type {_id: string,
  1430. * title: string}
  1431. */
  1432. JsonRoutes.add(
  1433. 'POST',
  1434. '/api/boards/:boardId/members/:userId/remove',
  1435. function(req, res) {
  1436. try {
  1437. Authentication.checkUserId(req.userId);
  1438. const userId = req.params.userId;
  1439. const boardId = req.params.boardId;
  1440. const action = req.body.action;
  1441. let data = Meteor.users.findOne({ _id: userId });
  1442. if (data !== undefined) {
  1443. if (action === 'remove') {
  1444. data = Boards.find({
  1445. _id: boardId,
  1446. }).map(function(board) {
  1447. if (board.hasMember(userId)) {
  1448. board.removeMember(userId);
  1449. }
  1450. return {
  1451. _id: board._id,
  1452. title: board.title,
  1453. };
  1454. });
  1455. }
  1456. }
  1457. JsonRoutes.sendResult(res, {
  1458. code: 200,
  1459. data: query,
  1460. });
  1461. } catch (error) {
  1462. JsonRoutes.sendResult(res, {
  1463. code: 200,
  1464. data: error,
  1465. });
  1466. }
  1467. },
  1468. );
  1469. /**
  1470. * @operation new_user
  1471. *
  1472. * @summary Create a new user
  1473. *
  1474. * @description Only the admin user (the first user) can call the REST API.
  1475. *
  1476. * @param {string} username the new username
  1477. * @param {string} email the email of the new user
  1478. * @param {string} password the password of the new user
  1479. * @return_type {_id: string}
  1480. */
  1481. JsonRoutes.add('POST', '/api/users/', function(req, res) {
  1482. try {
  1483. Authentication.checkUserId(req.userId);
  1484. const id = Accounts.createUser({
  1485. username: req.body.username,
  1486. email: req.body.email,
  1487. password: req.body.password,
  1488. from: 'admin',
  1489. });
  1490. JsonRoutes.sendResult(res, {
  1491. code: 200,
  1492. data: {
  1493. _id: id,
  1494. },
  1495. });
  1496. } catch (error) {
  1497. JsonRoutes.sendResult(res, {
  1498. code: 200,
  1499. data: error,
  1500. });
  1501. }
  1502. });
  1503. /**
  1504. * @operation delete_user
  1505. *
  1506. * @summary Delete a user
  1507. *
  1508. * @description Only the admin user (the first user) can call the REST API.
  1509. *
  1510. * @param {string} userId the ID of the user to delete
  1511. * @return_type {_id: string}
  1512. */
  1513. JsonRoutes.add('DELETE', '/api/users/:userId', function(req, res) {
  1514. try {
  1515. Authentication.checkUserId(req.userId);
  1516. const id = req.params.userId;
  1517. Meteor.users.remove({ _id: id });
  1518. JsonRoutes.sendResult(res, {
  1519. code: 200,
  1520. data: {
  1521. _id: id,
  1522. },
  1523. });
  1524. } catch (error) {
  1525. JsonRoutes.sendResult(res, {
  1526. code: 200,
  1527. data: error,
  1528. });
  1529. }
  1530. });
  1531. }
  1532. export default Users;