users.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122
  1. import { SyncedCron } from 'meteor/percolate:synced-cron';
  2. import ImpersonatedUsers from './impersonatedUsers';
  3. // Sandstorm context is detected using the METEOR_SETTINGS environment variable
  4. // in the package definition.
  5. const isSandstorm =
  6. Meteor.settings && Meteor.settings.public && Meteor.settings.public.sandstorm;
  7. Users = Meteor.users;
  8. const allowedSortValues = [
  9. '-modifiedAt',
  10. 'modifiedAt',
  11. '-title',
  12. 'title',
  13. '-sort',
  14. 'sort',
  15. ];
  16. const defaultSortBy = allowedSortValues[0];
  17. /**
  18. * A User in wekan
  19. */
  20. Users.attachSchema(
  21. new SimpleSchema({
  22. username: {
  23. /**
  24. * the username of the user
  25. */
  26. type: String,
  27. optional: true,
  28. // eslint-disable-next-line consistent-return
  29. autoValue() {
  30. if (this.isInsert && !this.isSet) {
  31. const name = this.field('profile.fullname');
  32. if (name.isSet) {
  33. return name.value.toLowerCase().replace(/\s/g, '');
  34. }
  35. }
  36. },
  37. },
  38. orgs: {
  39. /**
  40. * the list of organizations that a user belongs to
  41. */
  42. type: [Object],
  43. optional: true,
  44. },
  45. 'orgs.$.orgId':{
  46. /**
  47. * The uniq ID of the organization
  48. */
  49. type: String,
  50. },
  51. 'orgs.$.orgDisplayName':{
  52. /**
  53. * The display name of the organization
  54. */
  55. type: String,
  56. },
  57. teams: {
  58. /**
  59. * the list of teams that a user belongs to
  60. */
  61. type: [Object],
  62. optional: true,
  63. },
  64. 'teams.$.teamId':{
  65. /**
  66. * The uniq ID of the team
  67. */
  68. type: String,
  69. },
  70. 'teams.$.teamDisplayName':{
  71. /**
  72. * The display name of the team
  73. */
  74. type: String,
  75. },
  76. emails: {
  77. /**
  78. * the list of emails attached to a user
  79. */
  80. type: [Object],
  81. optional: true,
  82. },
  83. 'emails.$.address': {
  84. /**
  85. * The email address
  86. */
  87. type: String,
  88. regEx: SimpleSchema.RegEx.Email,
  89. },
  90. 'emails.$.verified': {
  91. /**
  92. * Has the email been verified
  93. */
  94. type: Boolean,
  95. },
  96. createdAt: {
  97. /**
  98. * creation date of the user
  99. */
  100. type: Date,
  101. // eslint-disable-next-line consistent-return
  102. autoValue() {
  103. if (this.isInsert) {
  104. return new Date();
  105. } else if (this.isUpsert) {
  106. return {
  107. $setOnInsert: new Date(),
  108. };
  109. } else {
  110. this.unset();
  111. }
  112. },
  113. },
  114. modifiedAt: {
  115. type: Date,
  116. denyUpdate: false,
  117. // eslint-disable-next-line consistent-return
  118. autoValue() {
  119. if (this.isInsert || this.isUpsert || this.isUpdate) {
  120. return new Date();
  121. } else {
  122. this.unset();
  123. }
  124. },
  125. },
  126. profile: {
  127. /**
  128. * profile settings
  129. */
  130. type: Object,
  131. optional: true,
  132. // eslint-disable-next-line consistent-return
  133. autoValue() {
  134. if (this.isInsert && !this.isSet) {
  135. return {
  136. boardView: 'board-view-swimlanes',
  137. };
  138. }
  139. },
  140. },
  141. 'profile.avatarUrl': {
  142. /**
  143. * URL of the avatar of the user
  144. */
  145. type: String,
  146. optional: true,
  147. },
  148. 'profile.emailBuffer': {
  149. /**
  150. * list of email buffers of the user
  151. */
  152. type: [String],
  153. optional: true,
  154. },
  155. 'profile.fullname': {
  156. /**
  157. * full name of the user
  158. */
  159. type: String,
  160. optional: true,
  161. },
  162. 'profile.showDesktopDragHandles': {
  163. /**
  164. * does the user want to show desktop drag handles?
  165. */
  166. type: Boolean,
  167. optional: true,
  168. },
  169. 'profile.hideCheckedItems': {
  170. /**
  171. * does the user want to hide checked checklist items?
  172. */
  173. type: Boolean,
  174. optional: true,
  175. },
  176. 'profile.cardMaximized': {
  177. /**
  178. * has user clicked maximize card?
  179. */
  180. type: Boolean,
  181. optional: true,
  182. },
  183. 'profile.hiddenSystemMessages': {
  184. /**
  185. * does the user want to hide system messages?
  186. */
  187. type: Boolean,
  188. optional: true,
  189. },
  190. 'profile.hiddenMinicardLabelText': {
  191. /**
  192. * does the user want to hide minicard label texts?
  193. */
  194. type: Boolean,
  195. optional: true,
  196. },
  197. 'profile.initials': {
  198. /**
  199. * initials of the user
  200. */
  201. type: String,
  202. optional: true,
  203. },
  204. 'profile.invitedBoards': {
  205. /**
  206. * board IDs the user has been invited to
  207. */
  208. type: [String],
  209. optional: true,
  210. },
  211. 'profile.language': {
  212. /**
  213. * language of the user
  214. */
  215. type: String,
  216. optional: true,
  217. },
  218. 'profile.notifications': {
  219. /**
  220. * enabled notifications for the user
  221. */
  222. type: [Object],
  223. optional: true,
  224. },
  225. 'profile.notifications.$.activity': {
  226. /**
  227. * The id of the activity this notification references
  228. */
  229. type: String,
  230. },
  231. 'profile.notifications.$.read': {
  232. /**
  233. * the date on which this notification was read
  234. */
  235. type: Date,
  236. optional: true,
  237. },
  238. 'profile.showCardsCountAt': {
  239. /**
  240. * showCardCountAt field of the user
  241. */
  242. type: Number,
  243. optional: true,
  244. },
  245. 'profile.startDayOfWeek': {
  246. /**
  247. * startDayOfWeek field of the user
  248. */
  249. type: Number,
  250. optional: true,
  251. },
  252. 'profile.starredBoards': {
  253. /**
  254. * list of starred board IDs
  255. */
  256. type: [String],
  257. optional: true,
  258. },
  259. 'profile.icode': {
  260. /**
  261. * icode
  262. */
  263. type: String,
  264. optional: true,
  265. },
  266. 'profile.boardView': {
  267. /**
  268. * boardView field of the user
  269. */
  270. type: String,
  271. optional: true,
  272. allowedValues: [
  273. 'board-view-swimlanes',
  274. 'board-view-lists',
  275. 'board-view-cal',
  276. ],
  277. },
  278. 'profile.listSortBy': {
  279. /**
  280. * default sort list for user
  281. */
  282. type: String,
  283. optional: true,
  284. defaultValue: defaultSortBy,
  285. allowedValues: allowedSortValues,
  286. },
  287. 'profile.templatesBoardId': {
  288. /**
  289. * Reference to the templates board
  290. */
  291. type: String,
  292. defaultValue: '',
  293. },
  294. 'profile.cardTemplatesSwimlaneId': {
  295. /**
  296. * Reference to the card templates swimlane Id
  297. */
  298. type: String,
  299. defaultValue: '',
  300. },
  301. 'profile.listTemplatesSwimlaneId': {
  302. /**
  303. * Reference to the list templates swimlane Id
  304. */
  305. type: String,
  306. defaultValue: '',
  307. },
  308. 'profile.boardTemplatesSwimlaneId': {
  309. /**
  310. * Reference to the board templates swimlane Id
  311. */
  312. type: String,
  313. defaultValue: '',
  314. },
  315. services: {
  316. /**
  317. * services field of the user
  318. */
  319. type: Object,
  320. optional: true,
  321. blackbox: true,
  322. },
  323. heartbeat: {
  324. /**
  325. * last time the user has been seen
  326. */
  327. type: Date,
  328. optional: true,
  329. },
  330. isAdmin: {
  331. /**
  332. * is the user an admin of the board?
  333. */
  334. type: Boolean,
  335. optional: true,
  336. },
  337. createdThroughApi: {
  338. /**
  339. * was the user created through the API?
  340. */
  341. type: Boolean,
  342. optional: true,
  343. },
  344. loginDisabled: {
  345. /**
  346. * loginDisabled field of the user
  347. */
  348. type: Boolean,
  349. optional: true,
  350. },
  351. authenticationMethod: {
  352. /**
  353. * authentication method of the user
  354. */
  355. type: String,
  356. optional: false,
  357. defaultValue: 'password',
  358. },
  359. sessionData: {
  360. /**
  361. * profile settings
  362. */
  363. type: Object,
  364. optional: true,
  365. // eslint-disable-next-line consistent-return
  366. autoValue() {
  367. if (this.isInsert && !this.isSet) {
  368. return {};
  369. }
  370. },
  371. },
  372. 'sessionData.totalHits': {
  373. /**
  374. * Total hits from last searchquery['members.userId'] = Meteor.userId();
  375. * last hit that was returned
  376. */
  377. type: Number,
  378. optional: true,
  379. },
  380. importUsernames: {
  381. /**
  382. * username for imported
  383. */
  384. type: [String],
  385. optional: true,
  386. },
  387. }),
  388. );
  389. Users.allow({
  390. update(userId, doc) {
  391. const user = Users.findOne({
  392. _id: userId,
  393. });
  394. if ((user && user.isAdmin) || (Meteor.user() && Meteor.user().isAdmin))
  395. return true;
  396. if (!user) {
  397. return false;
  398. }
  399. return doc._id === userId;
  400. },
  401. remove(userId, doc) {
  402. const adminsNumber = Users.find({
  403. isAdmin: true,
  404. }).count();
  405. const { isAdmin } = Users.findOne(
  406. {
  407. _id: userId,
  408. },
  409. {
  410. fields: {
  411. isAdmin: 1,
  412. },
  413. },
  414. );
  415. // Prevents remove of the only one administrator
  416. if (adminsNumber === 1 && isAdmin && userId === doc._id) {
  417. return false;
  418. }
  419. // If it's the user or an admin
  420. return userId === doc._id || isAdmin;
  421. },
  422. fetch: [],
  423. });
  424. // Search a user in the complete server database by its name or username. This
  425. // is used for instance to add a new user to a board.
  426. const searchInFields = ['username', 'profile.fullname'];
  427. Users.initEasySearch(searchInFields, {
  428. use: 'mongo-db',
  429. returnFields: [...searchInFields, 'profile.avatarUrl'],
  430. });
  431. Users.safeFields = {
  432. _id: 1,
  433. username: 1,
  434. 'profile.fullname': 1,
  435. 'profile.avatarUrl': 1,
  436. 'profile.initials': 1,
  437. };
  438. if (Meteor.isClient) {
  439. Users.helpers({
  440. isBoardMember() {
  441. const board = Boards.findOne(Session.get('currentBoard'));
  442. return board && board.hasMember(this._id);
  443. },
  444. isNotNoComments() {
  445. const board = Boards.findOne(Session.get('currentBoard'));
  446. return (
  447. board && board.hasMember(this._id) && !board.hasNoComments(this._id)
  448. );
  449. },
  450. isNoComments() {
  451. const board = Boards.findOne(Session.get('currentBoard'));
  452. return board && board.hasNoComments(this._id);
  453. },
  454. isNotCommentOnly() {
  455. const board = Boards.findOne(Session.get('currentBoard'));
  456. return (
  457. board && board.hasMember(this._id) && !board.hasCommentOnly(this._id)
  458. );
  459. },
  460. isCommentOnly() {
  461. const board = Boards.findOne(Session.get('currentBoard'));
  462. return board && board.hasCommentOnly(this._id);
  463. },
  464. isNotWorker() {
  465. const board = Boards.findOne(Session.get('currentBoard'));
  466. return board && board.hasMember(this._id) && !board.hasWorker(this._id);
  467. },
  468. isWorker() {
  469. const board = Boards.findOne(Session.get('currentBoard'));
  470. return board && board.hasWorker(this._id);
  471. },
  472. isBoardAdmin(boardId = Session.get('currentBoard')) {
  473. const board = Boards.findOne(boardId);
  474. return board && board.hasAdmin(this._id);
  475. },
  476. });
  477. }
  478. Users.parseImportUsernames = (usernamesString) => {
  479. return usernamesString.trim().split(new RegExp('\\s*[,;]\\s*'));
  480. };
  481. Users.helpers({
  482. importUsernamesString() {
  483. if (this.importUsernames) {
  484. return this.importUsernames.join(', ');
  485. }
  486. return '';
  487. },
  488. orgsUserBelongs() {
  489. if (this.orgs) {
  490. return this.orgs.map(function(org){return org.orgDisplayName}).join(',');
  491. }
  492. return '';
  493. },
  494. orgIdsUserBelongs() {
  495. if (this.orgs) {
  496. return this.orgs.map(function(org){return org.orgId}).join(',');
  497. }
  498. return '';
  499. },
  500. teamsUserBelongs() {
  501. if (this.teams) {
  502. return this.teams.map(function(team){ return team.teamDisplayName}).join(',');
  503. }
  504. return '';
  505. },
  506. teamIdsUserBelongs() {
  507. if (this.teams) {
  508. return this.teams.map(function(team){ return team.teamId}).join(',');
  509. }
  510. return '';
  511. },
  512. boards() {
  513. return Boards.find(
  514. {
  515. 'members.userId': this._id,
  516. },
  517. {
  518. sort: {
  519. sort: 1 /* boards default sorting */,
  520. },
  521. },
  522. );
  523. },
  524. starredBoards() {
  525. const { starredBoards = [] } = this.profile || {};
  526. return Boards.find(
  527. {
  528. archived: false,
  529. _id: {
  530. $in: starredBoards,
  531. },
  532. },
  533. {
  534. sort: {
  535. sort: 1 /* boards default sorting */,
  536. },
  537. },
  538. );
  539. },
  540. hasStarred(boardId) {
  541. const { starredBoards = [] } = this.profile || {};
  542. return _.contains(starredBoards, boardId);
  543. },
  544. invitedBoards() {
  545. const { invitedBoards = [] } = this.profile || {};
  546. return Boards.find(
  547. {
  548. archived: false,
  549. _id: {
  550. $in: invitedBoards,
  551. },
  552. },
  553. {
  554. sort: {
  555. sort: 1 /* boards default sorting */,
  556. },
  557. },
  558. );
  559. },
  560. isInvitedTo(boardId) {
  561. const { invitedBoards = [] } = this.profile || {};
  562. return _.contains(invitedBoards, boardId);
  563. },
  564. _getListSortBy() {
  565. const profile = this.profile || {};
  566. const sortBy = profile.listSortBy || defaultSortBy;
  567. const keyPattern = /^(-{0,1})(.*$)/;
  568. const ret = [];
  569. if (keyPattern.exec(sortBy)) {
  570. ret[0] = RegExp.$2;
  571. ret[1] = RegExp.$1 ? -1 : 1;
  572. }
  573. return ret;
  574. },
  575. hasSortBy() {
  576. // if use doesn't have dragHandle, then we can let user to choose sort list by different order
  577. return !this.hasShowDesktopDragHandles();
  578. },
  579. getListSortBy() {
  580. return this._getListSortBy()[0];
  581. },
  582. getListSortTypes() {
  583. return allowedSortValues;
  584. },
  585. getListSortByDirection() {
  586. return this._getListSortBy()[1];
  587. },
  588. hasTag(tag) {
  589. const { tags = [] } = this.profile || {};
  590. return _.contains(tags, tag);
  591. },
  592. hasNotification(activityId) {
  593. const { notifications = [] } = this.profile || {};
  594. return _.contains(notifications, activityId);
  595. },
  596. notifications() {
  597. const { notifications = [] } = this.profile || {};
  598. for (const index in notifications) {
  599. if (!notifications.hasOwnProperty(index)) continue;
  600. const notification = notifications[index];
  601. // this preserves their db sort order for editing
  602. notification.dbIndex = index;
  603. notification.activity = Activities.findOne(notification.activity);
  604. }
  605. // this sorts them newest to oldest to match Trello's behavior
  606. notifications.reverse();
  607. return notifications;
  608. },
  609. hasShowDesktopDragHandles() {
  610. const profile = this.profile || {};
  611. return profile.showDesktopDragHandles || false;
  612. },
  613. hasHideCheckedItems() {
  614. const profile = this.profile || {};
  615. return profile.hideCheckedItems || false;
  616. },
  617. hasHiddenSystemMessages() {
  618. const profile = this.profile || {};
  619. return profile.hiddenSystemMessages || false;
  620. },
  621. hasCardMaximized() {
  622. const profile = this.profile || {};
  623. return profile.cardMaximized || false;
  624. },
  625. hasHiddenMinicardLabelText() {
  626. const profile = this.profile || {};
  627. return profile.hiddenMinicardLabelText || false;
  628. },
  629. getEmailBuffer() {
  630. const { emailBuffer = [] } = this.profile || {};
  631. return emailBuffer;
  632. },
  633. getInitials() {
  634. const profile = this.profile || {};
  635. if (profile.initials) return profile.initials;
  636. else if (profile.fullname) {
  637. return profile.fullname
  638. .split(/\s+/)
  639. .reduce((memo, word) => {
  640. return memo + word[0];
  641. }, '')
  642. .toUpperCase();
  643. } else {
  644. return this.username[0].toUpperCase();
  645. }
  646. },
  647. getLimitToShowCardsCount() {
  648. const profile = this.profile || {};
  649. return profile.showCardsCountAt;
  650. },
  651. getName() {
  652. const profile = this.profile || {};
  653. return profile.fullname || this.username;
  654. },
  655. getLanguage() {
  656. const profile = this.profile || {};
  657. return profile.language || 'en';
  658. },
  659. getStartDayOfWeek() {
  660. const profile = this.profile || {};
  661. if (typeof profile.startDayOfWeek === 'undefined') {
  662. // default is 'Monday' (1)
  663. return 1;
  664. }
  665. return profile.startDayOfWeek;
  666. },
  667. getTemplatesBoardId() {
  668. return (this.profile || {}).templatesBoardId;
  669. },
  670. getTemplatesBoardSlug() {
  671. return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  672. },
  673. remove() {
  674. User.remove({
  675. _id: this._id,
  676. });
  677. },
  678. });
  679. Users.mutations({
  680. toggleBoardStar(boardId) {
  681. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  682. return {
  683. [queryKind]: {
  684. 'profile.starredBoards': boardId,
  685. },
  686. };
  687. },
  688. addInvite(boardId) {
  689. return {
  690. $addToSet: {
  691. 'profile.invitedBoards': boardId,
  692. },
  693. };
  694. },
  695. removeInvite(boardId) {
  696. return {
  697. $pull: {
  698. 'profile.invitedBoards': boardId,
  699. },
  700. };
  701. },
  702. addTag(tag) {
  703. return {
  704. $addToSet: {
  705. 'profile.tags': tag,
  706. },
  707. };
  708. },
  709. removeTag(tag) {
  710. return {
  711. $pull: {
  712. 'profile.tags': tag,
  713. },
  714. };
  715. },
  716. toggleTag(tag) {
  717. if (this.hasTag(tag)) this.removeTag(tag);
  718. else this.addTag(tag);
  719. },
  720. setListSortBy(value) {
  721. return {
  722. $set: {
  723. 'profile.listSortBy': value,
  724. },
  725. };
  726. },
  727. setName(value) {
  728. return {
  729. $set: {
  730. 'profile.fullname': value,
  731. },
  732. };
  733. },
  734. toggleDesktopHandles(value = false) {
  735. return {
  736. $set: {
  737. 'profile.showDesktopDragHandles': !value,
  738. },
  739. };
  740. },
  741. toggleHideCheckedItems() {
  742. const value = this.hasHideCheckedItems();
  743. return {
  744. $set: {
  745. 'profile.hideCheckedItems': !value,
  746. },
  747. };
  748. },
  749. toggleSystem(value = false) {
  750. return {
  751. $set: {
  752. 'profile.hiddenSystemMessages': !value,
  753. },
  754. };
  755. },
  756. toggleCardMaximized(value = false) {
  757. return {
  758. $set: {
  759. 'profile.cardMaximized': !value,
  760. },
  761. };
  762. },
  763. toggleLabelText(value = false) {
  764. return {
  765. $set: {
  766. 'profile.hiddenMinicardLabelText': !value,
  767. },
  768. };
  769. },
  770. addNotification(activityId) {
  771. return {
  772. $addToSet: {
  773. 'profile.notifications': {
  774. activity: activityId,
  775. },
  776. },
  777. };
  778. },
  779. removeNotification(activityId) {
  780. return {
  781. $pull: {
  782. 'profile.notifications': {
  783. activity: activityId,
  784. },
  785. },
  786. };
  787. },
  788. addEmailBuffer(text) {
  789. return {
  790. $addToSet: {
  791. 'profile.emailBuffer': text,
  792. },
  793. };
  794. },
  795. clearEmailBuffer() {
  796. return {
  797. $set: {
  798. 'profile.emailBuffer': [],
  799. },
  800. };
  801. },
  802. setAvatarUrl(avatarUrl) {
  803. return {
  804. $set: {
  805. 'profile.avatarUrl': avatarUrl,
  806. },
  807. };
  808. },
  809. setShowCardsCountAt(limit) {
  810. return {
  811. $set: {
  812. 'profile.showCardsCountAt': limit,
  813. },
  814. };
  815. },
  816. setStartDayOfWeek(startDay) {
  817. return {
  818. $set: {
  819. 'profile.startDayOfWeek': startDay,
  820. },
  821. };
  822. },
  823. setBoardView(view) {
  824. return {
  825. $set: {
  826. 'profile.boardView': view,
  827. },
  828. };
  829. },
  830. });
  831. Meteor.methods({
  832. setListSortBy(value) {
  833. check(value, String);
  834. Meteor.user().setListSortBy(value);
  835. },
  836. toggleDesktopDragHandles() {
  837. const user = Meteor.user();
  838. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  839. },
  840. toggleHideCheckedItems() {
  841. const user = Meteor.user();
  842. user.toggleHideCheckedItems();
  843. },
  844. toggleSystemMessages() {
  845. const user = Meteor.user();
  846. user.toggleSystem(user.hasHiddenSystemMessages());
  847. },
  848. toggleCardMaximized() {
  849. const user = Meteor.user();
  850. user.toggleCardMaximized(user.hasCardMaximized());
  851. },
  852. toggleMinicardLabelText() {
  853. const user = Meteor.user();
  854. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  855. },
  856. changeLimitToShowCardsCount(limit) {
  857. check(limit, Number);
  858. Meteor.user().setShowCardsCountAt(limit);
  859. },
  860. changeStartDayOfWeek(startDay) {
  861. check(startDay, Number);
  862. Meteor.user().setStartDayOfWeek(startDay);
  863. },
  864. });
  865. if (Meteor.isServer) {
  866. Meteor.methods({
  867. setAllUsersHideSystemMessages() {
  868. if (Meteor.user() && Meteor.user().isAdmin) {
  869. // If setting is missing, add it
  870. Users.update(
  871. {
  872. 'profile.hiddenSystemMessages': {
  873. $exists: false,
  874. },
  875. },
  876. {
  877. $set: {
  878. 'profile.hiddenSystemMessages': true,
  879. },
  880. },
  881. {
  882. multi: true,
  883. },
  884. );
  885. // If setting is false, set it to true
  886. Users.update(
  887. {
  888. 'profile.hiddenSystemMessages': false,
  889. },
  890. {
  891. $set: {
  892. 'profile.hiddenSystemMessages': true,
  893. },
  894. },
  895. {
  896. multi: true,
  897. },
  898. );
  899. return true;
  900. } else {
  901. return false;
  902. }
  903. },
  904. setCreateUser(
  905. fullname,
  906. username,
  907. initials,
  908. password,
  909. isAdmin,
  910. isActive,
  911. email,
  912. importUsernames,
  913. userOrgsArray,
  914. userTeamsArray,
  915. ) {
  916. check(fullname, String);
  917. check(username, String);
  918. check(initials, String);
  919. check(password, String);
  920. check(isAdmin, String);
  921. check(isActive, String);
  922. check(email, String);
  923. check(importUsernames, Array);
  924. check(userOrgsArray, Array);
  925. check(userTeamsArray, Array);
  926. if (Meteor.user() && Meteor.user().isAdmin) {
  927. const nUsersWithUsername = Users.find({
  928. username,
  929. }).count();
  930. const nUsersWithEmail = Users.find({
  931. email,
  932. }).count();
  933. if (nUsersWithUsername > 0) {
  934. throw new Meteor.Error('username-already-taken');
  935. } else if (nUsersWithEmail > 0) {
  936. throw new Meteor.Error('email-already-taken');
  937. } else {
  938. Accounts.createUser({
  939. username,
  940. password,
  941. isAdmin,
  942. isActive,
  943. email: email.toLowerCase(),
  944. from: 'admin',
  945. });
  946. const user =
  947. Users.findOne(username) ||
  948. Users.findOne({
  949. username,
  950. });
  951. if (user) {
  952. Users.update(user._id, {
  953. $set: {
  954. 'profile.fullname': fullname,
  955. importUsernames,
  956. 'profile.initials': initials,
  957. orgs: userOrgsArray,
  958. teams: userTeamsArray,
  959. },
  960. });
  961. }
  962. }
  963. }
  964. },
  965. setUsername(username, userId) {
  966. check(username, String);
  967. check(userId, String);
  968. if (Meteor.user() && Meteor.user().isAdmin) {
  969. const nUsersWithUsername = Users.find({
  970. username,
  971. }).count();
  972. if (nUsersWithUsername > 0) {
  973. throw new Meteor.Error('username-already-taken');
  974. } else {
  975. Users.update(userId, {
  976. $set: {
  977. username,
  978. },
  979. });
  980. }
  981. }
  982. },
  983. setEmail(email, userId) {
  984. check(email, String);
  985. check(username, String);
  986. if (Meteor.user() && Meteor.user().isAdmin) {
  987. if (Array.isArray(email)) {
  988. email = email.shift();
  989. }
  990. const existingUser = Users.findOne(
  991. {
  992. 'emails.address': email,
  993. },
  994. {
  995. fields: {
  996. _id: 1,
  997. },
  998. },
  999. );
  1000. if (existingUser) {
  1001. throw new Meteor.Error('email-already-taken');
  1002. } else {
  1003. Users.update(userId, {
  1004. $set: {
  1005. emails: [
  1006. {
  1007. address: email,
  1008. verified: false,
  1009. },
  1010. ],
  1011. },
  1012. });
  1013. }
  1014. }
  1015. },
  1016. setUsernameAndEmail(username, email, userId) {
  1017. check(username, String);
  1018. check(email, String);
  1019. check(userId, String);
  1020. if (Meteor.user() && Meteor.user().isAdmin) {
  1021. if (Array.isArray(email)) {
  1022. email = email.shift();
  1023. }
  1024. Meteor.call('setUsername', username, userId);
  1025. Meteor.call('setEmail', email, userId);
  1026. }
  1027. },
  1028. setPassword(newPassword, userId) {
  1029. check(userId, String);
  1030. check(newPassword, String);
  1031. if (Meteor.user() && Meteor.user().isAdmin) {
  1032. if (Meteor.user().isAdmin) {
  1033. Accounts.setPassword(userId, newPassword);
  1034. }
  1035. }
  1036. },
  1037. setEmailVerified(email, verified, userId) {
  1038. check(email, String);
  1039. check(verified, Boolean);
  1040. check(userId, String);
  1041. if (Meteor.user() && Meteor.user().isAdmin) {
  1042. Users.update(userId, {
  1043. $set: {
  1044. emails: [
  1045. {
  1046. address: email,
  1047. verified,
  1048. },
  1049. ],
  1050. },
  1051. });
  1052. }
  1053. },
  1054. setInitials(initials, userId) {
  1055. check(initials, String);
  1056. check(userId, String);
  1057. if (Meteor.user() && Meteor.user().isAdmin) {
  1058. Users.update(userId, {
  1059. $set: {
  1060. 'profile.initials': initials,
  1061. },
  1062. });
  1063. }
  1064. },
  1065. // we accept userId, username, email
  1066. inviteUserToBoard(username, boardId) {
  1067. check(username, String);
  1068. check(boardId, String);
  1069. const inviter = Meteor.user();
  1070. const board = Boards.findOne(boardId);
  1071. const allowInvite =
  1072. inviter &&
  1073. board &&
  1074. board.members &&
  1075. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  1076. _.where(board.members, {
  1077. userId: inviter._id,
  1078. })[0].isActive;
  1079. // GitHub issue 2060
  1080. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  1081. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  1082. this.unblock();
  1083. const posAt = username.indexOf('@');
  1084. let user = null;
  1085. if (posAt >= 0) {
  1086. user = Users.findOne({
  1087. emails: {
  1088. $elemMatch: {
  1089. address: username,
  1090. },
  1091. },
  1092. });
  1093. } else {
  1094. user =
  1095. Users.findOne(username) ||
  1096. Users.findOne({
  1097. username,
  1098. });
  1099. }
  1100. if (user) {
  1101. if (user._id === inviter._id)
  1102. throw new Meteor.Error('error-user-notAllowSelf');
  1103. } else {
  1104. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  1105. if (
  1106. Settings.findOne({
  1107. disableRegistration: true,
  1108. })
  1109. ) {
  1110. throw new Meteor.Error('error-user-notCreated');
  1111. }
  1112. // Set in lowercase email before creating account
  1113. const email = username.toLowerCase();
  1114. username = email.substring(0, posAt);
  1115. const newUserId = Accounts.createUser({
  1116. username,
  1117. email,
  1118. });
  1119. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  1120. // assume new user speak same language with inviter
  1121. if (inviter.profile && inviter.profile.language) {
  1122. Users.update(newUserId, {
  1123. $set: {
  1124. 'profile.language': inviter.profile.language,
  1125. },
  1126. });
  1127. }
  1128. Accounts.sendEnrollmentEmail(newUserId);
  1129. user = Users.findOne(newUserId);
  1130. }
  1131. board.addMember(user._id);
  1132. user.addInvite(boardId);
  1133. //Check if there is a subtasks board
  1134. if (board.subtasksDefaultBoardId) {
  1135. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  1136. //If there is, also add user to that board
  1137. if (subBoard) {
  1138. subBoard.addMember(user._id);
  1139. user.addInvite(subBoard._id);
  1140. }
  1141. }
  1142. try {
  1143. const params = {
  1144. user: user.username,
  1145. inviter: inviter.username,
  1146. board: board.title,
  1147. url: board.absoluteUrl(),
  1148. };
  1149. const lang = user.getLanguage();
  1150. Email.send({
  1151. to: user.emails[0].address.toLowerCase(),
  1152. from: Accounts.emailTemplates.from,
  1153. subject: TAPi18n.__('email-invite-subject', params, lang),
  1154. text: TAPi18n.__('email-invite-text', params, lang),
  1155. });
  1156. } catch (e) {
  1157. throw new Meteor.Error('email-fail', e.message);
  1158. }
  1159. return {
  1160. username: user.username,
  1161. email: user.emails[0].address,
  1162. };
  1163. },
  1164. impersonate(userId) {
  1165. check(userId, String);
  1166. if (!Meteor.users.findOne(userId))
  1167. throw new Meteor.Error(404, 'User not found');
  1168. if (!Meteor.user().isAdmin)
  1169. throw new Meteor.Error(403, 'Permission denied');
  1170. ImpersonatedUsers.insert({ adminId: Meteor.user()._id, userId: userId, reason: 'clickedImpersonate' });
  1171. this.setUserId(userId);
  1172. },
  1173. isImpersonated(userId) {
  1174. check(userId, String);
  1175. const isImpersonated = ImpersonatedUsers.findOne({
  1176. userId: userId,
  1177. });
  1178. return isImpersonated;
  1179. },
  1180. });
  1181. Accounts.onCreateUser((options, user) => {
  1182. const userCount = Users.find().count();
  1183. if (userCount === 0) {
  1184. user.isAdmin = true;
  1185. return user;
  1186. }
  1187. if (user.services.oidc) {
  1188. let email = user.services.oidc.email;
  1189. if (Array.isArray(email)) {
  1190. email = email.shift();
  1191. }
  1192. email = email.toLowerCase();
  1193. user.username = user.services.oidc.username;
  1194. user.emails = [
  1195. {
  1196. address: email,
  1197. verified: true,
  1198. },
  1199. ];
  1200. const initials = user.services.oidc.fullname
  1201. .split(/\s+/)
  1202. .reduce((memo, word) => {
  1203. return memo + word[0];
  1204. }, '')
  1205. .toUpperCase();
  1206. user.profile = {
  1207. initials,
  1208. fullname: user.services.oidc.fullname,
  1209. boardView: 'board-view-swimlanes',
  1210. };
  1211. user.authenticationMethod = 'oauth2';
  1212. // see if any existing user has this email address or username, otherwise create new
  1213. const existingUser = Meteor.users.findOne({
  1214. $or: [
  1215. {
  1216. 'emails.address': email,
  1217. },
  1218. {
  1219. username: user.username,
  1220. },
  1221. ],
  1222. });
  1223. if (!existingUser) return user;
  1224. // copy across new service info
  1225. const service = _.keys(user.services)[0];
  1226. existingUser.services[service] = user.services[service];
  1227. existingUser.emails = user.emails;
  1228. existingUser.username = user.username;
  1229. existingUser.profile = user.profile;
  1230. existingUser.authenticationMethod = user.authenticationMethod;
  1231. Meteor.users.remove({
  1232. _id: user._id,
  1233. });
  1234. Meteor.users.remove({
  1235. _id: existingUser._id,
  1236. }); // is going to be created again
  1237. return existingUser;
  1238. }
  1239. if (options.from === 'admin') {
  1240. user.createdThroughApi = true;
  1241. return user;
  1242. }
  1243. const disableRegistration = Settings.findOne().disableRegistration;
  1244. // If this is the first Authentication by the ldap and self registration disabled
  1245. if (disableRegistration && options && options.ldap) {
  1246. user.authenticationMethod = 'ldap';
  1247. return user;
  1248. }
  1249. // If self registration enabled
  1250. if (!disableRegistration) {
  1251. return user;
  1252. }
  1253. if (!options || !options.profile) {
  1254. throw new Meteor.Error(
  1255. 'error-invitation-code-blank',
  1256. 'The invitation code is required',
  1257. );
  1258. }
  1259. const invitationCode = InvitationCodes.findOne({
  1260. code: options.profile.invitationcode,
  1261. email: options.email,
  1262. valid: true,
  1263. });
  1264. if (!invitationCode) {
  1265. throw new Meteor.Error(
  1266. 'error-invitation-code-not-exist',
  1267. // eslint-disable-next-line quotes
  1268. "The invitation code doesn't exist",
  1269. );
  1270. } else {
  1271. user.profile = {
  1272. icode: options.profile.invitationcode,
  1273. };
  1274. user.profile.boardView = 'board-view-swimlanes';
  1275. // Deletes the invitation code after the user was created successfully.
  1276. setTimeout(
  1277. Meteor.bindEnvironment(() => {
  1278. InvitationCodes.remove({
  1279. _id: invitationCode._id,
  1280. });
  1281. }),
  1282. 200,
  1283. );
  1284. return user;
  1285. }
  1286. });
  1287. }
  1288. const addCronJob = _.debounce(
  1289. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  1290. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  1291. const envRemoveAge =
  1292. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  1293. // default notifications will be removed 2 days after they are read
  1294. const defaultRemoveAge = 2;
  1295. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  1296. SyncedCron.add({
  1297. name: 'notification_cleanup',
  1298. schedule: (parser) => parser.text('every 1 days'),
  1299. job: () => {
  1300. for (const user of Users.find()) {
  1301. if (!user.profile || !user.profile.notifications) continue;
  1302. for (const notification of user.profile.notifications) {
  1303. if (notification.read) {
  1304. const removeDate = new Date(notification.read);
  1305. removeDate.setDate(removeDate.getDate() + removeAge);
  1306. if (removeDate <= new Date()) {
  1307. user.removeNotification(notification.activity);
  1308. }
  1309. }
  1310. }
  1311. }
  1312. },
  1313. });
  1314. SyncedCron.start();
  1315. }),
  1316. 500,
  1317. );
  1318. if (Meteor.isServer) {
  1319. // Let mongoDB ensure username unicity
  1320. Meteor.startup(() => {
  1321. allowedSortValues.forEach((value) => {
  1322. Lists._collection._ensureIndex(value);
  1323. });
  1324. Users._collection._ensureIndex({
  1325. modifiedAt: -1,
  1326. });
  1327. Users._collection._ensureIndex(
  1328. {
  1329. username: 1,
  1330. },
  1331. {
  1332. unique: true,
  1333. },
  1334. );
  1335. Meteor.defer(() => {
  1336. addCronJob();
  1337. });
  1338. });
  1339. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  1340. // if admin is removed, board is removed.
  1341. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  1342. // to use that board, and not have board deleted.
  1343. // Someone can be later changed to be admin of board, by making change to database.
  1344. // TODO: Add UI for changing someone as board admin.
  1345. //Users.before.remove((userId, doc) => {
  1346. // Boards
  1347. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  1348. // .forEach((board) => {
  1349. // // If only one admin for the board
  1350. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  1351. // Boards.remove(board._id);
  1352. // }
  1353. // });
  1354. //});
  1355. // Each board document contains the de-normalized number of users that have
  1356. // starred it. If the user star or unstar a board, we need to update this
  1357. // counter.
  1358. // We need to run this code on the server only, otherwise the incrementation
  1359. // will be done twice.
  1360. Users.after.update(function (userId, user, fieldNames) {
  1361. // The `starredBoards` list is hosted on the `profile` field. If this
  1362. // field hasn't been modificated we don't need to run this hook.
  1363. if (!_.contains(fieldNames, 'profile')) return;
  1364. // To calculate a diff of board starred ids, we get both the previous
  1365. // and the newly board ids list
  1366. function getStarredBoardsIds(doc) {
  1367. return doc.profile && doc.profile.starredBoards;
  1368. }
  1369. const oldIds = getStarredBoardsIds(this.previous);
  1370. const newIds = getStarredBoardsIds(user);
  1371. // The _.difference(a, b) method returns the values from a that are not in
  1372. // b. We use it to find deleted and newly inserted ids by using it in one
  1373. // direction and then in the other.
  1374. function incrementBoards(boardsIds, inc) {
  1375. boardsIds.forEach((boardId) => {
  1376. Boards.update(boardId, {
  1377. $inc: {
  1378. stars: inc,
  1379. },
  1380. });
  1381. });
  1382. }
  1383. incrementBoards(_.difference(oldIds, newIds), -1);
  1384. incrementBoards(_.difference(newIds, oldIds), +1);
  1385. });
  1386. // Override getUserId so that we can TODO get the current userId
  1387. const fakeUserId = new Meteor.EnvironmentVariable();
  1388. const getUserId = CollectionHooks.getUserId;
  1389. CollectionHooks.getUserId = () => {
  1390. return fakeUserId.get() || getUserId();
  1391. };
  1392. if (!isSandstorm) {
  1393. Users.after.insert((userId, doc) => {
  1394. const fakeUser = {
  1395. extendAutoValueContext: {
  1396. userId: doc._id,
  1397. },
  1398. };
  1399. fakeUserId.withValue(doc._id, () => {
  1400. /*
  1401. // Insert the Welcome Board
  1402. Boards.insert({
  1403. title: TAPi18n.__('welcome-board'),
  1404. permission: 'private',
  1405. }, fakeUser, (err, boardId) => {
  1406. Swimlanes.insert({
  1407. title: TAPi18n.__('welcome-swimlane'),
  1408. boardId,
  1409. sort: 1,
  1410. }, fakeUser);
  1411. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1412. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1413. });
  1414. });
  1415. */
  1416. const Future = require('fibers/future');
  1417. const future1 = new Future();
  1418. const future2 = new Future();
  1419. const future3 = new Future();
  1420. Boards.insert(
  1421. {
  1422. title: TAPi18n.__('templates'),
  1423. permission: 'private',
  1424. type: 'template-container',
  1425. },
  1426. fakeUser,
  1427. (err, boardId) => {
  1428. // Insert the reference to our templates board
  1429. Users.update(fakeUserId.get(), {
  1430. $set: {
  1431. 'profile.templatesBoardId': boardId,
  1432. },
  1433. });
  1434. // Insert the card templates swimlane
  1435. Swimlanes.insert(
  1436. {
  1437. title: TAPi18n.__('card-templates-swimlane'),
  1438. boardId,
  1439. sort: 1,
  1440. type: 'template-container',
  1441. },
  1442. fakeUser,
  1443. (err, swimlaneId) => {
  1444. // Insert the reference to out card templates swimlane
  1445. Users.update(fakeUserId.get(), {
  1446. $set: {
  1447. 'profile.cardTemplatesSwimlaneId': swimlaneId,
  1448. },
  1449. });
  1450. future1.return();
  1451. },
  1452. );
  1453. // Insert the list templates swimlane
  1454. Swimlanes.insert(
  1455. {
  1456. title: TAPi18n.__('list-templates-swimlane'),
  1457. boardId,
  1458. sort: 2,
  1459. type: 'template-container',
  1460. },
  1461. fakeUser,
  1462. (err, swimlaneId) => {
  1463. // Insert the reference to out list templates swimlane
  1464. Users.update(fakeUserId.get(), {
  1465. $set: {
  1466. 'profile.listTemplatesSwimlaneId': swimlaneId,
  1467. },
  1468. });
  1469. future2.return();
  1470. },
  1471. );
  1472. // Insert the board templates swimlane
  1473. Swimlanes.insert(
  1474. {
  1475. title: TAPi18n.__('board-templates-swimlane'),
  1476. boardId,
  1477. sort: 3,
  1478. type: 'template-container',
  1479. },
  1480. fakeUser,
  1481. (err, swimlaneId) => {
  1482. // Insert the reference to out board templates swimlane
  1483. Users.update(fakeUserId.get(), {
  1484. $set: {
  1485. 'profile.boardTemplatesSwimlaneId': swimlaneId,
  1486. },
  1487. });
  1488. future3.return();
  1489. },
  1490. );
  1491. },
  1492. );
  1493. // HACK
  1494. future1.wait();
  1495. future2.wait();
  1496. future3.wait();
  1497. });
  1498. });
  1499. }
  1500. Users.after.insert((userId, doc) => {
  1501. // HACK
  1502. doc = Users.findOne({
  1503. _id: doc._id,
  1504. });
  1505. if (doc.createdThroughApi) {
  1506. // The admin user should be able to create a user despite disabling registration because
  1507. // it is two different things (registration and creation).
  1508. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1509. // the disableRegistration check.
  1510. // Issue : https://github.com/wekan/wekan/issues/1232
  1511. // PR : https://github.com/wekan/wekan/pull/1251
  1512. Users.update(doc._id, {
  1513. $set: {
  1514. createdThroughApi: '',
  1515. },
  1516. });
  1517. return;
  1518. }
  1519. //invite user to corresponding boards
  1520. const disableRegistration = Settings.findOne().disableRegistration;
  1521. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1522. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1523. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1524. const invitationCode = InvitationCodes.findOne({
  1525. code: doc.profile.icode,
  1526. valid: true,
  1527. });
  1528. if (!invitationCode) {
  1529. throw new Meteor.Error('error-invitation-code-not-exist');
  1530. } else {
  1531. invitationCode.boardsToBeInvited.forEach((boardId) => {
  1532. const board = Boards.findOne(boardId);
  1533. board.addMember(doc._id);
  1534. });
  1535. if (!doc.profile) {
  1536. doc.profile = {};
  1537. }
  1538. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1539. Users.update(doc._id, {
  1540. $set: {
  1541. profile: doc.profile,
  1542. },
  1543. });
  1544. InvitationCodes.update(invitationCode._id, {
  1545. $set: {
  1546. valid: false,
  1547. },
  1548. });
  1549. }
  1550. }
  1551. });
  1552. }
  1553. // USERS REST API
  1554. if (Meteor.isServer) {
  1555. // Middleware which checks that API is enabled.
  1556. JsonRoutes.Middleware.use(function (req, res, next) {
  1557. const api = req.url.startsWith('/api');
  1558. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1559. return next();
  1560. } else {
  1561. res.writeHead(301, {
  1562. Location: '/',
  1563. });
  1564. return res.end();
  1565. }
  1566. });
  1567. /**
  1568. * @operation get_current_user
  1569. *
  1570. * @summary returns the current user
  1571. * @return_type Users
  1572. */
  1573. JsonRoutes.add('GET', '/api/user', function (req, res) {
  1574. try {
  1575. Authentication.checkLoggedIn(req.userId);
  1576. const data = Meteor.users.findOne({
  1577. _id: req.userId,
  1578. });
  1579. delete data.services;
  1580. // get all boards where the user is member of
  1581. let boards = Boards.find(
  1582. {
  1583. type: 'board',
  1584. 'members.userId': req.userId,
  1585. },
  1586. {
  1587. fields: {
  1588. _id: 1,
  1589. members: 1,
  1590. },
  1591. },
  1592. );
  1593. boards = boards.map((b) => {
  1594. const u = b.members.find((m) => m.userId === req.userId);
  1595. delete u.userId;
  1596. u.boardId = b._id;
  1597. return u;
  1598. });
  1599. data.boards = boards;
  1600. JsonRoutes.sendResult(res, {
  1601. code: 200,
  1602. data,
  1603. });
  1604. } catch (error) {
  1605. JsonRoutes.sendResult(res, {
  1606. code: 200,
  1607. data: error,
  1608. });
  1609. }
  1610. });
  1611. /**
  1612. * @operation get_all_users
  1613. *
  1614. * @summary return all the users
  1615. *
  1616. * @description Only the admin user (the first user) can call the REST API.
  1617. * @return_type [{ _id: string,
  1618. * username: string}]
  1619. */
  1620. JsonRoutes.add('GET', '/api/users', function (req, res) {
  1621. try {
  1622. Authentication.checkUserId(req.userId);
  1623. JsonRoutes.sendResult(res, {
  1624. code: 200,
  1625. data: Meteor.users.find({}).map(function (doc) {
  1626. return {
  1627. _id: doc._id,
  1628. username: doc.username,
  1629. };
  1630. }),
  1631. });
  1632. } catch (error) {
  1633. JsonRoutes.sendResult(res, {
  1634. code: 200,
  1635. data: error,
  1636. });
  1637. }
  1638. });
  1639. /**
  1640. * @operation get_user
  1641. *
  1642. * @summary get a given user
  1643. *
  1644. * @description Only the admin user (the first user) can call the REST API.
  1645. *
  1646. * @param {string} userId the user ID or username
  1647. * @return_type Users
  1648. */
  1649. JsonRoutes.add('GET', '/api/users/:userId', function (req, res) {
  1650. try {
  1651. Authentication.checkUserId(req.userId);
  1652. let id = req.params.userId;
  1653. let user = Meteor.users.findOne({
  1654. _id: id,
  1655. });
  1656. if (!user) {
  1657. user = Meteor.users.findOne({
  1658. username: id,
  1659. });
  1660. id = user._id;
  1661. }
  1662. // get all boards where the user is member of
  1663. let boards = Boards.find(
  1664. {
  1665. type: 'board',
  1666. 'members.userId': id,
  1667. },
  1668. {
  1669. fields: {
  1670. _id: 1,
  1671. members: 1,
  1672. },
  1673. },
  1674. );
  1675. boards = boards.map((b) => {
  1676. const u = b.members.find((m) => m.userId === id);
  1677. delete u.userId;
  1678. u.boardId = b._id;
  1679. return u;
  1680. });
  1681. user.boards = boards;
  1682. JsonRoutes.sendResult(res, {
  1683. code: 200,
  1684. data: user,
  1685. });
  1686. } catch (error) {
  1687. JsonRoutes.sendResult(res, {
  1688. code: 200,
  1689. data: error,
  1690. });
  1691. }
  1692. });
  1693. /**
  1694. * @operation edit_user
  1695. *
  1696. * @summary edit a given user
  1697. *
  1698. * @description Only the admin user (the first user) can call the REST API.
  1699. *
  1700. * Possible values for *action*:
  1701. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1702. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1703. * - `enableLogin`: Enable a user
  1704. *
  1705. * @param {string} userId the user ID
  1706. * @param {string} action the action
  1707. * @return_type {_id: string,
  1708. * title: string}
  1709. */
  1710. JsonRoutes.add('PUT', '/api/users/:userId', function (req, res) {
  1711. try {
  1712. Authentication.checkUserId(req.userId);
  1713. const id = req.params.userId;
  1714. const action = req.body.action;
  1715. let data = Meteor.users.findOne({
  1716. _id: id,
  1717. });
  1718. if (data !== undefined) {
  1719. if (action === 'takeOwnership') {
  1720. data = Boards.find(
  1721. {
  1722. 'members.userId': id,
  1723. 'members.isAdmin': true,
  1724. },
  1725. {
  1726. sort: {
  1727. sort: 1 /* boards default sorting */,
  1728. },
  1729. },
  1730. ).map(function (board) {
  1731. if (board.hasMember(req.userId)) {
  1732. board.removeMember(req.userId);
  1733. }
  1734. board.changeOwnership(id, req.userId);
  1735. return {
  1736. _id: board._id,
  1737. title: board.title,
  1738. };
  1739. });
  1740. } else {
  1741. if (action === 'disableLogin' && id !== req.userId) {
  1742. Users.update(
  1743. {
  1744. _id: id,
  1745. },
  1746. {
  1747. $set: {
  1748. loginDisabled: true,
  1749. 'services.resume.loginTokens': '',
  1750. },
  1751. },
  1752. );
  1753. } else if (action === 'enableLogin') {
  1754. Users.update(
  1755. {
  1756. _id: id,
  1757. },
  1758. {
  1759. $set: {
  1760. loginDisabled: '',
  1761. },
  1762. },
  1763. );
  1764. }
  1765. data = Meteor.users.findOne({
  1766. _id: id,
  1767. });
  1768. }
  1769. }
  1770. JsonRoutes.sendResult(res, {
  1771. code: 200,
  1772. data,
  1773. });
  1774. } catch (error) {
  1775. JsonRoutes.sendResult(res, {
  1776. code: 200,
  1777. data: error,
  1778. });
  1779. }
  1780. });
  1781. /**
  1782. * @operation add_board_member
  1783. * @tag Boards
  1784. *
  1785. * @summary Add New Board Member with Role
  1786. *
  1787. * @description Only the admin user (the first user) can call the REST API.
  1788. *
  1789. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1790. * to later change the permissions.
  1791. *
  1792. * @param {string} boardId the board ID
  1793. * @param {string} userId the user ID
  1794. * @param {boolean} isAdmin is the user an admin of the board
  1795. * @param {boolean} isNoComments disable comments
  1796. * @param {boolean} isCommentOnly only enable comments
  1797. * @return_type {_id: string,
  1798. * title: string}
  1799. */
  1800. JsonRoutes.add(
  1801. 'POST',
  1802. '/api/boards/:boardId/members/:userId/add',
  1803. function (req, res) {
  1804. try {
  1805. Authentication.checkUserId(req.userId);
  1806. const userId = req.params.userId;
  1807. const boardId = req.params.boardId;
  1808. const action = req.body.action;
  1809. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1810. let data = Meteor.users.findOne({
  1811. _id: userId,
  1812. });
  1813. if (data !== undefined) {
  1814. if (action === 'add') {
  1815. data = Boards.find({
  1816. _id: boardId,
  1817. }).map(function (board) {
  1818. if (!board.hasMember(userId)) {
  1819. board.addMember(userId);
  1820. function isTrue(data) {
  1821. return data.toLowerCase() === 'true';
  1822. }
  1823. board.setMemberPermission(
  1824. userId,
  1825. isTrue(isAdmin),
  1826. isTrue(isNoComments),
  1827. isTrue(isCommentOnly),
  1828. userId,
  1829. );
  1830. }
  1831. return {
  1832. _id: board._id,
  1833. title: board.title,
  1834. };
  1835. });
  1836. }
  1837. }
  1838. JsonRoutes.sendResult(res, {
  1839. code: 200,
  1840. data: query,
  1841. });
  1842. } catch (error) {
  1843. JsonRoutes.sendResult(res, {
  1844. code: 200,
  1845. data: error,
  1846. });
  1847. }
  1848. },
  1849. );
  1850. /**
  1851. * @operation remove_board_member
  1852. * @tag Boards
  1853. *
  1854. * @summary Remove Member from Board
  1855. *
  1856. * @description Only the admin user (the first user) can call the REST API.
  1857. *
  1858. * @param {string} boardId the board ID
  1859. * @param {string} userId the user ID
  1860. * @param {string} action the action (needs to be `remove`)
  1861. * @return_type {_id: string,
  1862. * title: string}
  1863. */
  1864. JsonRoutes.add(
  1865. 'POST',
  1866. '/api/boards/:boardId/members/:userId/remove',
  1867. function (req, res) {
  1868. try {
  1869. Authentication.checkUserId(req.userId);
  1870. const userId = req.params.userId;
  1871. const boardId = req.params.boardId;
  1872. const action = req.body.action;
  1873. let data = Meteor.users.findOne({
  1874. _id: userId,
  1875. });
  1876. if (data !== undefined) {
  1877. if (action === 'remove') {
  1878. data = Boards.find({
  1879. _id: boardId,
  1880. }).map(function (board) {
  1881. if (board.hasMember(userId)) {
  1882. board.removeMember(userId);
  1883. }
  1884. return {
  1885. _id: board._id,
  1886. title: board.title,
  1887. };
  1888. });
  1889. }
  1890. }
  1891. JsonRoutes.sendResult(res, {
  1892. code: 200,
  1893. data: query,
  1894. });
  1895. } catch (error) {
  1896. JsonRoutes.sendResult(res, {
  1897. code: 200,
  1898. data: error,
  1899. });
  1900. }
  1901. },
  1902. );
  1903. /**
  1904. * @operation new_user
  1905. *
  1906. * @summary Create a new user
  1907. *
  1908. * @description Only the admin user (the first user) can call the REST API.
  1909. *
  1910. * @param {string} username the new username
  1911. * @param {string} email the email of the new user
  1912. * @param {string} password the password of the new user
  1913. * @return_type {_id: string}
  1914. */
  1915. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  1916. try {
  1917. Authentication.checkUserId(req.userId);
  1918. const id = Accounts.createUser({
  1919. username: req.body.username,
  1920. email: req.body.email,
  1921. password: req.body.password,
  1922. from: 'admin',
  1923. });
  1924. JsonRoutes.sendResult(res, {
  1925. code: 200,
  1926. data: {
  1927. _id: id,
  1928. },
  1929. });
  1930. } catch (error) {
  1931. JsonRoutes.sendResult(res, {
  1932. code: 200,
  1933. data: error,
  1934. });
  1935. }
  1936. });
  1937. /**
  1938. * @operation delete_user
  1939. *
  1940. * @summary Delete a user
  1941. *
  1942. * @description Only the admin user (the first user) can call the REST API.
  1943. *
  1944. * @param {string} userId the ID of the user to delete
  1945. * @return_type {_id: string}
  1946. */
  1947. JsonRoutes.add('DELETE', '/api/users/:userId', function (req, res) {
  1948. try {
  1949. Authentication.checkUserId(req.userId);
  1950. const id = req.params.userId;
  1951. // Delete is not enabled yet, because it does leave empty user avatars
  1952. // to boards: boards members, card members and assignees have
  1953. // empty users. See:
  1954. // - wekan/client/components/settings/peopleBody.jade deleteButton
  1955. // - wekan/client/components/settings/peopleBody.js deleteButton
  1956. // - wekan/client/components/sidebar/sidebar.js Popup.afterConfirm('removeMember'
  1957. // that does now remove member from board, card members and assignees correctly,
  1958. // but that should be used to remove user from all boards similarly
  1959. // - wekan/models/users.js Delete is not enabled
  1960. // Meteor.users.remove({ _id: id });
  1961. JsonRoutes.sendResult(res, {
  1962. code: 200,
  1963. data: {
  1964. _id: id,
  1965. },
  1966. });
  1967. } catch (error) {
  1968. JsonRoutes.sendResult(res, {
  1969. code: 200,
  1970. data: error,
  1971. });
  1972. }
  1973. });
  1974. /**
  1975. * @operation create_user_token
  1976. *
  1977. * @summary Create a user token
  1978. *
  1979. * @description Only the admin user (the first user) can call the REST API.
  1980. *
  1981. * @param {string} userId the ID of the user to create token for.
  1982. * @return_type {_id: string}
  1983. */
  1984. JsonRoutes.add('POST', '/api/createtoken/:userId', function (req, res) {
  1985. try {
  1986. Authentication.checkUserId(req.userId);
  1987. const id = req.params.userId;
  1988. const token = Accounts._generateStampedLoginToken();
  1989. Accounts._insertLoginToken(id, token);
  1990. JsonRoutes.sendResult(res, {
  1991. code: 200,
  1992. data: {
  1993. _id: id,
  1994. authToken: token.token,
  1995. },
  1996. });
  1997. } catch (error) {
  1998. JsonRoutes.sendResult(res, {
  1999. code: 200,
  2000. data: error,
  2001. });
  2002. }
  2003. });
  2004. }
  2005. export default Users;