users.js 43 KB

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