users.js 54 KB

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