users.js 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397
  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.createIndex(value);
  1575. });
  1576. Users._collection.createIndex({
  1577. modifiedAt: -1,
  1578. });
  1579. /* Commented out extra index because of IndexOptionsConflict.
  1580. Users._collection.createIndex(
  1581. {
  1582. username: 1,
  1583. },
  1584. {
  1585. unique: true,
  1586. },
  1587. );
  1588. */
  1589. Meteor.defer(() => {
  1590. addCronJob();
  1591. });
  1592. });
  1593. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  1594. // if admin is removed, board is removed.
  1595. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  1596. // to use that board, and not have board deleted.
  1597. // Someone can be later changed to be admin of board, by making change to database.
  1598. // TODO: Add UI for changing someone as board admin.
  1599. //Users.before.remove((userId, doc) => {
  1600. // Boards
  1601. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  1602. // .forEach((board) => {
  1603. // // If only one admin for the board
  1604. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  1605. // Boards.remove(board._id);
  1606. // }
  1607. // });
  1608. //});
  1609. // Each board document contains the de-normalized number of users that have
  1610. // starred it. If the user star or unstar a board, we need to update this
  1611. // counter.
  1612. // We need to run this code on the server only, otherwise the incrementation
  1613. // will be done twice.
  1614. Users.after.update(function (userId, user, fieldNames) {
  1615. // The `starredBoards` list is hosted on the `profile` field. If this
  1616. // field hasn't been modificated we don't need to run this hook.
  1617. if (!_.contains(fieldNames, 'profile')) return;
  1618. // To calculate a diff of board starred ids, we get both the previous
  1619. // and the newly board ids list
  1620. function getStarredBoardsIds(doc) {
  1621. return doc.profile && doc.profile.starredBoards;
  1622. }
  1623. const oldIds = getStarredBoardsIds(this.previous);
  1624. const newIds = getStarredBoardsIds(user);
  1625. // The _.difference(a, b) method returns the values from a that are not in
  1626. // b. We use it to find deleted and newly inserted ids by using it in one
  1627. // direction and then in the other.
  1628. function incrementBoards(boardsIds, inc) {
  1629. boardsIds.forEach((boardId) => {
  1630. Boards.update(boardId, {
  1631. $inc: {
  1632. stars: inc,
  1633. },
  1634. });
  1635. });
  1636. }
  1637. incrementBoards(_.difference(oldIds, newIds), -1);
  1638. incrementBoards(_.difference(newIds, oldIds), +1);
  1639. });
  1640. // Override getUserId so that we can TODO get the current userId
  1641. const fakeUserId = new Meteor.EnvironmentVariable();
  1642. const getUserId = CollectionHooks.getUserId;
  1643. CollectionHooks.getUserId = () => {
  1644. return fakeUserId.get() || getUserId();
  1645. };
  1646. if (!isSandstorm) {
  1647. Users.after.insert((userId, doc) => {
  1648. const fakeUser = {
  1649. extendAutoValueContext: {
  1650. userId: doc._id,
  1651. },
  1652. };
  1653. fakeUserId.withValue(doc._id, () => {
  1654. /*
  1655. // Insert the Welcome Board
  1656. Boards.insert({
  1657. title: TAPi18n.__('welcome-board'),
  1658. permission: 'private',
  1659. }, fakeUser, (err, boardId) => {
  1660. Swimlanes.insert({
  1661. title: TAPi18n.__('welcome-swimlane'),
  1662. boardId,
  1663. sort: 1,
  1664. }, fakeUser);
  1665. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1666. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1667. });
  1668. });
  1669. */
  1670. // Insert Template Container
  1671. const Future = require('fibers/future');
  1672. const future1 = new Future();
  1673. const future2 = new Future();
  1674. const future3 = new Future();
  1675. Boards.insert(
  1676. {
  1677. title: TAPi18n.__('templates'),
  1678. permission: 'private',
  1679. type: 'template-container',
  1680. },
  1681. fakeUser,
  1682. (err, boardId) => {
  1683. // Insert the reference to our templates board
  1684. Users.update(fakeUserId.get(), {
  1685. $set: {
  1686. 'profile.templatesBoardId': boardId,
  1687. },
  1688. });
  1689. // Insert the card templates swimlane
  1690. Swimlanes.insert(
  1691. {
  1692. title: TAPi18n.__('card-templates-swimlane'),
  1693. boardId,
  1694. sort: 1,
  1695. type: 'template-container',
  1696. },
  1697. fakeUser,
  1698. (err, swimlaneId) => {
  1699. // Insert the reference to out card templates swimlane
  1700. Users.update(fakeUserId.get(), {
  1701. $set: {
  1702. 'profile.cardTemplatesSwimlaneId': swimlaneId,
  1703. },
  1704. });
  1705. future1.return();
  1706. },
  1707. );
  1708. // Insert the list templates swimlane
  1709. Swimlanes.insert(
  1710. {
  1711. title: TAPi18n.__('list-templates-swimlane'),
  1712. boardId,
  1713. sort: 2,
  1714. type: 'template-container',
  1715. },
  1716. fakeUser,
  1717. (err, swimlaneId) => {
  1718. // Insert the reference to out list templates swimlane
  1719. Users.update(fakeUserId.get(), {
  1720. $set: {
  1721. 'profile.listTemplatesSwimlaneId': swimlaneId,
  1722. },
  1723. });
  1724. future2.return();
  1725. },
  1726. );
  1727. // Insert the board templates swimlane
  1728. Swimlanes.insert(
  1729. {
  1730. title: TAPi18n.__('board-templates-swimlane'),
  1731. boardId,
  1732. sort: 3,
  1733. type: 'template-container',
  1734. },
  1735. fakeUser,
  1736. (err, swimlaneId) => {
  1737. // Insert the reference to out board templates swimlane
  1738. Users.update(fakeUserId.get(), {
  1739. $set: {
  1740. 'profile.boardTemplatesSwimlaneId': swimlaneId,
  1741. },
  1742. });
  1743. future3.return();
  1744. },
  1745. );
  1746. },
  1747. );
  1748. // HACK
  1749. future1.wait();
  1750. future2.wait();
  1751. future3.wait();
  1752. // End of Insert Template Container
  1753. });
  1754. });
  1755. }
  1756. Users.after.insert((userId, doc) => {
  1757. // HACK
  1758. doc = Users.findOne({
  1759. _id: doc._id,
  1760. });
  1761. if (doc.createdThroughApi) {
  1762. // The admin user should be able to create a user despite disabling registration because
  1763. // it is two different things (registration and creation).
  1764. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1765. // the disableRegistration check.
  1766. // Issue : https://github.com/wekan/wekan/issues/1232
  1767. // PR : https://github.com/wekan/wekan/pull/1251
  1768. Users.update(doc._id, {
  1769. $set: {
  1770. createdThroughApi: '',
  1771. },
  1772. });
  1773. return;
  1774. }
  1775. //invite user to corresponding boards
  1776. const disableRegistration = Settings.findOne().disableRegistration;
  1777. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1778. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1779. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1780. let invitationCode = null;
  1781. if(doc.authenticationMethod.toLowerCase() == 'oauth2')
  1782. { // OIDC authentication mode
  1783. invitationCode = InvitationCodes.findOne({
  1784. email: doc.emails[0].address.toLowerCase(),
  1785. valid: true,
  1786. });
  1787. }
  1788. else{
  1789. invitationCode = InvitationCodes.findOne({
  1790. code: doc.profile.icode,
  1791. valid: true,
  1792. });
  1793. }
  1794. if (!invitationCode) {
  1795. throw new Meteor.Error('error-invitation-code-not-exist');
  1796. } else {
  1797. invitationCode.boardsToBeInvited.forEach((boardId) => {
  1798. const board = Boards.findOne(boardId);
  1799. board.addMember(doc._id);
  1800. });
  1801. if (!doc.profile) {
  1802. doc.profile = {};
  1803. }
  1804. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1805. Users.update(doc._id, {
  1806. $set: {
  1807. profile: doc.profile,
  1808. },
  1809. });
  1810. InvitationCodes.update(invitationCode._id, {
  1811. $set: {
  1812. valid: false,
  1813. },
  1814. });
  1815. }
  1816. }
  1817. });
  1818. }
  1819. // USERS REST API
  1820. if (Meteor.isServer) {
  1821. // Middleware which checks that API is enabled.
  1822. JsonRoutes.Middleware.use(function (req, res, next) {
  1823. const api = req.url.startsWith('/api');
  1824. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1825. return next();
  1826. } else {
  1827. res.writeHead(301, {
  1828. Location: '/',
  1829. });
  1830. return res.end();
  1831. }
  1832. });
  1833. /**
  1834. * @operation get_current_user
  1835. *
  1836. * @summary returns the current user
  1837. * @return_type Users
  1838. */
  1839. JsonRoutes.add('GET', '/api/user', function (req, res) {
  1840. try {
  1841. Authentication.checkLoggedIn(req.userId);
  1842. const data = Meteor.users.findOne({
  1843. _id: req.userId,
  1844. });
  1845. delete data.services;
  1846. // get all boards where the user is member of
  1847. let boards = Boards.find(
  1848. {
  1849. type: 'board',
  1850. 'members.userId': req.userId,
  1851. },
  1852. {
  1853. fields: {
  1854. _id: 1,
  1855. members: 1,
  1856. },
  1857. },
  1858. );
  1859. boards = boards.map((b) => {
  1860. const u = b.members.find((m) => m.userId === req.userId);
  1861. delete u.userId;
  1862. u.boardId = b._id;
  1863. return u;
  1864. });
  1865. data.boards = boards;
  1866. JsonRoutes.sendResult(res, {
  1867. code: 200,
  1868. data,
  1869. });
  1870. } catch (error) {
  1871. JsonRoutes.sendResult(res, {
  1872. code: 200,
  1873. data: error,
  1874. });
  1875. }
  1876. });
  1877. /**
  1878. * @operation get_all_users
  1879. *
  1880. * @summary return all the users
  1881. *
  1882. * @description Only the admin user (the first user) can call the REST API.
  1883. * @return_type [{ _id: string,
  1884. * username: string}]
  1885. */
  1886. JsonRoutes.add('GET', '/api/users', function (req, res) {
  1887. try {
  1888. Authentication.checkUserId(req.userId);
  1889. JsonRoutes.sendResult(res, {
  1890. code: 200,
  1891. data: Meteor.users.find({}).map(function (doc) {
  1892. return {
  1893. _id: doc._id,
  1894. username: doc.username,
  1895. };
  1896. }),
  1897. });
  1898. } catch (error) {
  1899. JsonRoutes.sendResult(res, {
  1900. code: 200,
  1901. data: error,
  1902. });
  1903. }
  1904. });
  1905. /**
  1906. * @operation get_user
  1907. *
  1908. * @summary get a given user
  1909. *
  1910. * @description Only the admin user (the first user) can call the REST API.
  1911. *
  1912. * @param {string} userId the user ID or username
  1913. * @return_type Users
  1914. */
  1915. JsonRoutes.add('GET', '/api/users/:userId', function (req, res) {
  1916. try {
  1917. Authentication.checkUserId(req.userId);
  1918. let id = req.params.userId;
  1919. let user = Meteor.users.findOne({
  1920. _id: id,
  1921. });
  1922. if (!user) {
  1923. user = Meteor.users.findOne({
  1924. username: id,
  1925. });
  1926. id = user._id;
  1927. }
  1928. // get all boards where the user is member of
  1929. let boards = Boards.find(
  1930. {
  1931. type: 'board',
  1932. 'members.userId': id,
  1933. },
  1934. {
  1935. fields: {
  1936. _id: 1,
  1937. members: 1,
  1938. },
  1939. },
  1940. );
  1941. boards = boards.map((b) => {
  1942. const u = b.members.find((m) => m.userId === id);
  1943. delete u.userId;
  1944. u.boardId = b._id;
  1945. return u;
  1946. });
  1947. user.boards = boards;
  1948. JsonRoutes.sendResult(res, {
  1949. code: 200,
  1950. data: user,
  1951. });
  1952. } catch (error) {
  1953. JsonRoutes.sendResult(res, {
  1954. code: 200,
  1955. data: error,
  1956. });
  1957. }
  1958. });
  1959. /**
  1960. * @operation edit_user
  1961. *
  1962. * @summary edit a given user
  1963. *
  1964. * @description Only the admin user (the first user) can call the REST API.
  1965. *
  1966. * Possible values for *action*:
  1967. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1968. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1969. * - `enableLogin`: Enable a user
  1970. *
  1971. * @param {string} userId the user ID
  1972. * @param {string} action the action
  1973. * @return_type {_id: string,
  1974. * title: string}
  1975. */
  1976. JsonRoutes.add('PUT', '/api/users/:userId', function (req, res) {
  1977. try {
  1978. Authentication.checkUserId(req.userId);
  1979. const id = req.params.userId;
  1980. const action = req.body.action;
  1981. let data = Meteor.users.findOne({
  1982. _id: id,
  1983. });
  1984. if (data !== undefined) {
  1985. if (action === 'takeOwnership') {
  1986. data = Boards.find(
  1987. {
  1988. 'members.userId': id,
  1989. 'members.isAdmin': true,
  1990. },
  1991. {
  1992. sort: {
  1993. sort: 1 /* boards default sorting */,
  1994. },
  1995. },
  1996. ).map(function (board) {
  1997. if (board.hasMember(req.userId)) {
  1998. board.removeMember(req.userId);
  1999. }
  2000. board.changeOwnership(id, req.userId);
  2001. return {
  2002. _id: board._id,
  2003. title: board.title,
  2004. };
  2005. });
  2006. } else {
  2007. if (action === 'disableLogin' && id !== req.userId) {
  2008. Users.update(
  2009. {
  2010. _id: id,
  2011. },
  2012. {
  2013. $set: {
  2014. loginDisabled: true,
  2015. 'services.resume.loginTokens': '',
  2016. },
  2017. },
  2018. );
  2019. } else if (action === 'enableLogin') {
  2020. Users.update(
  2021. {
  2022. _id: id,
  2023. },
  2024. {
  2025. $set: {
  2026. loginDisabled: '',
  2027. },
  2028. },
  2029. );
  2030. }
  2031. data = Meteor.users.findOne({
  2032. _id: id,
  2033. });
  2034. }
  2035. }
  2036. JsonRoutes.sendResult(res, {
  2037. code: 200,
  2038. data,
  2039. });
  2040. } catch (error) {
  2041. JsonRoutes.sendResult(res, {
  2042. code: 200,
  2043. data: error,
  2044. });
  2045. }
  2046. });
  2047. /**
  2048. * @operation add_board_member
  2049. * @tag Boards
  2050. *
  2051. * @summary Add New Board Member with Role
  2052. *
  2053. * @description Only the admin user (the first user) can call the REST API.
  2054. *
  2055. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  2056. * to later change the permissions.
  2057. *
  2058. * @param {string} boardId the board ID
  2059. * @param {string} userId the user ID
  2060. * @param {boolean} isAdmin is the user an admin of the board
  2061. * @param {boolean} isNoComments disable comments
  2062. * @param {boolean} isCommentOnly only enable comments
  2063. * @return_type {_id: string,
  2064. * title: string}
  2065. */
  2066. JsonRoutes.add(
  2067. 'POST',
  2068. '/api/boards/:boardId/members/:userId/add',
  2069. function (req, res) {
  2070. try {
  2071. Authentication.checkUserId(req.userId);
  2072. const userId = req.params.userId;
  2073. const boardId = req.params.boardId;
  2074. const action = req.body.action;
  2075. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  2076. let data = Meteor.users.findOne({
  2077. _id: userId,
  2078. });
  2079. if (data !== undefined) {
  2080. if (action === 'add') {
  2081. data = Boards.find({
  2082. _id: boardId,
  2083. }).map(function (board) {
  2084. if (!board.hasMember(userId)) {
  2085. board.addMember(userId);
  2086. function isTrue(data) {
  2087. return data.toLowerCase() === 'true';
  2088. }
  2089. board.setMemberPermission(
  2090. userId,
  2091. isTrue(isAdmin),
  2092. isTrue(isNoComments),
  2093. isTrue(isCommentOnly),
  2094. userId,
  2095. );
  2096. }
  2097. return {
  2098. _id: board._id,
  2099. title: board.title,
  2100. };
  2101. });
  2102. }
  2103. }
  2104. JsonRoutes.sendResult(res, {
  2105. code: 200,
  2106. data: query,
  2107. });
  2108. } catch (error) {
  2109. JsonRoutes.sendResult(res, {
  2110. code: 200,
  2111. data: error,
  2112. });
  2113. }
  2114. },
  2115. );
  2116. /**
  2117. * @operation remove_board_member
  2118. * @tag Boards
  2119. *
  2120. * @summary Remove Member from Board
  2121. *
  2122. * @description Only the admin user (the first user) can call the REST API.
  2123. *
  2124. * @param {string} boardId the board ID
  2125. * @param {string} userId the user ID
  2126. * @param {string} action the action (needs to be `remove`)
  2127. * @return_type {_id: string,
  2128. * title: string}
  2129. */
  2130. JsonRoutes.add(
  2131. 'POST',
  2132. '/api/boards/:boardId/members/:userId/remove',
  2133. function (req, res) {
  2134. try {
  2135. Authentication.checkUserId(req.userId);
  2136. const userId = req.params.userId;
  2137. const boardId = req.params.boardId;
  2138. const action = req.body.action;
  2139. let data = Meteor.users.findOne({
  2140. _id: userId,
  2141. });
  2142. if (data !== undefined) {
  2143. if (action === 'remove') {
  2144. data = Boards.find({
  2145. _id: boardId,
  2146. }).map(function (board) {
  2147. if (board.hasMember(userId)) {
  2148. board.removeMember(userId);
  2149. }
  2150. return {
  2151. _id: board._id,
  2152. title: board.title,
  2153. };
  2154. });
  2155. }
  2156. }
  2157. JsonRoutes.sendResult(res, {
  2158. code: 200,
  2159. data: query,
  2160. });
  2161. } catch (error) {
  2162. JsonRoutes.sendResult(res, {
  2163. code: 200,
  2164. data: error,
  2165. });
  2166. }
  2167. },
  2168. );
  2169. /**
  2170. * @operation new_user
  2171. *
  2172. * @summary Create a new user
  2173. *
  2174. * @description Only the admin user (the first user) can call the REST API.
  2175. *
  2176. * @param {string} username the new username
  2177. * @param {string} email the email of the new user
  2178. * @param {string} password the password of the new user
  2179. * @return_type {_id: string}
  2180. */
  2181. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  2182. try {
  2183. Authentication.checkUserId(req.userId);
  2184. const id = Accounts.createUser({
  2185. username: req.body.username,
  2186. email: req.body.email,
  2187. password: req.body.password,
  2188. from: 'admin',
  2189. });
  2190. JsonRoutes.sendResult(res, {
  2191. code: 200,
  2192. data: {
  2193. _id: id,
  2194. },
  2195. });
  2196. } catch (error) {
  2197. JsonRoutes.sendResult(res, {
  2198. code: 200,
  2199. data: error,
  2200. });
  2201. }
  2202. });
  2203. /**
  2204. * @operation delete_user
  2205. *
  2206. * @summary Delete a user
  2207. *
  2208. * @description Only the admin user (the first user) can call the REST API.
  2209. *
  2210. * @param {string} userId the ID of the user to delete
  2211. * @return_type {_id: string}
  2212. */
  2213. JsonRoutes.add('DELETE', '/api/users/:userId', function (req, res) {
  2214. try {
  2215. Authentication.checkUserId(req.userId);
  2216. const id = req.params.userId;
  2217. // Delete user is enabled, but is still has bug of leaving empty user avatars
  2218. // to boards: boards members, card members and assignees have
  2219. // empty users. So it would be better to delete user from all boards before
  2220. // deleting user.
  2221. // See:
  2222. // - wekan/client/components/settings/peopleBody.jade deleteButton
  2223. // - wekan/client/components/settings/peopleBody.js deleteButton
  2224. // - wekan/client/components/sidebar/sidebar.js Popup.afterConfirm('removeMember'
  2225. // that does now remove member from board, card members and assignees correctly,
  2226. // but that should be used to remove user from all boards similarly
  2227. // - wekan/models/users.js Delete is not enabled
  2228. Meteor.users.remove({ _id: id });
  2229. JsonRoutes.sendResult(res, {
  2230. code: 200,
  2231. data: {
  2232. _id: id,
  2233. },
  2234. });
  2235. } catch (error) {
  2236. JsonRoutes.sendResult(res, {
  2237. code: 200,
  2238. data: error,
  2239. });
  2240. }
  2241. });
  2242. /**
  2243. * @operation create_user_token
  2244. *
  2245. * @summary Create a user token
  2246. *
  2247. * @description Only the admin user (the first user) can call the REST API.
  2248. *
  2249. * @param {string} userId the ID of the user to create token for.
  2250. * @return_type {_id: string}
  2251. */
  2252. JsonRoutes.add('POST', '/api/createtoken/:userId', function (req, res) {
  2253. try {
  2254. Authentication.checkUserId(req.userId);
  2255. const id = req.params.userId;
  2256. const token = Accounts._generateStampedLoginToken();
  2257. Accounts._insertLoginToken(id, token);
  2258. JsonRoutes.sendResult(res, {
  2259. code: 200,
  2260. data: {
  2261. _id: id,
  2262. authToken: token.token,
  2263. },
  2264. });
  2265. } catch (error) {
  2266. JsonRoutes.sendResult(res, {
  2267. code: 200,
  2268. data: error,
  2269. });
  2270. }
  2271. });
  2272. }
  2273. export default Users;