users.js 58 KB

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