users.js 52 KB

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