users.js 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  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. setName(value) {
  576. return {
  577. $set: {
  578. 'profile.fullname': value,
  579. },
  580. };
  581. },
  582. toggleDesktopHandles(value = false) {
  583. return {
  584. $set: {
  585. 'profile.showDesktopDragHandles': !value,
  586. },
  587. };
  588. },
  589. toggleHideCheckedItems() {
  590. const value = this.hasHideCheckedItems();
  591. return {
  592. $set: {
  593. 'profile.hideCheckedItems': !value,
  594. },
  595. };
  596. },
  597. toggleSystem(value = false) {
  598. return {
  599. $set: {
  600. 'profile.hiddenSystemMessages': !value,
  601. },
  602. };
  603. },
  604. toggleLabelText(value = false) {
  605. return {
  606. $set: {
  607. 'profile.hiddenMinicardLabelText': !value,
  608. },
  609. };
  610. },
  611. addNotification(activityId) {
  612. return {
  613. $addToSet: {
  614. 'profile.notifications': { activity: activityId },
  615. },
  616. };
  617. },
  618. removeNotification(activityId) {
  619. return {
  620. $pull: {
  621. 'profile.notifications': { activity: activityId },
  622. },
  623. };
  624. },
  625. addEmailBuffer(text) {
  626. return {
  627. $addToSet: {
  628. 'profile.emailBuffer': text,
  629. },
  630. };
  631. },
  632. clearEmailBuffer() {
  633. return {
  634. $set: {
  635. 'profile.emailBuffer': [],
  636. },
  637. };
  638. },
  639. setAvatarUrl(avatarUrl) {
  640. return { $set: { 'profile.avatarUrl': avatarUrl } };
  641. },
  642. setShowCardsCountAt(limit) {
  643. return { $set: { 'profile.showCardsCountAt': limit } };
  644. },
  645. setStartDayOfWeek(startDay) {
  646. return { $set: { 'profile.startDayOfWeek': startDay } };
  647. },
  648. setBoardView(view) {
  649. return {
  650. $set: {
  651. 'profile.boardView': view,
  652. },
  653. };
  654. },
  655. });
  656. Meteor.methods({
  657. setListSortBy(value) {
  658. check(value, String);
  659. Meteor.user().setListSortBy(value);
  660. },
  661. toggleDesktopDragHandles() {
  662. const user = Meteor.user();
  663. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  664. },
  665. toggleHideCheckedItems() {
  666. const user = Meteor.user();
  667. user.toggleHideCheckedItems();
  668. },
  669. toggleSystemMessages() {
  670. const user = Meteor.user();
  671. user.toggleSystem(user.hasHiddenSystemMessages());
  672. },
  673. toggleMinicardLabelText() {
  674. const user = Meteor.user();
  675. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  676. },
  677. changeLimitToShowCardsCount(limit) {
  678. check(limit, Number);
  679. Meteor.user().setShowCardsCountAt(limit);
  680. },
  681. changeStartDayOfWeek(startDay) {
  682. check(startDay, Number);
  683. Meteor.user().setStartDayOfWeek(startDay);
  684. },
  685. });
  686. if (Meteor.isServer) {
  687. Meteor.methods({
  688. setCreateUser(fullname, username, password, isAdmin, isActive, email) {
  689. if (Meteor.user() && Meteor.user().isAdmin) {
  690. check(fullname, String);
  691. check(username, String);
  692. check(password, String);
  693. check(isAdmin, String);
  694. check(isActive, String);
  695. check(email, String);
  696. const nUsersWithUsername = Users.find({ username }).count();
  697. const nUsersWithEmail = Users.find({ email }).count();
  698. if (nUsersWithUsername > 0) {
  699. throw new Meteor.Error('username-already-taken');
  700. } else if (nUsersWithEmail > 0) {
  701. throw new Meteor.Error('email-already-taken');
  702. } else {
  703. Accounts.createUser({
  704. username,
  705. password,
  706. isAdmin,
  707. isActive,
  708. email: email.toLowerCase(),
  709. from: 'admin',
  710. });
  711. user = Users.findOne(username) || Users.findOne({ username });
  712. if (user) {
  713. Users.update(user._id, {
  714. $set: { 'profile.fullname': fullname },
  715. });
  716. }
  717. }
  718. }
  719. },
  720. setUsername(username, userId) {
  721. if (Meteor.user() && Meteor.user().isAdmin) {
  722. check(username, String);
  723. check(userId, String);
  724. const nUsersWithUsername = Users.find({ username }).count();
  725. if (nUsersWithUsername > 0) {
  726. throw new Meteor.Error('username-already-taken');
  727. } else {
  728. Users.update(userId, { $set: { username } });
  729. }
  730. }
  731. },
  732. setEmail(email, userId) {
  733. if (Meteor.user() && Meteor.user().isAdmin) {
  734. if (Array.isArray(email)) {
  735. email = email.shift();
  736. }
  737. check(email, String);
  738. const existingUser = Users.findOne(
  739. { 'emails.address': email },
  740. { fields: { _id: 1 } },
  741. );
  742. if (existingUser) {
  743. throw new Meteor.Error('email-already-taken');
  744. } else {
  745. Users.update(userId, {
  746. $set: {
  747. emails: [
  748. {
  749. address: email,
  750. verified: false,
  751. },
  752. ],
  753. },
  754. });
  755. }
  756. }
  757. },
  758. setUsernameAndEmail(username, email, userId) {
  759. if (Meteor.user() && Meteor.user().isAdmin) {
  760. check(username, String);
  761. if (Array.isArray(email)) {
  762. email = email.shift();
  763. }
  764. check(email, String);
  765. check(userId, String);
  766. Meteor.call('setUsername', username, userId);
  767. Meteor.call('setEmail', email, userId);
  768. }
  769. },
  770. setPassword(newPassword, userId) {
  771. if (Meteor.user() && Meteor.user().isAdmin) {
  772. check(userId, String);
  773. check(newPassword, String);
  774. if (Meteor.user().isAdmin) {
  775. Accounts.setPassword(userId, newPassword);
  776. }
  777. }
  778. },
  779. // we accept userId, username, email
  780. inviteUserToBoard(username, boardId) {
  781. check(username, String);
  782. check(boardId, String);
  783. const inviter = Meteor.user();
  784. const board = Boards.findOne(boardId);
  785. const allowInvite =
  786. inviter &&
  787. board &&
  788. board.members &&
  789. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  790. _.where(board.members, { userId: inviter._id })[0].isActive;
  791. // GitHub issue 2060
  792. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  793. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  794. this.unblock();
  795. const posAt = username.indexOf('@');
  796. let user = null;
  797. if (posAt >= 0) {
  798. user = Users.findOne({ emails: { $elemMatch: { address: username } } });
  799. } else {
  800. user = Users.findOne(username) || Users.findOne({ username });
  801. }
  802. if (user) {
  803. if (user._id === inviter._id)
  804. throw new Meteor.Error('error-user-notAllowSelf');
  805. } else {
  806. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  807. if (Settings.findOne({ disableRegistration: true })) {
  808. throw new Meteor.Error('error-user-notCreated');
  809. }
  810. // Set in lowercase email before creating account
  811. const email = username.toLowerCase();
  812. username = email.substring(0, posAt);
  813. const newUserId = Accounts.createUser({ username, email });
  814. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  815. // assume new user speak same language with inviter
  816. if (inviter.profile && inviter.profile.language) {
  817. Users.update(newUserId, {
  818. $set: {
  819. 'profile.language': inviter.profile.language,
  820. },
  821. });
  822. }
  823. Accounts.sendEnrollmentEmail(newUserId);
  824. user = Users.findOne(newUserId);
  825. }
  826. board.addMember(user._id);
  827. user.addInvite(boardId);
  828. //Check if there is a subtasks board
  829. if (board.subtasksDefaultBoardId) {
  830. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  831. //If there is, also add user to that board
  832. if (subBoard) {
  833. subBoard.addMember(user._id);
  834. user.addInvite(subBoard._id);
  835. }
  836. }
  837. try {
  838. const params = {
  839. user: user.username,
  840. inviter: inviter.username,
  841. board: board.title,
  842. url: board.absoluteUrl(),
  843. };
  844. const lang = user.getLanguage();
  845. Email.send({
  846. to: user.emails[0].address.toLowerCase(),
  847. from: Accounts.emailTemplates.from,
  848. subject: TAPi18n.__('email-invite-subject', params, lang),
  849. text: TAPi18n.__('email-invite-text', params, lang),
  850. });
  851. } catch (e) {
  852. throw new Meteor.Error('email-fail', e.message);
  853. }
  854. return { username: user.username, email: user.emails[0].address };
  855. },
  856. impersonate(userId) {
  857. check(userId, String);
  858. if (!Meteor.users.findOne(userId))
  859. throw new Meteor.Error(404, 'User not found');
  860. if (!Meteor.user().isAdmin)
  861. throw new Meteor.Error(403, 'Permission denied');
  862. this.setUserId(userId);
  863. },
  864. });
  865. Accounts.onCreateUser((options, user) => {
  866. const userCount = Users.find().count();
  867. if (userCount === 0) {
  868. user.isAdmin = true;
  869. return user;
  870. }
  871. if (user.services.oidc) {
  872. let email = user.services.oidc.email;
  873. if (Array.isArray(email)) {
  874. email = email.shift();
  875. }
  876. email = email.toLowerCase();
  877. user.username = user.services.oidc.username;
  878. user.emails = [{ address: email, verified: true }];
  879. const initials = user.services.oidc.fullname
  880. .match(/\b[a-zA-Z]/g)
  881. .join('')
  882. .toUpperCase();
  883. user.profile = {
  884. initials,
  885. fullname: user.services.oidc.fullname,
  886. boardView: 'board-view-swimlanes',
  887. };
  888. user.authenticationMethod = 'oauth2';
  889. // see if any existing user has this email address or username, otherwise create new
  890. const existingUser = Meteor.users.findOne({
  891. $or: [{ 'emails.address': email }, { username: user.username }],
  892. });
  893. if (!existingUser) return user;
  894. // copy across new service info
  895. const service = _.keys(user.services)[0];
  896. existingUser.services[service] = user.services[service];
  897. existingUser.emails = user.emails;
  898. existingUser.username = user.username;
  899. existingUser.profile = user.profile;
  900. existingUser.authenticationMethod = user.authenticationMethod;
  901. Meteor.users.remove({ _id: user._id });
  902. Meteor.users.remove({ _id: existingUser._id }); // is going to be created again
  903. return existingUser;
  904. }
  905. if (options.from === 'admin') {
  906. user.createdThroughApi = true;
  907. return user;
  908. }
  909. const disableRegistration = Settings.findOne().disableRegistration;
  910. // If this is the first Authentication by the ldap and self registration disabled
  911. if (disableRegistration && options && options.ldap) {
  912. user.authenticationMethod = 'ldap';
  913. return user;
  914. }
  915. // If self registration enabled
  916. if (!disableRegistration) {
  917. return user;
  918. }
  919. if (!options || !options.profile) {
  920. throw new Meteor.Error(
  921. 'error-invitation-code-blank',
  922. 'The invitation code is required',
  923. );
  924. }
  925. const invitationCode = InvitationCodes.findOne({
  926. code: options.profile.invitationcode,
  927. email: options.email,
  928. valid: true,
  929. });
  930. if (!invitationCode) {
  931. throw new Meteor.Error(
  932. 'error-invitation-code-not-exist',
  933. // eslint-disable-next-line quotes
  934. "The invitation code doesn't exist",
  935. );
  936. } else {
  937. user.profile = { icode: options.profile.invitationcode };
  938. user.profile.boardView = 'board-view-swimlanes';
  939. // Deletes the invitation code after the user was created successfully.
  940. setTimeout(
  941. Meteor.bindEnvironment(() => {
  942. InvitationCodes.remove({ _id: invitationCode._id });
  943. }),
  944. 200,
  945. );
  946. return user;
  947. }
  948. });
  949. }
  950. const addCronJob = _.debounce(
  951. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  952. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  953. const envRemoveAge =
  954. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  955. // default notifications will be removed 2 days after they are read
  956. const defaultRemoveAge = 2;
  957. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  958. SyncedCron.add({
  959. name: 'notification_cleanup',
  960. schedule: parser => parser.text('every 1 days'),
  961. job: () => {
  962. for (const user of Users.find()) {
  963. if (!user.profile || !user.profile.notifications) continue;
  964. for (const notification of user.profile.notifications) {
  965. if (notification.read) {
  966. const removeDate = new Date(notification.read);
  967. removeDate.setDate(removeDate.getDate() + removeAge);
  968. if (removeDate <= new Date()) {
  969. user.removeNotification(notification.activity);
  970. }
  971. }
  972. }
  973. }
  974. },
  975. });
  976. SyncedCron.start();
  977. }),
  978. 500,
  979. );
  980. if (Meteor.isServer) {
  981. // Let mongoDB ensure username unicity
  982. Meteor.startup(() => {
  983. allowedSortValues.forEach(value => {
  984. Lists._collection._ensureIndex(value);
  985. });
  986. Users._collection._ensureIndex({ modifiedAt: -1 });
  987. Users._collection._ensureIndex(
  988. {
  989. username: 1,
  990. },
  991. { unique: true },
  992. );
  993. Meteor.defer(() => {
  994. addCronJob();
  995. });
  996. });
  997. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  998. // if admin is removed, board is removed.
  999. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  1000. // to use that board, and not have board deleted.
  1001. // Someone can be later changed to be admin of board, by making change to database.
  1002. // TODO: Add UI for changing someone as board admin.
  1003. //Users.before.remove((userId, doc) => {
  1004. // Boards
  1005. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  1006. // .forEach((board) => {
  1007. // // If only one admin for the board
  1008. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  1009. // Boards.remove(board._id);
  1010. // }
  1011. // });
  1012. //});
  1013. // Each board document contains the de-normalized number of users that have
  1014. // starred it. If the user star or unstar a board, we need to update this
  1015. // counter.
  1016. // We need to run this code on the server only, otherwise the incrementation
  1017. // will be done twice.
  1018. Users.after.update(function(userId, user, fieldNames) {
  1019. // The `starredBoards` list is hosted on the `profile` field. If this
  1020. // field hasn't been modificated we don't need to run this hook.
  1021. if (!_.contains(fieldNames, 'profile')) return;
  1022. // To calculate a diff of board starred ids, we get both the previous
  1023. // and the newly board ids list
  1024. function getStarredBoardsIds(doc) {
  1025. return doc.profile && doc.profile.starredBoards;
  1026. }
  1027. const oldIds = getStarredBoardsIds(this.previous);
  1028. const newIds = getStarredBoardsIds(user);
  1029. // The _.difference(a, b) method returns the values from a that are not in
  1030. // b. We use it to find deleted and newly inserted ids by using it in one
  1031. // direction and then in the other.
  1032. function incrementBoards(boardsIds, inc) {
  1033. boardsIds.forEach(boardId => {
  1034. Boards.update(boardId, { $inc: { stars: inc } });
  1035. });
  1036. }
  1037. incrementBoards(_.difference(oldIds, newIds), -1);
  1038. incrementBoards(_.difference(newIds, oldIds), +1);
  1039. });
  1040. // Override getUserId so that we can TODO get the current userId
  1041. const fakeUserId = new Meteor.EnvironmentVariable();
  1042. const getUserId = CollectionHooks.getUserId;
  1043. CollectionHooks.getUserId = () => {
  1044. return fakeUserId.get() || getUserId();
  1045. };
  1046. if (!isSandstorm) {
  1047. Users.after.insert((userId, doc) => {
  1048. const fakeUser = {
  1049. extendAutoValueContext: {
  1050. userId: doc._id,
  1051. },
  1052. };
  1053. fakeUserId.withValue(doc._id, () => {
  1054. /*
  1055. // Insert the Welcome Board
  1056. Boards.insert({
  1057. title: TAPi18n.__('welcome-board'),
  1058. permission: 'private',
  1059. }, fakeUser, (err, boardId) => {
  1060. Swimlanes.insert({
  1061. title: TAPi18n.__('welcome-swimlane'),
  1062. boardId,
  1063. sort: 1,
  1064. }, fakeUser);
  1065. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1066. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1067. });
  1068. });
  1069. */
  1070. const Future = require('fibers/future');
  1071. const future1 = new Future();
  1072. const future2 = new Future();
  1073. const future3 = new Future();
  1074. Boards.insert(
  1075. {
  1076. title: TAPi18n.__('templates'),
  1077. permission: 'private',
  1078. type: 'template-container',
  1079. },
  1080. fakeUser,
  1081. (err, boardId) => {
  1082. // Insert the reference to our templates board
  1083. Users.update(fakeUserId.get(), {
  1084. $set: { 'profile.templatesBoardId': boardId },
  1085. });
  1086. // Insert the card templates swimlane
  1087. Swimlanes.insert(
  1088. {
  1089. title: TAPi18n.__('card-templates-swimlane'),
  1090. boardId,
  1091. sort: 1,
  1092. type: 'template-container',
  1093. },
  1094. fakeUser,
  1095. (err, swimlaneId) => {
  1096. // Insert the reference to out card templates swimlane
  1097. Users.update(fakeUserId.get(), {
  1098. $set: { 'profile.cardTemplatesSwimlaneId': swimlaneId },
  1099. });
  1100. future1.return();
  1101. },
  1102. );
  1103. // Insert the list templates swimlane
  1104. Swimlanes.insert(
  1105. {
  1106. title: TAPi18n.__('list-templates-swimlane'),
  1107. boardId,
  1108. sort: 2,
  1109. type: 'template-container',
  1110. },
  1111. fakeUser,
  1112. (err, swimlaneId) => {
  1113. // Insert the reference to out list templates swimlane
  1114. Users.update(fakeUserId.get(), {
  1115. $set: { 'profile.listTemplatesSwimlaneId': swimlaneId },
  1116. });
  1117. future2.return();
  1118. },
  1119. );
  1120. // Insert the board templates swimlane
  1121. Swimlanes.insert(
  1122. {
  1123. title: TAPi18n.__('board-templates-swimlane'),
  1124. boardId,
  1125. sort: 3,
  1126. type: 'template-container',
  1127. },
  1128. fakeUser,
  1129. (err, swimlaneId) => {
  1130. // Insert the reference to out board templates swimlane
  1131. Users.update(fakeUserId.get(), {
  1132. $set: { 'profile.boardTemplatesSwimlaneId': swimlaneId },
  1133. });
  1134. future3.return();
  1135. },
  1136. );
  1137. },
  1138. );
  1139. // HACK
  1140. future1.wait();
  1141. future2.wait();
  1142. future3.wait();
  1143. });
  1144. });
  1145. }
  1146. Users.after.insert((userId, doc) => {
  1147. // HACK
  1148. doc = Users.findOne({ _id: doc._id });
  1149. if (doc.createdThroughApi) {
  1150. // The admin user should be able to create a user despite disabling registration because
  1151. // it is two different things (registration and creation).
  1152. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1153. // the disableRegistration check.
  1154. // Issue : https://github.com/wekan/wekan/issues/1232
  1155. // PR : https://github.com/wekan/wekan/pull/1251
  1156. Users.update(doc._id, { $set: { createdThroughApi: '' } });
  1157. return;
  1158. }
  1159. //invite user to corresponding boards
  1160. const disableRegistration = Settings.findOne().disableRegistration;
  1161. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1162. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1163. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1164. const invitationCode = InvitationCodes.findOne({
  1165. code: doc.profile.icode,
  1166. valid: true,
  1167. });
  1168. if (!invitationCode) {
  1169. throw new Meteor.Error('error-invitation-code-not-exist');
  1170. } else {
  1171. invitationCode.boardsToBeInvited.forEach(boardId => {
  1172. const board = Boards.findOne(boardId);
  1173. board.addMember(doc._id);
  1174. });
  1175. if (!doc.profile) {
  1176. doc.profile = {};
  1177. }
  1178. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1179. Users.update(doc._id, { $set: { profile: doc.profile } });
  1180. InvitationCodes.update(invitationCode._id, { $set: { valid: false } });
  1181. }
  1182. }
  1183. });
  1184. }
  1185. // USERS REST API
  1186. if (Meteor.isServer) {
  1187. // Middleware which checks that API is enabled.
  1188. JsonRoutes.Middleware.use(function(req, res, next) {
  1189. const api = req.url.startsWith('/api');
  1190. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1191. return next();
  1192. } else {
  1193. res.writeHead(301, { Location: '/' });
  1194. return res.end();
  1195. }
  1196. });
  1197. /**
  1198. * @operation get_current_user
  1199. *
  1200. * @summary returns the current user
  1201. * @return_type Users
  1202. */
  1203. JsonRoutes.add('GET', '/api/user', function(req, res) {
  1204. try {
  1205. Authentication.checkLoggedIn(req.userId);
  1206. const data = Meteor.users.findOne({ _id: req.userId });
  1207. delete data.services;
  1208. // get all boards where the user is member of
  1209. let boards = Boards.find(
  1210. {
  1211. type: 'board',
  1212. 'members.userId': req.userId,
  1213. },
  1214. {
  1215. fields: { _id: 1, members: 1 },
  1216. },
  1217. );
  1218. boards = boards.map(b => {
  1219. const u = b.members.find(m => m.userId === req.userId);
  1220. delete u.userId;
  1221. u.boardId = b._id;
  1222. return u;
  1223. });
  1224. data.boards = boards;
  1225. JsonRoutes.sendResult(res, {
  1226. code: 200,
  1227. data,
  1228. });
  1229. } catch (error) {
  1230. JsonRoutes.sendResult(res, {
  1231. code: 200,
  1232. data: error,
  1233. });
  1234. }
  1235. });
  1236. /**
  1237. * @operation get_all_users
  1238. *
  1239. * @summary return all the users
  1240. *
  1241. * @description Only the admin user (the first user) can call the REST API.
  1242. * @return_type [{ _id: string,
  1243. * username: string}]
  1244. */
  1245. JsonRoutes.add('GET', '/api/users', function(req, res) {
  1246. try {
  1247. Authentication.checkUserId(req.userId);
  1248. JsonRoutes.sendResult(res, {
  1249. code: 200,
  1250. data: Meteor.users.find({}).map(function(doc) {
  1251. return { _id: doc._id, username: doc.username };
  1252. }),
  1253. });
  1254. } catch (error) {
  1255. JsonRoutes.sendResult(res, {
  1256. code: 200,
  1257. data: error,
  1258. });
  1259. }
  1260. });
  1261. /**
  1262. * @operation get_user
  1263. *
  1264. * @summary get a given user
  1265. *
  1266. * @description Only the admin user (the first user) can call the REST API.
  1267. *
  1268. * @param {string} userId the user ID
  1269. * @return_type Users
  1270. */
  1271. JsonRoutes.add('GET', '/api/users/:userId', function(req, res) {
  1272. try {
  1273. Authentication.checkUserId(req.userId);
  1274. const id = req.params.userId;
  1275. // get all boards where the user is member of
  1276. let boards = Boards.find(
  1277. {
  1278. type: 'board',
  1279. 'members.userId': id,
  1280. },
  1281. {
  1282. fields: { _id: 1, members: 1 },
  1283. },
  1284. );
  1285. boards = boards.map(b => {
  1286. const u = b.members.find(m => m.userId === id);
  1287. delete u.userId;
  1288. u.boardId = b._id;
  1289. return u;
  1290. });
  1291. const user = Meteor.users.findOne({ _id: id });
  1292. user.boards = boards;
  1293. JsonRoutes.sendResult(res, {
  1294. code: 200,
  1295. data: user,
  1296. });
  1297. } catch (error) {
  1298. JsonRoutes.sendResult(res, {
  1299. code: 200,
  1300. data: error,
  1301. });
  1302. }
  1303. });
  1304. /**
  1305. * @operation edit_user
  1306. *
  1307. * @summary edit a given user
  1308. *
  1309. * @description Only the admin user (the first user) can call the REST API.
  1310. *
  1311. * Possible values for *action*:
  1312. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1313. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1314. * - `enableLogin`: Enable a user
  1315. *
  1316. * @param {string} userId the user ID
  1317. * @param {string} action the action
  1318. * @return_type {_id: string,
  1319. * title: string}
  1320. */
  1321. JsonRoutes.add('PUT', '/api/users/:userId', function(req, res) {
  1322. try {
  1323. Authentication.checkUserId(req.userId);
  1324. const id = req.params.userId;
  1325. const action = req.body.action;
  1326. let data = Meteor.users.findOne({ _id: id });
  1327. if (data !== undefined) {
  1328. if (action === 'takeOwnership') {
  1329. data = Boards.find(
  1330. {
  1331. 'members.userId': id,
  1332. 'members.isAdmin': true,
  1333. },
  1334. { sort: { sort: 1 /* boards default sorting */ } },
  1335. ).map(function(board) {
  1336. if (board.hasMember(req.userId)) {
  1337. board.removeMember(req.userId);
  1338. }
  1339. board.changeOwnership(id, req.userId);
  1340. return {
  1341. _id: board._id,
  1342. title: board.title,
  1343. };
  1344. });
  1345. } else {
  1346. if (action === 'disableLogin' && id !== req.userId) {
  1347. Users.update(
  1348. { _id: id },
  1349. {
  1350. $set: {
  1351. loginDisabled: true,
  1352. 'services.resume.loginTokens': '',
  1353. },
  1354. },
  1355. );
  1356. } else if (action === 'enableLogin') {
  1357. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  1358. }
  1359. data = Meteor.users.findOne({ _id: id });
  1360. }
  1361. }
  1362. JsonRoutes.sendResult(res, {
  1363. code: 200,
  1364. data,
  1365. });
  1366. } catch (error) {
  1367. JsonRoutes.sendResult(res, {
  1368. code: 200,
  1369. data: error,
  1370. });
  1371. }
  1372. });
  1373. /**
  1374. * @operation add_board_member
  1375. * @tag Boards
  1376. *
  1377. * @summary Add New Board Member with Role
  1378. *
  1379. * @description Only the admin user (the first user) can call the REST API.
  1380. *
  1381. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1382. * to later change the permissions.
  1383. *
  1384. * @param {string} boardId the board ID
  1385. * @param {string} userId the user ID
  1386. * @param {boolean} isAdmin is the user an admin of the board
  1387. * @param {boolean} isNoComments disable comments
  1388. * @param {boolean} isCommentOnly only enable comments
  1389. * @return_type {_id: string,
  1390. * title: string}
  1391. */
  1392. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function(
  1393. req,
  1394. res,
  1395. ) {
  1396. try {
  1397. Authentication.checkUserId(req.userId);
  1398. const userId = req.params.userId;
  1399. const boardId = req.params.boardId;
  1400. const action = req.body.action;
  1401. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1402. let data = Meteor.users.findOne({ _id: userId });
  1403. if (data !== undefined) {
  1404. if (action === 'add') {
  1405. data = Boards.find({
  1406. _id: boardId,
  1407. }).map(function(board) {
  1408. if (!board.hasMember(userId)) {
  1409. board.addMember(userId);
  1410. function isTrue(data) {
  1411. return data.toLowerCase() === 'true';
  1412. }
  1413. board.setMemberPermission(
  1414. userId,
  1415. isTrue(isAdmin),
  1416. isTrue(isNoComments),
  1417. isTrue(isCommentOnly),
  1418. userId,
  1419. );
  1420. }
  1421. return {
  1422. _id: board._id,
  1423. title: board.title,
  1424. };
  1425. });
  1426. }
  1427. }
  1428. JsonRoutes.sendResult(res, {
  1429. code: 200,
  1430. data: query,
  1431. });
  1432. } catch (error) {
  1433. JsonRoutes.sendResult(res, {
  1434. code: 200,
  1435. data: error,
  1436. });
  1437. }
  1438. });
  1439. /**
  1440. * @operation remove_board_member
  1441. * @tag Boards
  1442. *
  1443. * @summary Remove Member from Board
  1444. *
  1445. * @description Only the admin user (the first user) can call the REST API.
  1446. *
  1447. * @param {string} boardId the board ID
  1448. * @param {string} userId the user ID
  1449. * @param {string} action the action (needs to be `remove`)
  1450. * @return_type {_id: string,
  1451. * title: string}
  1452. */
  1453. JsonRoutes.add(
  1454. 'POST',
  1455. '/api/boards/:boardId/members/:userId/remove',
  1456. function(req, res) {
  1457. try {
  1458. Authentication.checkUserId(req.userId);
  1459. const userId = req.params.userId;
  1460. const boardId = req.params.boardId;
  1461. const action = req.body.action;
  1462. let data = Meteor.users.findOne({ _id: userId });
  1463. if (data !== undefined) {
  1464. if (action === 'remove') {
  1465. data = Boards.find({
  1466. _id: boardId,
  1467. }).map(function(board) {
  1468. if (board.hasMember(userId)) {
  1469. board.removeMember(userId);
  1470. }
  1471. return {
  1472. _id: board._id,
  1473. title: board.title,
  1474. };
  1475. });
  1476. }
  1477. }
  1478. JsonRoutes.sendResult(res, {
  1479. code: 200,
  1480. data: query,
  1481. });
  1482. } catch (error) {
  1483. JsonRoutes.sendResult(res, {
  1484. code: 200,
  1485. data: error,
  1486. });
  1487. }
  1488. },
  1489. );
  1490. /**
  1491. * @operation new_user
  1492. *
  1493. * @summary Create a new user
  1494. *
  1495. * @description Only the admin user (the first user) can call the REST API.
  1496. *
  1497. * @param {string} username the new username
  1498. * @param {string} email the email of the new user
  1499. * @param {string} password the password of the new user
  1500. * @return_type {_id: string}
  1501. */
  1502. JsonRoutes.add('POST', '/api/users/', function(req, res) {
  1503. try {
  1504. Authentication.checkUserId(req.userId);
  1505. const id = Accounts.createUser({
  1506. username: req.body.username,
  1507. email: req.body.email,
  1508. password: req.body.password,
  1509. from: 'admin',
  1510. });
  1511. JsonRoutes.sendResult(res, {
  1512. code: 200,
  1513. data: {
  1514. _id: id,
  1515. },
  1516. });
  1517. } catch (error) {
  1518. JsonRoutes.sendResult(res, {
  1519. code: 200,
  1520. data: error,
  1521. });
  1522. }
  1523. });
  1524. /**
  1525. * @operation delete_user
  1526. *
  1527. * @summary Delete a user
  1528. *
  1529. * @description Only the admin user (the first user) can call the REST API.
  1530. *
  1531. * @param {string} userId the ID of the user to delete
  1532. * @return_type {_id: string}
  1533. */
  1534. JsonRoutes.add('DELETE', '/api/users/:userId', function(req, res) {
  1535. try {
  1536. Authentication.checkUserId(req.userId);
  1537. const id = req.params.userId;
  1538. // Delete is not enabled yet, because it does leave empty user avatars
  1539. // to boards: boards members, card members and assignees have
  1540. // empty users. See:
  1541. // - wekan/client/components/settings/peopleBody.jade deleteButton
  1542. // - wekan/client/components/settings/peopleBody.js deleteButton
  1543. // - wekan/client/components/sidebar/sidebar.js Popup.afterConfirm('removeMember'
  1544. // that does now remove member from board, card members and assignees correctly,
  1545. // but that should be used to remove user from all boards similarly
  1546. // - wekan/models/users.js Delete is not enabled
  1547. // Meteor.users.remove({ _id: id });
  1548. JsonRoutes.sendResult(res, {
  1549. code: 200,
  1550. data: {
  1551. _id: id,
  1552. },
  1553. });
  1554. } catch (error) {
  1555. JsonRoutes.sendResult(res, {
  1556. code: 200,
  1557. data: error,
  1558. });
  1559. }
  1560. });
  1561. }
  1562. export default Users;