users.js 46 KB

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