users.js 47 KB

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