users.js 60 KB

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