users.js 54 KB

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