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. teamIds() {
  505. if (this.teams) {
  506. return this.teams.map(team => { return team.teamId });
  507. }
  508. return [];
  509. },
  510. orgIds() {
  511. if (this.orgs) {
  512. return this.orgs.map(org => { return org.orgId });
  513. }
  514. return [];
  515. },
  516. orgsUserBelongs() {
  517. if (this.orgs) {
  518. return this.orgs.map(function(org){return org.orgDisplayName}).sort().join(',');
  519. }
  520. return '';
  521. },
  522. orgIdsUserBelongs() {
  523. if (this.orgs) {
  524. return this.orgs.map(function(org){return org.orgId}).join(',');
  525. }
  526. return '';
  527. },
  528. teamsUserBelongs() {
  529. if (this.teams) {
  530. return this.teams.map(function(team){ return team.teamDisplayName}).sort().join(',');
  531. }
  532. return '';
  533. },
  534. teamIdsUserBelongs() {
  535. if (this.teams) {
  536. return this.teams.map(function(team){ return team.teamId}).join(',');
  537. }
  538. return '';
  539. },
  540. boards() {
  541. return Boards.userBoards(this._id, null, {}, { sort: { sort: 1 } })
  542. },
  543. starredBoards() {
  544. const { starredBoards = [] } = this.profile || {};
  545. return Boards.userBoards(
  546. this._id,
  547. false,
  548. { _id: { $in: starredBoards } },
  549. { sort: { sort: 1 } }
  550. );
  551. },
  552. hasStarred(boardId) {
  553. const { starredBoards = [] } = this.profile || {};
  554. return _.contains(starredBoards, boardId);
  555. },
  556. invitedBoards() {
  557. const { invitedBoards = [] } = this.profile || {};
  558. return Boards.userBoards(
  559. this._id,
  560. false,
  561. { _id: { $in: invitedBoards } },
  562. { sort: { sort: 1 } }
  563. );
  564. },
  565. isInvitedTo(boardId) {
  566. const { invitedBoards = [] } = this.profile || {};
  567. return _.contains(invitedBoards, boardId);
  568. },
  569. _getListSortBy() {
  570. const profile = this.profile || {};
  571. const sortBy = profile.listSortBy || defaultSortBy;
  572. const keyPattern = /^(-{0,1})(.*$)/;
  573. const ret = [];
  574. if (keyPattern.exec(sortBy)) {
  575. ret[0] = RegExp.$2;
  576. ret[1] = RegExp.$1 ? -1 : 1;
  577. }
  578. return ret;
  579. },
  580. hasSortBy() {
  581. // if use doesn't have dragHandle, then we can let user to choose sort list by different order
  582. return !this.hasShowDesktopDragHandles();
  583. },
  584. getListSortBy() {
  585. return this._getListSortBy()[0];
  586. },
  587. getListSortTypes() {
  588. return allowedSortValues;
  589. },
  590. getListSortByDirection() {
  591. return this._getListSortBy()[1];
  592. },
  593. hasTag(tag) {
  594. const { tags = [] } = this.profile || {};
  595. return _.contains(tags, tag);
  596. },
  597. hasNotification(activityId) {
  598. const { notifications = [] } = this.profile || {};
  599. return _.contains(notifications, activityId);
  600. },
  601. notifications() {
  602. const { notifications = [] } = this.profile || {};
  603. for (const index in notifications) {
  604. if (!notifications.hasOwnProperty(index)) continue;
  605. const notification = notifications[index];
  606. // this preserves their db sort order for editing
  607. notification.dbIndex = index;
  608. notification.activity = Activities.findOne(notification.activity);
  609. }
  610. // this sorts them newest to oldest to match Trello's behavior
  611. notifications.reverse();
  612. return notifications;
  613. },
  614. hasShowDesktopDragHandles() {
  615. const profile = this.profile || {};
  616. return profile.showDesktopDragHandles || false;
  617. },
  618. hasHideCheckedItems() {
  619. const profile = this.profile || {};
  620. return profile.hideCheckedItems || false;
  621. },
  622. hasHiddenSystemMessages() {
  623. const profile = this.profile || {};
  624. return profile.hiddenSystemMessages || false;
  625. },
  626. hasCustomFieldsGrid() {
  627. const profile = this.profile || {};
  628. return profile.customFieldsGrid || false;
  629. },
  630. hasCardMaximized() {
  631. const profile = this.profile || {};
  632. return profile.cardMaximized || false;
  633. },
  634. hasHiddenMinicardLabelText() {
  635. const profile = this.profile || {};
  636. return profile.hiddenMinicardLabelText || false;
  637. },
  638. getEmailBuffer() {
  639. const { emailBuffer = [] } = this.profile || {};
  640. return emailBuffer;
  641. },
  642. getInitials() {
  643. const profile = this.profile || {};
  644. if (profile.initials) return profile.initials;
  645. else if (profile.fullname) {
  646. return profile.fullname
  647. .split(/\s+/)
  648. .reduce((memo, word) => {
  649. return memo + word[0];
  650. }, '')
  651. .toUpperCase();
  652. } else {
  653. return this.username[0].toUpperCase();
  654. }
  655. },
  656. getLimitToShowCardsCount() {
  657. const profile = this.profile || {};
  658. return profile.showCardsCountAt;
  659. },
  660. getName() {
  661. const profile = this.profile || {};
  662. return profile.fullname || this.username;
  663. },
  664. getLanguage() {
  665. const profile = this.profile || {};
  666. return profile.language || 'en';
  667. },
  668. getStartDayOfWeek() {
  669. const profile = this.profile || {};
  670. if (typeof profile.startDayOfWeek === 'undefined') {
  671. // default is 'Monday' (1)
  672. return 1;
  673. }
  674. return profile.startDayOfWeek;
  675. },
  676. getTemplatesBoardId() {
  677. return (this.profile || {}).templatesBoardId;
  678. },
  679. getTemplatesBoardSlug() {
  680. return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  681. },
  682. remove() {
  683. User.remove({
  684. _id: this._id,
  685. });
  686. },
  687. });
  688. Users.mutations({
  689. toggleBoardStar(boardId) {
  690. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  691. return {
  692. [queryKind]: {
  693. 'profile.starredBoards': boardId,
  694. },
  695. };
  696. },
  697. addInvite(boardId) {
  698. return {
  699. $addToSet: {
  700. 'profile.invitedBoards': boardId,
  701. },
  702. };
  703. },
  704. removeInvite(boardId) {
  705. return {
  706. $pull: {
  707. 'profile.invitedBoards': boardId,
  708. },
  709. };
  710. },
  711. addTag(tag) {
  712. return {
  713. $addToSet: {
  714. 'profile.tags': tag,
  715. },
  716. };
  717. },
  718. removeTag(tag) {
  719. return {
  720. $pull: {
  721. 'profile.tags': tag,
  722. },
  723. };
  724. },
  725. toggleTag(tag) {
  726. if (this.hasTag(tag)) this.removeTag(tag);
  727. else this.addTag(tag);
  728. },
  729. setListSortBy(value) {
  730. return {
  731. $set: {
  732. 'profile.listSortBy': value,
  733. },
  734. };
  735. },
  736. setName(value) {
  737. return {
  738. $set: {
  739. 'profile.fullname': value,
  740. },
  741. };
  742. },
  743. toggleDesktopHandles(value = false) {
  744. return {
  745. $set: {
  746. 'profile.showDesktopDragHandles': !value,
  747. },
  748. };
  749. },
  750. toggleHideCheckedItems() {
  751. const value = this.hasHideCheckedItems();
  752. return {
  753. $set: {
  754. 'profile.hideCheckedItems': !value,
  755. },
  756. };
  757. },
  758. toggleSystem(value = false) {
  759. return {
  760. $set: {
  761. 'profile.hiddenSystemMessages': !value,
  762. },
  763. };
  764. },
  765. toggleFieldsGrid(value = false) {
  766. return {
  767. $set: {
  768. 'profile.customFieldsGrid': !value,
  769. },
  770. };
  771. },
  772. toggleCardMaximized(value = false) {
  773. return {
  774. $set: {
  775. 'profile.cardMaximized': !value,
  776. },
  777. };
  778. },
  779. toggleLabelText(value = false) {
  780. return {
  781. $set: {
  782. 'profile.hiddenMinicardLabelText': !value,
  783. },
  784. };
  785. },
  786. addNotification(activityId) {
  787. return {
  788. $addToSet: {
  789. 'profile.notifications': {
  790. activity: activityId,
  791. },
  792. },
  793. };
  794. },
  795. removeNotification(activityId) {
  796. return {
  797. $pull: {
  798. 'profile.notifications': {
  799. activity: activityId,
  800. },
  801. },
  802. };
  803. },
  804. addEmailBuffer(text) {
  805. return {
  806. $addToSet: {
  807. 'profile.emailBuffer': text,
  808. },
  809. };
  810. },
  811. clearEmailBuffer() {
  812. return {
  813. $set: {
  814. 'profile.emailBuffer': [],
  815. },
  816. };
  817. },
  818. setAvatarUrl(avatarUrl) {
  819. return {
  820. $set: {
  821. 'profile.avatarUrl': avatarUrl,
  822. },
  823. };
  824. },
  825. setShowCardsCountAt(limit) {
  826. return {
  827. $set: {
  828. 'profile.showCardsCountAt': limit,
  829. },
  830. };
  831. },
  832. setStartDayOfWeek(startDay) {
  833. return {
  834. $set: {
  835. 'profile.startDayOfWeek': startDay,
  836. },
  837. };
  838. },
  839. setBoardView(view) {
  840. return {
  841. $set: {
  842. 'profile.boardView': view,
  843. },
  844. };
  845. },
  846. });
  847. Meteor.methods({
  848. setListSortBy(value) {
  849. check(value, String);
  850. Meteor.user().setListSortBy(value);
  851. },
  852. toggleDesktopDragHandles() {
  853. const user = Meteor.user();
  854. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  855. },
  856. toggleHideCheckedItems() {
  857. const user = Meteor.user();
  858. user.toggleHideCheckedItems();
  859. },
  860. toggleSystemMessages() {
  861. const user = Meteor.user();
  862. user.toggleSystem(user.hasHiddenSystemMessages());
  863. },
  864. toggleCustomFieldsGrid() {
  865. const user = Meteor.user();
  866. user.toggleFieldsGrid(user.hasCustomFieldsGrid());
  867. },
  868. toggleCardMaximized() {
  869. const user = Meteor.user();
  870. user.toggleCardMaximized(user.hasCardMaximized());
  871. },
  872. toggleMinicardLabelText() {
  873. const user = Meteor.user();
  874. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  875. },
  876. changeLimitToShowCardsCount(limit) {
  877. check(limit, Number);
  878. Meteor.user().setShowCardsCountAt(limit);
  879. },
  880. changeStartDayOfWeek(startDay) {
  881. check(startDay, Number);
  882. Meteor.user().setStartDayOfWeek(startDay);
  883. },
  884. });
  885. if (Meteor.isServer) {
  886. Meteor.methods({
  887. setAllUsersHideSystemMessages() {
  888. if (Meteor.user() && Meteor.user().isAdmin) {
  889. // If setting is missing, add it
  890. Users.update(
  891. {
  892. 'profile.hiddenSystemMessages': {
  893. $exists: false,
  894. },
  895. },
  896. {
  897. $set: {
  898. 'profile.hiddenSystemMessages': true,
  899. },
  900. },
  901. {
  902. multi: true,
  903. },
  904. );
  905. // If setting is false, set it to true
  906. Users.update(
  907. {
  908. 'profile.hiddenSystemMessages': false,
  909. },
  910. {
  911. $set: {
  912. 'profile.hiddenSystemMessages': true,
  913. },
  914. },
  915. {
  916. multi: true,
  917. },
  918. );
  919. return true;
  920. } else {
  921. return false;
  922. }
  923. },
  924. setCreateUser(
  925. fullname,
  926. username,
  927. initials,
  928. password,
  929. isAdmin,
  930. isActive,
  931. email,
  932. importUsernames,
  933. userOrgsArray,
  934. userTeamsArray,
  935. ) {
  936. check(fullname, String);
  937. check(username, String);
  938. check(initials, String);
  939. check(password, String);
  940. check(isAdmin, String);
  941. check(isActive, String);
  942. check(email, String);
  943. check(importUsernames, Array);
  944. check(userOrgsArray, Array);
  945. check(userTeamsArray, Array);
  946. if (Meteor.user() && Meteor.user().isAdmin) {
  947. const nUsersWithUsername = Users.find({
  948. username,
  949. }).count();
  950. const nUsersWithEmail = Users.find({
  951. email,
  952. }).count();
  953. if (nUsersWithUsername > 0) {
  954. throw new Meteor.Error('username-already-taken');
  955. } else if (nUsersWithEmail > 0) {
  956. throw new Meteor.Error('email-already-taken');
  957. } else {
  958. Accounts.createUser({
  959. username,
  960. password,
  961. isAdmin,
  962. isActive,
  963. email: email.toLowerCase(),
  964. from: 'admin',
  965. });
  966. const user =
  967. Users.findOne(username) ||
  968. Users.findOne({
  969. username,
  970. });
  971. if (user) {
  972. Users.update(user._id, {
  973. $set: {
  974. 'profile.fullname': fullname,
  975. importUsernames,
  976. 'profile.initials': initials,
  977. orgs: userOrgsArray,
  978. teams: userTeamsArray,
  979. },
  980. });
  981. }
  982. }
  983. }
  984. },
  985. setUsername(username, userId) {
  986. check(username, String);
  987. check(userId, String);
  988. if (Meteor.user() && Meteor.user().isAdmin) {
  989. const nUsersWithUsername = Users.find({
  990. username,
  991. }).count();
  992. if (nUsersWithUsername > 0) {
  993. throw new Meteor.Error('username-already-taken');
  994. } else {
  995. Users.update(userId, {
  996. $set: {
  997. username,
  998. },
  999. });
  1000. }
  1001. }
  1002. },
  1003. setEmail(email, userId) {
  1004. check(email, String);
  1005. check(username, String);
  1006. if (Meteor.user() && Meteor.user().isAdmin) {
  1007. if (Array.isArray(email)) {
  1008. email = email.shift();
  1009. }
  1010. const existingUser = Users.findOne(
  1011. {
  1012. 'emails.address': email,
  1013. },
  1014. {
  1015. fields: {
  1016. _id: 1,
  1017. },
  1018. },
  1019. );
  1020. if (existingUser) {
  1021. throw new Meteor.Error('email-already-taken');
  1022. } else {
  1023. Users.update(userId, {
  1024. $set: {
  1025. emails: [
  1026. {
  1027. address: email,
  1028. verified: false,
  1029. },
  1030. ],
  1031. },
  1032. });
  1033. }
  1034. }
  1035. },
  1036. setUsernameAndEmail(username, email, userId) {
  1037. check(username, String);
  1038. check(email, String);
  1039. check(userId, String);
  1040. if (Meteor.user() && Meteor.user().isAdmin) {
  1041. if (Array.isArray(email)) {
  1042. email = email.shift();
  1043. }
  1044. Meteor.call('setUsername', username, userId);
  1045. Meteor.call('setEmail', email, userId);
  1046. }
  1047. },
  1048. setPassword(newPassword, userId) {
  1049. check(userId, String);
  1050. check(newPassword, String);
  1051. if (Meteor.user() && Meteor.user().isAdmin) {
  1052. if (Meteor.user().isAdmin) {
  1053. Accounts.setPassword(userId, newPassword);
  1054. }
  1055. }
  1056. },
  1057. setEmailVerified(email, verified, userId) {
  1058. check(email, String);
  1059. check(verified, Boolean);
  1060. check(userId, String);
  1061. if (Meteor.user() && Meteor.user().isAdmin) {
  1062. Users.update(userId, {
  1063. $set: {
  1064. emails: [
  1065. {
  1066. address: email,
  1067. verified,
  1068. },
  1069. ],
  1070. },
  1071. });
  1072. }
  1073. },
  1074. setInitials(initials, userId) {
  1075. check(initials, String);
  1076. check(userId, String);
  1077. if (Meteor.user() && Meteor.user().isAdmin) {
  1078. Users.update(userId, {
  1079. $set: {
  1080. 'profile.initials': initials,
  1081. },
  1082. });
  1083. }
  1084. },
  1085. // we accept userId, username, email
  1086. inviteUserToBoard(username, boardId) {
  1087. check(username, String);
  1088. check(boardId, String);
  1089. const inviter = Meteor.user();
  1090. const board = Boards.findOne(boardId);
  1091. const allowInvite =
  1092. inviter &&
  1093. board &&
  1094. board.members &&
  1095. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  1096. _.where(board.members, {
  1097. userId: inviter._id,
  1098. })[0].isActive;
  1099. // GitHub issue 2060
  1100. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  1101. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  1102. this.unblock();
  1103. const posAt = username.indexOf('@');
  1104. let user = null;
  1105. if (posAt >= 0) {
  1106. user = Users.findOne({
  1107. emails: {
  1108. $elemMatch: {
  1109. address: username,
  1110. },
  1111. },
  1112. });
  1113. } else {
  1114. user =
  1115. Users.findOne(username) ||
  1116. Users.findOne({
  1117. username,
  1118. });
  1119. }
  1120. if (user) {
  1121. if (user._id === inviter._id)
  1122. throw new Meteor.Error('error-user-notAllowSelf');
  1123. } else {
  1124. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  1125. if (
  1126. Settings.findOne({
  1127. disableRegistration: true,
  1128. })
  1129. ) {
  1130. throw new Meteor.Error('error-user-notCreated');
  1131. }
  1132. // Set in lowercase email before creating account
  1133. const email = username.toLowerCase();
  1134. username = email.substring(0, posAt);
  1135. const newUserId = Accounts.createUser({
  1136. username,
  1137. email,
  1138. });
  1139. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  1140. // assume new user speak same language with inviter
  1141. if (inviter.profile && inviter.profile.language) {
  1142. Users.update(newUserId, {
  1143. $set: {
  1144. 'profile.language': inviter.profile.language,
  1145. },
  1146. });
  1147. }
  1148. Accounts.sendEnrollmentEmail(newUserId);
  1149. user = Users.findOne(newUserId);
  1150. }
  1151. board.addMember(user._id);
  1152. user.addInvite(boardId);
  1153. //Check if there is a subtasks board
  1154. if (board.subtasksDefaultBoardId) {
  1155. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  1156. //If there is, also add user to that board
  1157. if (subBoard) {
  1158. subBoard.addMember(user._id);
  1159. user.addInvite(subBoard._id);
  1160. }
  1161. }
  1162. try {
  1163. const fullName = inviter.profile !== undefined && inviter.profile.fullname !== undefined ? inviter.profile.fullname : "";
  1164. const userFullName = user.profile !== undefined && user.profile.fullname !== undefined ? user.profile.fullname : "";
  1165. const params = {
  1166. user: userFullName != "" ? userFullName + " (" + user.username + " )" : user.username,
  1167. inviter: fullName != "" ? fullName + " (" + inviter.username + " )" : inviter.username,
  1168. board: board.title,
  1169. url: board.absoluteUrl(),
  1170. };
  1171. const lang = user.getLanguage();
  1172. /*
  1173. if (process.env.MAIL_SERVICE !== '') {
  1174. let transporter = nodemailer.createTransport({
  1175. service: process.env.MAIL_SERVICE,
  1176. auth: {
  1177. user: process.env.MAIL_SERVICE_USER,
  1178. pass: process.env.MAIL_SERVICE_PASSWORD
  1179. },
  1180. })
  1181. let info = transporter.sendMail({
  1182. to: user.emails[0].address.toLowerCase(),
  1183. from: Accounts.emailTemplates.from,
  1184. subject: TAPi18n.__('email-invite-subject', params, lang),
  1185. text: TAPi18n.__('email-invite-text', params, lang),
  1186. })
  1187. } else {
  1188. Email.send({
  1189. to: user.emails[0].address.toLowerCase(),
  1190. from: Accounts.emailTemplates.from,
  1191. subject: TAPi18n.__('email-invite-subject', params, lang),
  1192. text: TAPi18n.__('email-invite-text', params, lang),
  1193. });
  1194. }
  1195. */
  1196. Email.send({
  1197. to: user.emails[0].address.toLowerCase(),
  1198. from: Accounts.emailTemplates.from,
  1199. subject: TAPi18n.__('email-invite-subject', params, lang),
  1200. text: TAPi18n.__('email-invite-text', params, lang),
  1201. });
  1202. } catch (e) {
  1203. throw new Meteor.Error('email-fail', e.message);
  1204. }
  1205. return {
  1206. username: user.username,
  1207. email: user.emails[0].address,
  1208. };
  1209. },
  1210. impersonate(userId) {
  1211. check(userId, String);
  1212. if (!Meteor.users.findOne(userId))
  1213. throw new Meteor.Error(404, 'User not found');
  1214. if (!Meteor.user().isAdmin)
  1215. throw new Meteor.Error(403, 'Permission denied');
  1216. ImpersonatedUsers.insert({ adminId: Meteor.user()._id, userId: userId, reason: 'clickedImpersonate' });
  1217. this.setUserId(userId);
  1218. },
  1219. isImpersonated(userId) {
  1220. check(userId, String);
  1221. const isImpersonated = ImpersonatedUsers.findOne({
  1222. userId: userId,
  1223. });
  1224. return isImpersonated;
  1225. },
  1226. });
  1227. Accounts.onCreateUser((options, user) => {
  1228. const userCount = Users.find().count();
  1229. if (userCount === 0) {
  1230. user.isAdmin = true;
  1231. }
  1232. if (user.services.oidc) {
  1233. let email = user.services.oidc.email;
  1234. if (Array.isArray(email)) {
  1235. email = email.shift();
  1236. }
  1237. email = email.toLowerCase();
  1238. user.username = user.services.oidc.username;
  1239. user.emails = [
  1240. {
  1241. address: email,
  1242. verified: true,
  1243. },
  1244. ];
  1245. const initials = user.services.oidc.fullname
  1246. .split(/\s+/)
  1247. .reduce((memo, word) => {
  1248. return memo + word[0];
  1249. }, '')
  1250. .toUpperCase();
  1251. user.profile = {
  1252. initials,
  1253. fullname: user.services.oidc.fullname,
  1254. boardView: 'board-view-swimlanes',
  1255. };
  1256. user.authenticationMethod = 'oauth2';
  1257. // see if any existing user has this email address or username, otherwise create new
  1258. const existingUser = Meteor.users.findOne({
  1259. $or: [
  1260. {
  1261. 'emails.address': email,
  1262. },
  1263. {
  1264. username: user.username,
  1265. },
  1266. ],
  1267. });
  1268. if (!existingUser) return user;
  1269. // copy across new service info
  1270. const service = _.keys(user.services)[0];
  1271. existingUser.services[service] = user.services[service];
  1272. existingUser.emails = user.emails;
  1273. existingUser.username = user.username;
  1274. existingUser.profile = user.profile;
  1275. existingUser.authenticationMethod = user.authenticationMethod;
  1276. Meteor.users.remove({
  1277. _id: user._id,
  1278. });
  1279. Meteor.users.remove({
  1280. _id: existingUser._id,
  1281. }); // is going to be created again
  1282. return existingUser;
  1283. }
  1284. if (options.from === 'admin') {
  1285. user.createdThroughApi = true;
  1286. return user;
  1287. }
  1288. const disableRegistration = Settings.findOne().disableRegistration;
  1289. // If this is the first Authentication by the ldap and self registration disabled
  1290. if (disableRegistration && options && options.ldap) {
  1291. user.authenticationMethod = 'ldap';
  1292. return user;
  1293. }
  1294. // If self registration enabled
  1295. if (!disableRegistration) {
  1296. return user;
  1297. }
  1298. if (!options || !options.profile) {
  1299. throw new Meteor.Error(
  1300. 'error-invitation-code-blank',
  1301. 'The invitation code is required',
  1302. );
  1303. }
  1304. const invitationCode = InvitationCodes.findOne({
  1305. code: options.profile.invitationcode,
  1306. email: options.email,
  1307. valid: true,
  1308. });
  1309. if (!invitationCode) {
  1310. throw new Meteor.Error(
  1311. 'error-invitation-code-not-exist',
  1312. // eslint-disable-next-line quotes
  1313. "The invitation code doesn't exist",
  1314. );
  1315. } else {
  1316. user.profile = {
  1317. icode: options.profile.invitationcode,
  1318. };
  1319. user.profile.boardView = 'board-view-swimlanes';
  1320. // Deletes the invitation code after the user was created successfully.
  1321. setTimeout(
  1322. Meteor.bindEnvironment(() => {
  1323. InvitationCodes.remove({
  1324. _id: invitationCode._id,
  1325. });
  1326. }),
  1327. 200,
  1328. );
  1329. return user;
  1330. }
  1331. });
  1332. }
  1333. const addCronJob = _.debounce(
  1334. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  1335. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  1336. const envRemoveAge =
  1337. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  1338. // default notifications will be removed 2 days after they are read
  1339. const defaultRemoveAge = 2;
  1340. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  1341. SyncedCron.add({
  1342. name: 'notification_cleanup',
  1343. schedule: (parser) => parser.text('every 1 days'),
  1344. job: () => {
  1345. for (const user of Users.find()) {
  1346. if (!user.profile || !user.profile.notifications) continue;
  1347. for (const notification of user.profile.notifications) {
  1348. if (notification.read) {
  1349. const removeDate = new Date(notification.read);
  1350. removeDate.setDate(removeDate.getDate() + removeAge);
  1351. if (removeDate <= new Date()) {
  1352. user.removeNotification(notification.activity);
  1353. }
  1354. }
  1355. }
  1356. }
  1357. },
  1358. });
  1359. SyncedCron.start();
  1360. }),
  1361. 500,
  1362. );
  1363. if (Meteor.isServer) {
  1364. // Let mongoDB ensure username unicity
  1365. Meteor.startup(() => {
  1366. allowedSortValues.forEach((value) => {
  1367. Lists._collection._ensureIndex(value);
  1368. });
  1369. Users._collection._ensureIndex({
  1370. modifiedAt: -1,
  1371. });
  1372. Users._collection._ensureIndex(
  1373. {
  1374. username: 1,
  1375. },
  1376. {
  1377. unique: true,
  1378. },
  1379. );
  1380. Meteor.defer(() => {
  1381. addCronJob();
  1382. });
  1383. });
  1384. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  1385. // if admin is removed, board is removed.
  1386. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  1387. // to use that board, and not have board deleted.
  1388. // Someone can be later changed to be admin of board, by making change to database.
  1389. // TODO: Add UI for changing someone as board admin.
  1390. //Users.before.remove((userId, doc) => {
  1391. // Boards
  1392. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  1393. // .forEach((board) => {
  1394. // // If only one admin for the board
  1395. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  1396. // Boards.remove(board._id);
  1397. // }
  1398. // });
  1399. //});
  1400. // Each board document contains the de-normalized number of users that have
  1401. // starred it. If the user star or unstar a board, we need to update this
  1402. // counter.
  1403. // We need to run this code on the server only, otherwise the incrementation
  1404. // will be done twice.
  1405. Users.after.update(function (userId, user, fieldNames) {
  1406. // The `starredBoards` list is hosted on the `profile` field. If this
  1407. // field hasn't been modificated we don't need to run this hook.
  1408. if (!_.contains(fieldNames, 'profile')) return;
  1409. // To calculate a diff of board starred ids, we get both the previous
  1410. // and the newly board ids list
  1411. function getStarredBoardsIds(doc) {
  1412. return doc.profile && doc.profile.starredBoards;
  1413. }
  1414. const oldIds = getStarredBoardsIds(this.previous);
  1415. const newIds = getStarredBoardsIds(user);
  1416. // The _.difference(a, b) method returns the values from a that are not in
  1417. // b. We use it to find deleted and newly inserted ids by using it in one
  1418. // direction and then in the other.
  1419. function incrementBoards(boardsIds, inc) {
  1420. boardsIds.forEach((boardId) => {
  1421. Boards.update(boardId, {
  1422. $inc: {
  1423. stars: inc,
  1424. },
  1425. });
  1426. });
  1427. }
  1428. incrementBoards(_.difference(oldIds, newIds), -1);
  1429. incrementBoards(_.difference(newIds, oldIds), +1);
  1430. });
  1431. // Override getUserId so that we can TODO get the current userId
  1432. const fakeUserId = new Meteor.EnvironmentVariable();
  1433. const getUserId = CollectionHooks.getUserId;
  1434. CollectionHooks.getUserId = () => {
  1435. return fakeUserId.get() || getUserId();
  1436. };
  1437. if (!isSandstorm) {
  1438. Users.after.insert((userId, doc) => {
  1439. const fakeUser = {
  1440. extendAutoValueContext: {
  1441. userId: doc._id,
  1442. },
  1443. };
  1444. fakeUserId.withValue(doc._id, () => {
  1445. /*
  1446. // Insert the Welcome Board
  1447. Boards.insert({
  1448. title: TAPi18n.__('welcome-board'),
  1449. permission: 'private',
  1450. }, fakeUser, (err, boardId) => {
  1451. Swimlanes.insert({
  1452. title: TAPi18n.__('welcome-swimlane'),
  1453. boardId,
  1454. sort: 1,
  1455. }, fakeUser);
  1456. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1457. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1458. });
  1459. });
  1460. */
  1461. // Insert Template Container
  1462. const Future = require('fibers/future');
  1463. const future1 = new Future();
  1464. const future2 = new Future();
  1465. const future3 = new Future();
  1466. Boards.insert(
  1467. {
  1468. title: TAPi18n.__('templates'),
  1469. permission: 'private',
  1470. type: 'template-container',
  1471. },
  1472. fakeUser,
  1473. (err, boardId) => {
  1474. // Insert the reference to our templates board
  1475. Users.update(fakeUserId.get(), {
  1476. $set: {
  1477. 'profile.templatesBoardId': boardId,
  1478. },
  1479. });
  1480. // Insert the card templates swimlane
  1481. Swimlanes.insert(
  1482. {
  1483. title: TAPi18n.__('card-templates-swimlane'),
  1484. boardId,
  1485. sort: 1,
  1486. type: 'template-container',
  1487. },
  1488. fakeUser,
  1489. (err, swimlaneId) => {
  1490. // Insert the reference to out card templates swimlane
  1491. Users.update(fakeUserId.get(), {
  1492. $set: {
  1493. 'profile.cardTemplatesSwimlaneId': swimlaneId,
  1494. },
  1495. });
  1496. future1.return();
  1497. },
  1498. );
  1499. // Insert the list templates swimlane
  1500. Swimlanes.insert(
  1501. {
  1502. title: TAPi18n.__('list-templates-swimlane'),
  1503. boardId,
  1504. sort: 2,
  1505. type: 'template-container',
  1506. },
  1507. fakeUser,
  1508. (err, swimlaneId) => {
  1509. // Insert the reference to out list templates swimlane
  1510. Users.update(fakeUserId.get(), {
  1511. $set: {
  1512. 'profile.listTemplatesSwimlaneId': swimlaneId,
  1513. },
  1514. });
  1515. future2.return();
  1516. },
  1517. );
  1518. // Insert the board templates swimlane
  1519. Swimlanes.insert(
  1520. {
  1521. title: TAPi18n.__('board-templates-swimlane'),
  1522. boardId,
  1523. sort: 3,
  1524. type: 'template-container',
  1525. },
  1526. fakeUser,
  1527. (err, swimlaneId) => {
  1528. // Insert the reference to out board templates swimlane
  1529. Users.update(fakeUserId.get(), {
  1530. $set: {
  1531. 'profile.boardTemplatesSwimlaneId': swimlaneId,
  1532. },
  1533. });
  1534. future3.return();
  1535. },
  1536. );
  1537. },
  1538. );
  1539. // HACK
  1540. future1.wait();
  1541. future2.wait();
  1542. future3.wait();
  1543. // End of Insert Template Container
  1544. });
  1545. });
  1546. }
  1547. Users.after.insert((userId, doc) => {
  1548. // HACK
  1549. doc = Users.findOne({
  1550. _id: doc._id,
  1551. });
  1552. if (doc.createdThroughApi) {
  1553. // The admin user should be able to create a user despite disabling registration because
  1554. // it is two different things (registration and creation).
  1555. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1556. // the disableRegistration check.
  1557. // Issue : https://github.com/wekan/wekan/issues/1232
  1558. // PR : https://github.com/wekan/wekan/pull/1251
  1559. Users.update(doc._id, {
  1560. $set: {
  1561. createdThroughApi: '',
  1562. },
  1563. });
  1564. return;
  1565. }
  1566. //invite user to corresponding boards
  1567. const disableRegistration = Settings.findOne().disableRegistration;
  1568. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1569. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1570. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1571. let invitationCode = null;
  1572. if(doc.authenticationMethod.toLowerCase() == 'oauth2')
  1573. { // OIDC authentication mode
  1574. invitationCode = InvitationCodes.findOne({
  1575. email: doc.emails[0].address.toLowerCase(),
  1576. valid: true,
  1577. });
  1578. }
  1579. else{
  1580. invitationCode = InvitationCodes.findOne({
  1581. code: doc.profile.icode,
  1582. valid: true,
  1583. });
  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;