users.js 46 KB

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