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. check(fullname, String);
  895. check(username, String);
  896. check(initials, String);
  897. check(password, String);
  898. check(isAdmin, String);
  899. check(isActive, String);
  900. check(email, String);
  901. check(importUsernames, Array);
  902. check(userOrgsArray, Array);
  903. check(userTeamsArray, Array);
  904. if (Meteor.user() && Meteor.user().isAdmin) {
  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. check(username, String);
  945. check(userId, String);
  946. if (Meteor.user() && Meteor.user().isAdmin) {
  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. check(email, String);
  963. check(username, String);
  964. if (Meteor.user() && Meteor.user().isAdmin) {
  965. if (Array.isArray(email)) {
  966. email = email.shift();
  967. }
  968. const existingUser = Users.findOne(
  969. {
  970. 'emails.address': email,
  971. },
  972. {
  973. fields: {
  974. _id: 1,
  975. },
  976. },
  977. );
  978. if (existingUser) {
  979. throw new Meteor.Error('email-already-taken');
  980. } else {
  981. Users.update(userId, {
  982. $set: {
  983. emails: [
  984. {
  985. address: email,
  986. verified: false,
  987. },
  988. ],
  989. },
  990. });
  991. }
  992. }
  993. },
  994. setUsernameAndEmail(username, email, userId) {
  995. check(username, String);
  996. check(email, String);
  997. check(userId, String);
  998. if (Meteor.user() && Meteor.user().isAdmin) {
  999. if (Array.isArray(email)) {
  1000. email = email.shift();
  1001. }
  1002. Meteor.call('setUsername', username, userId);
  1003. Meteor.call('setEmail', email, userId);
  1004. }
  1005. },
  1006. setPassword(newPassword, userId) {
  1007. check(userId, String);
  1008. check(newPassword, String);
  1009. if (Meteor.user() && Meteor.user().isAdmin) {
  1010. if (Meteor.user().isAdmin) {
  1011. Accounts.setPassword(userId, newPassword);
  1012. }
  1013. }
  1014. },
  1015. setEmailVerified(email, verified, userId) {
  1016. check(email, String);
  1017. check(verified, Boolean);
  1018. check(userId, String);
  1019. if (Meteor.user() && Meteor.user().isAdmin) {
  1020. Users.update(userId, {
  1021. $set: {
  1022. emails: [
  1023. {
  1024. address: email,
  1025. verified,
  1026. },
  1027. ],
  1028. },
  1029. });
  1030. }
  1031. },
  1032. setInitials(initials, userId) {
  1033. check(initials, String);
  1034. check(userId, String);
  1035. if (Meteor.user() && Meteor.user().isAdmin) {
  1036. Users.update(userId, {
  1037. $set: {
  1038. 'profile.initials': initials,
  1039. },
  1040. });
  1041. }
  1042. },
  1043. // we accept userId, username, email
  1044. inviteUserToBoard(username, boardId) {
  1045. check(username, String);
  1046. check(boardId, String);
  1047. const inviter = Meteor.user();
  1048. const board = Boards.findOne(boardId);
  1049. const allowInvite =
  1050. inviter &&
  1051. board &&
  1052. board.members &&
  1053. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  1054. _.where(board.members, {
  1055. userId: inviter._id,
  1056. })[0].isActive;
  1057. // GitHub issue 2060
  1058. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  1059. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  1060. this.unblock();
  1061. const posAt = username.indexOf('@');
  1062. let user = null;
  1063. if (posAt >= 0) {
  1064. user = Users.findOne({
  1065. emails: {
  1066. $elemMatch: {
  1067. address: username,
  1068. },
  1069. },
  1070. });
  1071. } else {
  1072. user =
  1073. Users.findOne(username) ||
  1074. Users.findOne({
  1075. username,
  1076. });
  1077. }
  1078. if (user) {
  1079. if (user._id === inviter._id)
  1080. throw new Meteor.Error('error-user-notAllowSelf');
  1081. } else {
  1082. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  1083. if (
  1084. Settings.findOne({
  1085. disableRegistration: true,
  1086. })
  1087. ) {
  1088. throw new Meteor.Error('error-user-notCreated');
  1089. }
  1090. // Set in lowercase email before creating account
  1091. const email = username.toLowerCase();
  1092. username = email.substring(0, posAt);
  1093. const newUserId = Accounts.createUser({
  1094. username,
  1095. email,
  1096. });
  1097. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  1098. // assume new user speak same language with inviter
  1099. if (inviter.profile && inviter.profile.language) {
  1100. Users.update(newUserId, {
  1101. $set: {
  1102. 'profile.language': inviter.profile.language,
  1103. },
  1104. });
  1105. }
  1106. Accounts.sendEnrollmentEmail(newUserId);
  1107. user = Users.findOne(newUserId);
  1108. }
  1109. board.addMember(user._id);
  1110. user.addInvite(boardId);
  1111. //Check if there is a subtasks board
  1112. if (board.subtasksDefaultBoardId) {
  1113. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  1114. //If there is, also add user to that board
  1115. if (subBoard) {
  1116. subBoard.addMember(user._id);
  1117. user.addInvite(subBoard._id);
  1118. }
  1119. }
  1120. try {
  1121. const params = {
  1122. user: user.username,
  1123. inviter: inviter.username,
  1124. board: board.title,
  1125. url: board.absoluteUrl(),
  1126. };
  1127. const lang = user.getLanguage();
  1128. Email.send({
  1129. to: user.emails[0].address.toLowerCase(),
  1130. from: Accounts.emailTemplates.from,
  1131. subject: TAPi18n.__('email-invite-subject', params, lang),
  1132. text: TAPi18n.__('email-invite-text', params, lang),
  1133. });
  1134. } catch (e) {
  1135. throw new Meteor.Error('email-fail', e.message);
  1136. }
  1137. return {
  1138. username: user.username,
  1139. email: user.emails[0].address,
  1140. };
  1141. },
  1142. impersonate(userId) {
  1143. check(userId, String);
  1144. if (!Meteor.users.findOne(userId))
  1145. throw new Meteor.Error(404, 'User not found');
  1146. if (!Meteor.user().isAdmin)
  1147. throw new Meteor.Error(403, 'Permission denied');
  1148. ImpersonatedUsers.insert({ adminId: Meteor.user()._id, userId: userId, reason: 'clickedImpersonate' });
  1149. this.setUserId(userId);
  1150. },
  1151. isImpersonated(userId) {
  1152. check(userId, String);
  1153. const isImpersonated = ImpersonatedUsers.findOne({
  1154. userId: userId,
  1155. });
  1156. return isImpersonated;
  1157. },
  1158. });
  1159. Accounts.onCreateUser((options, user) => {
  1160. const userCount = Users.find().count();
  1161. if (userCount === 0) {
  1162. user.isAdmin = true;
  1163. return user;
  1164. }
  1165. if (user.services.oidc) {
  1166. let email = user.services.oidc.email;
  1167. if (Array.isArray(email)) {
  1168. email = email.shift();
  1169. }
  1170. email = email.toLowerCase();
  1171. user.username = user.services.oidc.username;
  1172. user.emails = [
  1173. {
  1174. address: email,
  1175. verified: true,
  1176. },
  1177. ];
  1178. const initials = user.services.oidc.fullname
  1179. .split(/\s+/)
  1180. .reduce((memo, word) => {
  1181. return memo + word[0];
  1182. }, '')
  1183. .toUpperCase();
  1184. user.profile = {
  1185. initials,
  1186. fullname: user.services.oidc.fullname,
  1187. boardView: 'board-view-swimlanes',
  1188. };
  1189. user.authenticationMethod = 'oauth2';
  1190. // see if any existing user has this email address or username, otherwise create new
  1191. const existingUser = Meteor.users.findOne({
  1192. $or: [
  1193. {
  1194. 'emails.address': email,
  1195. },
  1196. {
  1197. username: user.username,
  1198. },
  1199. ],
  1200. });
  1201. if (!existingUser) return user;
  1202. // copy across new service info
  1203. const service = _.keys(user.services)[0];
  1204. existingUser.services[service] = user.services[service];
  1205. existingUser.emails = user.emails;
  1206. existingUser.username = user.username;
  1207. existingUser.profile = user.profile;
  1208. existingUser.authenticationMethod = user.authenticationMethod;
  1209. Meteor.users.remove({
  1210. _id: user._id,
  1211. });
  1212. Meteor.users.remove({
  1213. _id: existingUser._id,
  1214. }); // is going to be created again
  1215. return existingUser;
  1216. }
  1217. if (options.from === 'admin') {
  1218. user.createdThroughApi = true;
  1219. return user;
  1220. }
  1221. const disableRegistration = Settings.findOne().disableRegistration;
  1222. // If this is the first Authentication by the ldap and self registration disabled
  1223. if (disableRegistration && options && options.ldap) {
  1224. user.authenticationMethod = 'ldap';
  1225. return user;
  1226. }
  1227. // If self registration enabled
  1228. if (!disableRegistration) {
  1229. return user;
  1230. }
  1231. if (!options || !options.profile) {
  1232. throw new Meteor.Error(
  1233. 'error-invitation-code-blank',
  1234. 'The invitation code is required',
  1235. );
  1236. }
  1237. const invitationCode = InvitationCodes.findOne({
  1238. code: options.profile.invitationcode,
  1239. email: options.email,
  1240. valid: true,
  1241. });
  1242. if (!invitationCode) {
  1243. throw new Meteor.Error(
  1244. 'error-invitation-code-not-exist',
  1245. // eslint-disable-next-line quotes
  1246. "The invitation code doesn't exist",
  1247. );
  1248. } else {
  1249. user.profile = {
  1250. icode: options.profile.invitationcode,
  1251. };
  1252. user.profile.boardView = 'board-view-swimlanes';
  1253. // Deletes the invitation code after the user was created successfully.
  1254. setTimeout(
  1255. Meteor.bindEnvironment(() => {
  1256. InvitationCodes.remove({
  1257. _id: invitationCode._id,
  1258. });
  1259. }),
  1260. 200,
  1261. );
  1262. return user;
  1263. }
  1264. });
  1265. }
  1266. const addCronJob = _.debounce(
  1267. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  1268. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  1269. const envRemoveAge =
  1270. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  1271. // default notifications will be removed 2 days after they are read
  1272. const defaultRemoveAge = 2;
  1273. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  1274. SyncedCron.add({
  1275. name: 'notification_cleanup',
  1276. schedule: (parser) => parser.text('every 1 days'),
  1277. job: () => {
  1278. for (const user of Users.find()) {
  1279. if (!user.profile || !user.profile.notifications) continue;
  1280. for (const notification of user.profile.notifications) {
  1281. if (notification.read) {
  1282. const removeDate = new Date(notification.read);
  1283. removeDate.setDate(removeDate.getDate() + removeAge);
  1284. if (removeDate <= new Date()) {
  1285. user.removeNotification(notification.activity);
  1286. }
  1287. }
  1288. }
  1289. }
  1290. },
  1291. });
  1292. SyncedCron.start();
  1293. }),
  1294. 500,
  1295. );
  1296. if (Meteor.isServer) {
  1297. // Let mongoDB ensure username unicity
  1298. Meteor.startup(() => {
  1299. allowedSortValues.forEach((value) => {
  1300. Lists._collection._ensureIndex(value);
  1301. });
  1302. Users._collection._ensureIndex({
  1303. modifiedAt: -1,
  1304. });
  1305. Users._collection._ensureIndex(
  1306. {
  1307. username: 1,
  1308. },
  1309. {
  1310. unique: true,
  1311. },
  1312. );
  1313. Meteor.defer(() => {
  1314. addCronJob();
  1315. });
  1316. });
  1317. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  1318. // if admin is removed, board is removed.
  1319. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  1320. // to use that board, and not have board deleted.
  1321. // Someone can be later changed to be admin of board, by making change to database.
  1322. // TODO: Add UI for changing someone as board admin.
  1323. //Users.before.remove((userId, doc) => {
  1324. // Boards
  1325. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  1326. // .forEach((board) => {
  1327. // // If only one admin for the board
  1328. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  1329. // Boards.remove(board._id);
  1330. // }
  1331. // });
  1332. //});
  1333. // Each board document contains the de-normalized number of users that have
  1334. // starred it. If the user star or unstar a board, we need to update this
  1335. // counter.
  1336. // We need to run this code on the server only, otherwise the incrementation
  1337. // will be done twice.
  1338. Users.after.update(function (userId, user, fieldNames) {
  1339. // The `starredBoards` list is hosted on the `profile` field. If this
  1340. // field hasn't been modificated we don't need to run this hook.
  1341. if (!_.contains(fieldNames, 'profile')) return;
  1342. // To calculate a diff of board starred ids, we get both the previous
  1343. // and the newly board ids list
  1344. function getStarredBoardsIds(doc) {
  1345. return doc.profile && doc.profile.starredBoards;
  1346. }
  1347. const oldIds = getStarredBoardsIds(this.previous);
  1348. const newIds = getStarredBoardsIds(user);
  1349. // The _.difference(a, b) method returns the values from a that are not in
  1350. // b. We use it to find deleted and newly inserted ids by using it in one
  1351. // direction and then in the other.
  1352. function incrementBoards(boardsIds, inc) {
  1353. boardsIds.forEach((boardId) => {
  1354. Boards.update(boardId, {
  1355. $inc: {
  1356. stars: inc,
  1357. },
  1358. });
  1359. });
  1360. }
  1361. incrementBoards(_.difference(oldIds, newIds), -1);
  1362. incrementBoards(_.difference(newIds, oldIds), +1);
  1363. });
  1364. // Override getUserId so that we can TODO get the current userId
  1365. const fakeUserId = new Meteor.EnvironmentVariable();
  1366. const getUserId = CollectionHooks.getUserId;
  1367. CollectionHooks.getUserId = () => {
  1368. return fakeUserId.get() || getUserId();
  1369. };
  1370. if (!isSandstorm) {
  1371. Users.after.insert((userId, doc) => {
  1372. const fakeUser = {
  1373. extendAutoValueContext: {
  1374. userId: doc._id,
  1375. },
  1376. };
  1377. fakeUserId.withValue(doc._id, () => {
  1378. /*
  1379. // Insert the Welcome Board
  1380. Boards.insert({
  1381. title: TAPi18n.__('welcome-board'),
  1382. permission: 'private',
  1383. }, fakeUser, (err, boardId) => {
  1384. Swimlanes.insert({
  1385. title: TAPi18n.__('welcome-swimlane'),
  1386. boardId,
  1387. sort: 1,
  1388. }, fakeUser);
  1389. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1390. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1391. });
  1392. });
  1393. */
  1394. const Future = require('fibers/future');
  1395. const future1 = new Future();
  1396. const future2 = new Future();
  1397. const future3 = new Future();
  1398. Boards.insert(
  1399. {
  1400. title: TAPi18n.__('templates'),
  1401. permission: 'private',
  1402. type: 'template-container',
  1403. },
  1404. fakeUser,
  1405. (err, boardId) => {
  1406. // Insert the reference to our templates board
  1407. Users.update(fakeUserId.get(), {
  1408. $set: {
  1409. 'profile.templatesBoardId': boardId,
  1410. },
  1411. });
  1412. // Insert the card templates swimlane
  1413. Swimlanes.insert(
  1414. {
  1415. title: TAPi18n.__('card-templates-swimlane'),
  1416. boardId,
  1417. sort: 1,
  1418. type: 'template-container',
  1419. },
  1420. fakeUser,
  1421. (err, swimlaneId) => {
  1422. // Insert the reference to out card templates swimlane
  1423. Users.update(fakeUserId.get(), {
  1424. $set: {
  1425. 'profile.cardTemplatesSwimlaneId': swimlaneId,
  1426. },
  1427. });
  1428. future1.return();
  1429. },
  1430. );
  1431. // Insert the list templates swimlane
  1432. Swimlanes.insert(
  1433. {
  1434. title: TAPi18n.__('list-templates-swimlane'),
  1435. boardId,
  1436. sort: 2,
  1437. type: 'template-container',
  1438. },
  1439. fakeUser,
  1440. (err, swimlaneId) => {
  1441. // Insert the reference to out list templates swimlane
  1442. Users.update(fakeUserId.get(), {
  1443. $set: {
  1444. 'profile.listTemplatesSwimlaneId': swimlaneId,
  1445. },
  1446. });
  1447. future2.return();
  1448. },
  1449. );
  1450. // Insert the board templates swimlane
  1451. Swimlanes.insert(
  1452. {
  1453. title: TAPi18n.__('board-templates-swimlane'),
  1454. boardId,
  1455. sort: 3,
  1456. type: 'template-container',
  1457. },
  1458. fakeUser,
  1459. (err, swimlaneId) => {
  1460. // Insert the reference to out board templates swimlane
  1461. Users.update(fakeUserId.get(), {
  1462. $set: {
  1463. 'profile.boardTemplatesSwimlaneId': swimlaneId,
  1464. },
  1465. });
  1466. future3.return();
  1467. },
  1468. );
  1469. },
  1470. );
  1471. // HACK
  1472. future1.wait();
  1473. future2.wait();
  1474. future3.wait();
  1475. });
  1476. });
  1477. }
  1478. Users.after.insert((userId, doc) => {
  1479. // HACK
  1480. doc = Users.findOne({
  1481. _id: doc._id,
  1482. });
  1483. if (doc.createdThroughApi) {
  1484. // The admin user should be able to create a user despite disabling registration because
  1485. // it is two different things (registration and creation).
  1486. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1487. // the disableRegistration check.
  1488. // Issue : https://github.com/wekan/wekan/issues/1232
  1489. // PR : https://github.com/wekan/wekan/pull/1251
  1490. Users.update(doc._id, {
  1491. $set: {
  1492. createdThroughApi: '',
  1493. },
  1494. });
  1495. return;
  1496. }
  1497. //invite user to corresponding boards
  1498. const disableRegistration = Settings.findOne().disableRegistration;
  1499. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1500. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1501. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1502. const invitationCode = InvitationCodes.findOne({
  1503. code: doc.profile.icode,
  1504. valid: true,
  1505. });
  1506. if (!invitationCode) {
  1507. throw new Meteor.Error('error-invitation-code-not-exist');
  1508. } else {
  1509. invitationCode.boardsToBeInvited.forEach((boardId) => {
  1510. const board = Boards.findOne(boardId);
  1511. board.addMember(doc._id);
  1512. });
  1513. if (!doc.profile) {
  1514. doc.profile = {};
  1515. }
  1516. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1517. Users.update(doc._id, {
  1518. $set: {
  1519. profile: doc.profile,
  1520. },
  1521. });
  1522. InvitationCodes.update(invitationCode._id, {
  1523. $set: {
  1524. valid: false,
  1525. },
  1526. });
  1527. }
  1528. }
  1529. });
  1530. }
  1531. // USERS REST API
  1532. if (Meteor.isServer) {
  1533. // Middleware which checks that API is enabled.
  1534. JsonRoutes.Middleware.use(function (req, res, next) {
  1535. const api = req.url.startsWith('/api');
  1536. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1537. return next();
  1538. } else {
  1539. res.writeHead(301, {
  1540. Location: '/',
  1541. });
  1542. return res.end();
  1543. }
  1544. });
  1545. /**
  1546. * @operation get_current_user
  1547. *
  1548. * @summary returns the current user
  1549. * @return_type Users
  1550. */
  1551. JsonRoutes.add('GET', '/api/user', function (req, res) {
  1552. try {
  1553. Authentication.checkLoggedIn(req.userId);
  1554. const data = Meteor.users.findOne({
  1555. _id: req.userId,
  1556. });
  1557. delete data.services;
  1558. // get all boards where the user is member of
  1559. let boards = Boards.find(
  1560. {
  1561. type: 'board',
  1562. 'members.userId': req.userId,
  1563. },
  1564. {
  1565. fields: {
  1566. _id: 1,
  1567. members: 1,
  1568. },
  1569. },
  1570. );
  1571. boards = boards.map((b) => {
  1572. const u = b.members.find((m) => m.userId === req.userId);
  1573. delete u.userId;
  1574. u.boardId = b._id;
  1575. return u;
  1576. });
  1577. data.boards = boards;
  1578. JsonRoutes.sendResult(res, {
  1579. code: 200,
  1580. data,
  1581. });
  1582. } catch (error) {
  1583. JsonRoutes.sendResult(res, {
  1584. code: 200,
  1585. data: error,
  1586. });
  1587. }
  1588. });
  1589. /**
  1590. * @operation get_all_users
  1591. *
  1592. * @summary return all the users
  1593. *
  1594. * @description Only the admin user (the first user) can call the REST API.
  1595. * @return_type [{ _id: string,
  1596. * username: string}]
  1597. */
  1598. JsonRoutes.add('GET', '/api/users', function (req, res) {
  1599. try {
  1600. Authentication.checkUserId(req.userId);
  1601. JsonRoutes.sendResult(res, {
  1602. code: 200,
  1603. data: Meteor.users.find({}).map(function (doc) {
  1604. return {
  1605. _id: doc._id,
  1606. username: doc.username,
  1607. };
  1608. }),
  1609. });
  1610. } catch (error) {
  1611. JsonRoutes.sendResult(res, {
  1612. code: 200,
  1613. data: error,
  1614. });
  1615. }
  1616. });
  1617. /**
  1618. * @operation get_user
  1619. *
  1620. * @summary get a given user
  1621. *
  1622. * @description Only the admin user (the first user) can call the REST API.
  1623. *
  1624. * @param {string} userId the user ID or username
  1625. * @return_type Users
  1626. */
  1627. JsonRoutes.add('GET', '/api/users/:userId', function (req, res) {
  1628. try {
  1629. Authentication.checkUserId(req.userId);
  1630. let id = req.params.userId;
  1631. let user = Meteor.users.findOne({
  1632. _id: id,
  1633. });
  1634. if (!user) {
  1635. user = Meteor.users.findOne({
  1636. username: id,
  1637. });
  1638. id = user._id;
  1639. }
  1640. // get all boards where the user is member of
  1641. let boards = Boards.find(
  1642. {
  1643. type: 'board',
  1644. 'members.userId': id,
  1645. },
  1646. {
  1647. fields: {
  1648. _id: 1,
  1649. members: 1,
  1650. },
  1651. },
  1652. );
  1653. boards = boards.map((b) => {
  1654. const u = b.members.find((m) => m.userId === id);
  1655. delete u.userId;
  1656. u.boardId = b._id;
  1657. return u;
  1658. });
  1659. user.boards = boards;
  1660. JsonRoutes.sendResult(res, {
  1661. code: 200,
  1662. data: user,
  1663. });
  1664. } catch (error) {
  1665. JsonRoutes.sendResult(res, {
  1666. code: 200,
  1667. data: error,
  1668. });
  1669. }
  1670. });
  1671. /**
  1672. * @operation edit_user
  1673. *
  1674. * @summary edit a given user
  1675. *
  1676. * @description Only the admin user (the first user) can call the REST API.
  1677. *
  1678. * Possible values for *action*:
  1679. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1680. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1681. * - `enableLogin`: Enable a user
  1682. *
  1683. * @param {string} userId the user ID
  1684. * @param {string} action the action
  1685. * @return_type {_id: string,
  1686. * title: string}
  1687. */
  1688. JsonRoutes.add('PUT', '/api/users/:userId', function (req, res) {
  1689. try {
  1690. Authentication.checkUserId(req.userId);
  1691. const id = req.params.userId;
  1692. const action = req.body.action;
  1693. let data = Meteor.users.findOne({
  1694. _id: id,
  1695. });
  1696. if (data !== undefined) {
  1697. if (action === 'takeOwnership') {
  1698. data = Boards.find(
  1699. {
  1700. 'members.userId': id,
  1701. 'members.isAdmin': true,
  1702. },
  1703. {
  1704. sort: {
  1705. sort: 1 /* boards default sorting */,
  1706. },
  1707. },
  1708. ).map(function (board) {
  1709. if (board.hasMember(req.userId)) {
  1710. board.removeMember(req.userId);
  1711. }
  1712. board.changeOwnership(id, req.userId);
  1713. return {
  1714. _id: board._id,
  1715. title: board.title,
  1716. };
  1717. });
  1718. } else {
  1719. if (action === 'disableLogin' && id !== req.userId) {
  1720. Users.update(
  1721. {
  1722. _id: id,
  1723. },
  1724. {
  1725. $set: {
  1726. loginDisabled: true,
  1727. 'services.resume.loginTokens': '',
  1728. },
  1729. },
  1730. );
  1731. } else if (action === 'enableLogin') {
  1732. Users.update(
  1733. {
  1734. _id: id,
  1735. },
  1736. {
  1737. $set: {
  1738. loginDisabled: '',
  1739. },
  1740. },
  1741. );
  1742. }
  1743. data = Meteor.users.findOne({
  1744. _id: id,
  1745. });
  1746. }
  1747. }
  1748. JsonRoutes.sendResult(res, {
  1749. code: 200,
  1750. data,
  1751. });
  1752. } catch (error) {
  1753. JsonRoutes.sendResult(res, {
  1754. code: 200,
  1755. data: error,
  1756. });
  1757. }
  1758. });
  1759. /**
  1760. * @operation add_board_member
  1761. * @tag Boards
  1762. *
  1763. * @summary Add New Board Member with Role
  1764. *
  1765. * @description Only the admin user (the first user) can call the REST API.
  1766. *
  1767. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1768. * to later change the permissions.
  1769. *
  1770. * @param {string} boardId the board ID
  1771. * @param {string} userId the user ID
  1772. * @param {boolean} isAdmin is the user an admin of the board
  1773. * @param {boolean} isNoComments disable comments
  1774. * @param {boolean} isCommentOnly only enable comments
  1775. * @return_type {_id: string,
  1776. * title: string}
  1777. */
  1778. JsonRoutes.add(
  1779. 'POST',
  1780. '/api/boards/:boardId/members/:userId/add',
  1781. function (req, res) {
  1782. try {
  1783. Authentication.checkUserId(req.userId);
  1784. const userId = req.params.userId;
  1785. const boardId = req.params.boardId;
  1786. const action = req.body.action;
  1787. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1788. let data = Meteor.users.findOne({
  1789. _id: userId,
  1790. });
  1791. if (data !== undefined) {
  1792. if (action === 'add') {
  1793. data = Boards.find({
  1794. _id: boardId,
  1795. }).map(function (board) {
  1796. if (!board.hasMember(userId)) {
  1797. board.addMember(userId);
  1798. function isTrue(data) {
  1799. return data.toLowerCase() === 'true';
  1800. }
  1801. board.setMemberPermission(
  1802. userId,
  1803. isTrue(isAdmin),
  1804. isTrue(isNoComments),
  1805. isTrue(isCommentOnly),
  1806. userId,
  1807. );
  1808. }
  1809. return {
  1810. _id: board._id,
  1811. title: board.title,
  1812. };
  1813. });
  1814. }
  1815. }
  1816. JsonRoutes.sendResult(res, {
  1817. code: 200,
  1818. data: query,
  1819. });
  1820. } catch (error) {
  1821. JsonRoutes.sendResult(res, {
  1822. code: 200,
  1823. data: error,
  1824. });
  1825. }
  1826. },
  1827. );
  1828. /**
  1829. * @operation remove_board_member
  1830. * @tag Boards
  1831. *
  1832. * @summary Remove Member from Board
  1833. *
  1834. * @description Only the admin user (the first user) can call the REST API.
  1835. *
  1836. * @param {string} boardId the board ID
  1837. * @param {string} userId the user ID
  1838. * @param {string} action the action (needs to be `remove`)
  1839. * @return_type {_id: string,
  1840. * title: string}
  1841. */
  1842. JsonRoutes.add(
  1843. 'POST',
  1844. '/api/boards/:boardId/members/:userId/remove',
  1845. function (req, res) {
  1846. try {
  1847. Authentication.checkUserId(req.userId);
  1848. const userId = req.params.userId;
  1849. const boardId = req.params.boardId;
  1850. const action = req.body.action;
  1851. let data = Meteor.users.findOne({
  1852. _id: userId,
  1853. });
  1854. if (data !== undefined) {
  1855. if (action === 'remove') {
  1856. data = Boards.find({
  1857. _id: boardId,
  1858. }).map(function (board) {
  1859. if (board.hasMember(userId)) {
  1860. board.removeMember(userId);
  1861. }
  1862. return {
  1863. _id: board._id,
  1864. title: board.title,
  1865. };
  1866. });
  1867. }
  1868. }
  1869. JsonRoutes.sendResult(res, {
  1870. code: 200,
  1871. data: query,
  1872. });
  1873. } catch (error) {
  1874. JsonRoutes.sendResult(res, {
  1875. code: 200,
  1876. data: error,
  1877. });
  1878. }
  1879. },
  1880. );
  1881. /**
  1882. * @operation new_user
  1883. *
  1884. * @summary Create a new user
  1885. *
  1886. * @description Only the admin user (the first user) can call the REST API.
  1887. *
  1888. * @param {string} username the new username
  1889. * @param {string} email the email of the new user
  1890. * @param {string} password the password of the new user
  1891. * @return_type {_id: string}
  1892. */
  1893. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  1894. try {
  1895. Authentication.checkUserId(req.userId);
  1896. const id = Accounts.createUser({
  1897. username: req.body.username,
  1898. email: req.body.email,
  1899. password: req.body.password,
  1900. from: 'admin',
  1901. });
  1902. JsonRoutes.sendResult(res, {
  1903. code: 200,
  1904. data: {
  1905. _id: id,
  1906. },
  1907. });
  1908. } catch (error) {
  1909. JsonRoutes.sendResult(res, {
  1910. code: 200,
  1911. data: error,
  1912. });
  1913. }
  1914. });
  1915. /**
  1916. * @operation delete_user
  1917. *
  1918. * @summary Delete a user
  1919. *
  1920. * @description Only the admin user (the first user) can call the REST API.
  1921. *
  1922. * @param {string} userId the ID of the user to delete
  1923. * @return_type {_id: string}
  1924. */
  1925. JsonRoutes.add('DELETE', '/api/users/:userId', function (req, res) {
  1926. try {
  1927. Authentication.checkUserId(req.userId);
  1928. const id = req.params.userId;
  1929. // Delete is not enabled yet, because it does leave empty user avatars
  1930. // to boards: boards members, card members and assignees have
  1931. // empty users. See:
  1932. // - wekan/client/components/settings/peopleBody.jade deleteButton
  1933. // - wekan/client/components/settings/peopleBody.js deleteButton
  1934. // - wekan/client/components/sidebar/sidebar.js Popup.afterConfirm('removeMember'
  1935. // that does now remove member from board, card members and assignees correctly,
  1936. // but that should be used to remove user from all boards similarly
  1937. // - wekan/models/users.js Delete is not enabled
  1938. // Meteor.users.remove({ _id: id });
  1939. JsonRoutes.sendResult(res, {
  1940. code: 200,
  1941. data: {
  1942. _id: id,
  1943. },
  1944. });
  1945. } catch (error) {
  1946. JsonRoutes.sendResult(res, {
  1947. code: 200,
  1948. data: error,
  1949. });
  1950. }
  1951. });
  1952. /**
  1953. * @operation create_user_token
  1954. *
  1955. * @summary Create a user token
  1956. *
  1957. * @description Only the admin user (the first user) can call the REST API.
  1958. *
  1959. * @param {string} userId the ID of the user to create token for.
  1960. * @return_type {_id: string}
  1961. */
  1962. JsonRoutes.add('POST', '/api/createtoken/:userId', function (req, res) {
  1963. try {
  1964. Authentication.checkUserId(req.userId);
  1965. const id = req.params.userId;
  1966. const token = Accounts._generateStampedLoginToken();
  1967. Accounts._insertLoginToken(id, token);
  1968. JsonRoutes.sendResult(res, {
  1969. code: 200,
  1970. data: {
  1971. _id: id,
  1972. authToken: token.token,
  1973. },
  1974. });
  1975. } catch (error) {
  1976. JsonRoutes.sendResult(res, {
  1977. code: 200,
  1978. data: error,
  1979. });
  1980. }
  1981. });
  1982. }
  1983. export default Users;