users.js 61 KB

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