users.js 61 KB

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