users.js 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535
  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. lastConnectionDate: {
  495. type: Date,
  496. optional: true,
  497. },
  498. }),
  499. );
  500. Users.allow({
  501. update(userId, doc) {
  502. const user = Users.findOne({
  503. _id: userId,
  504. });
  505. if ((user && user.isAdmin) || (Meteor.user() && Meteor.user().isAdmin))
  506. return true;
  507. if (!user) {
  508. return false;
  509. }
  510. return doc._id === userId;
  511. },
  512. remove(userId, doc) {
  513. const adminsNumber = Users.find({
  514. isAdmin: true,
  515. }).count();
  516. const { isAdmin } = Users.findOne(
  517. {
  518. _id: userId,
  519. },
  520. {
  521. fields: {
  522. isAdmin: 1,
  523. },
  524. },
  525. );
  526. // Prevents remove of the only one administrator
  527. if (adminsNumber === 1 && isAdmin && userId === doc._id) {
  528. return false;
  529. }
  530. // If it's the user or an admin
  531. return userId === doc._id || isAdmin;
  532. },
  533. fetch: [],
  534. });
  535. // Non-Admin users can not change to Admin
  536. Users.deny({
  537. update(userId, board, fieldNames) {
  538. return _.contains(fieldNames, 'isAdmin') && !Meteor.user().isAdmin;
  539. },
  540. fetch: [],
  541. });
  542. // Search a user in the complete server database by its name, username or emails adress. This
  543. // is used for instance to add a new user to a board.
  544. UserSearchIndex = new Index({
  545. collection: Users,
  546. fields: ['username', 'profile.fullname', 'profile.avatarUrl'],
  547. allowedFields: ['username', 'profile.fullname', 'profile.avatarUrl'],
  548. engine: new MongoDBEngine({
  549. fields: function (searchObject, options) {
  550. return {
  551. username: 1,
  552. 'profile.fullname': 1,
  553. 'profile.avatarUrl': 1,
  554. };
  555. },
  556. }),
  557. });
  558. Users.safeFields = {
  559. _id: 1,
  560. username: 1,
  561. 'profile.fullname': 1,
  562. 'profile.avatarUrl': 1,
  563. 'profile.initials': 1,
  564. orgs: 1,
  565. teams: 1,
  566. authenticationMethod: 1,
  567. lastConnectionDate: 1,
  568. };
  569. if (Meteor.isClient) {
  570. Users.helpers({
  571. isBoardMember() {
  572. const board = Utils.getCurrentBoard();
  573. return board && board.hasMember(this._id);
  574. },
  575. isNotNoComments() {
  576. const board = Utils.getCurrentBoard();
  577. return (
  578. board && board.hasMember(this._id) && !board.hasNoComments(this._id)
  579. );
  580. },
  581. isNoComments() {
  582. const board = Utils.getCurrentBoard();
  583. return board && board.hasNoComments(this._id);
  584. },
  585. isNotCommentOnly() {
  586. const board = Utils.getCurrentBoard();
  587. return (
  588. board && board.hasMember(this._id) && !board.hasCommentOnly(this._id)
  589. );
  590. },
  591. isCommentOnly() {
  592. const board = Utils.getCurrentBoard();
  593. return board && board.hasCommentOnly(this._id);
  594. },
  595. isNotWorker() {
  596. const board = Utils.getCurrentBoard();
  597. return board && board.hasMember(this._id) && !board.hasWorker(this._id);
  598. },
  599. isWorker() {
  600. const board = Utils.getCurrentBoard();
  601. return board && board.hasWorker(this._id);
  602. },
  603. isBoardAdmin(boardId) {
  604. let board;
  605. if (boardId) {
  606. board = Boards.findOne(boardId);
  607. } else {
  608. board = Utils.getCurrentBoard();
  609. }
  610. return board && board.hasAdmin(this._id);
  611. },
  612. });
  613. }
  614. Users.parseImportUsernames = (usernamesString) => {
  615. return usernamesString.trim().split(new RegExp('\\s*[,;]\\s*'));
  616. };
  617. Users.helpers({
  618. importUsernamesString() {
  619. if (this.importUsernames) {
  620. return this.importUsernames.join(', ');
  621. }
  622. return '';
  623. },
  624. teamIds() {
  625. if (this.teams) {
  626. // TODO: Should the Team collection be queried to determine if the team isActive?
  627. return this.teams.map((team) => {
  628. return team.teamId;
  629. });
  630. }
  631. return [];
  632. },
  633. orgIds() {
  634. if (this.orgs) {
  635. // TODO: Should the Org collection be queried to determine if the organization isActive?
  636. return this.orgs.map((org) => {
  637. return org.orgId;
  638. });
  639. }
  640. return [];
  641. },
  642. orgsUserBelongs() {
  643. if (this.orgs) {
  644. return this.orgs
  645. .map(function (org) {
  646. return org.orgDisplayName;
  647. })
  648. .sort()
  649. .join(',');
  650. }
  651. return '';
  652. },
  653. orgIdsUserBelongs() {
  654. if (this.orgs) {
  655. return this.orgs
  656. .map(function (org) {
  657. return org.orgId;
  658. })
  659. .join(',');
  660. }
  661. return '';
  662. },
  663. teamsUserBelongs() {
  664. if (this.teams) {
  665. return this.teams
  666. .map(function (team) {
  667. return team.teamDisplayName;
  668. })
  669. .sort()
  670. .join(',');
  671. }
  672. return '';
  673. },
  674. teamIdsUserBelongs() {
  675. if (this.teams) {
  676. return this.teams
  677. .map(function (team) {
  678. return team.teamId;
  679. })
  680. .join(',');
  681. }
  682. return '';
  683. },
  684. boards() {
  685. return Boards.userBoards(this._id, null, {}, { sort: { sort: 1 } });
  686. },
  687. starredBoards() {
  688. const { starredBoards = [] } = this.profile || {};
  689. return Boards.userBoards(
  690. this._id,
  691. false,
  692. { _id: { $in: starredBoards } },
  693. { sort: { sort: 1 } },
  694. );
  695. },
  696. hasStarred(boardId) {
  697. const { starredBoards = [] } = this.profile || {};
  698. return _.contains(starredBoards, boardId);
  699. },
  700. invitedBoards() {
  701. const { invitedBoards = [] } = this.profile || {};
  702. return Boards.userBoards(
  703. this._id,
  704. false,
  705. { _id: { $in: invitedBoards } },
  706. { sort: { sort: 1 } },
  707. );
  708. },
  709. isInvitedTo(boardId) {
  710. const { invitedBoards = [] } = this.profile || {};
  711. return _.contains(invitedBoards, boardId);
  712. },
  713. _getListSortBy() {
  714. const profile = this.profile || {};
  715. const sortBy = profile.listSortBy || defaultSortBy;
  716. const keyPattern = /^(-{0,1})(.*$)/;
  717. const ret = [];
  718. if (keyPattern.exec(sortBy)) {
  719. ret[0] = RegExp.$2;
  720. ret[1] = RegExp.$1 ? -1 : 1;
  721. }
  722. return ret;
  723. },
  724. hasSortBy() {
  725. // if use doesn't have dragHandle, then we can let user to choose sort list by different order
  726. return !this.hasShowDesktopDragHandles();
  727. },
  728. getListSortBy() {
  729. return this._getListSortBy()[0];
  730. },
  731. getListSortTypes() {
  732. return allowedSortValues;
  733. },
  734. getListSortByDirection() {
  735. return this._getListSortBy()[1];
  736. },
  737. /** returns all confirmed move and copy dialog field values
  738. * <li> the board, swimlane and list id is stored for each board
  739. */
  740. getMoveAndCopyDialogOptions() {
  741. let _ret = {};
  742. if (this.profile && this.profile.moveAndCopyDialog) {
  743. _ret = this.profile.moveAndCopyDialog;
  744. }
  745. return _ret;
  746. },
  747. /** returns all confirmed move checklist dialog field values
  748. * <li> the board, swimlane, list and card id is stored for each board
  749. */
  750. getMoveChecklistDialogOptions() {
  751. let _ret = {};
  752. if (this.profile && this.profile.moveChecklistDialog) {
  753. _ret = this.profile.moveChecklistDialog;
  754. }
  755. return _ret;
  756. },
  757. /** returns all confirmed copy checklist dialog field values
  758. * <li> the board, swimlane, list and card id is stored for each board
  759. */
  760. getCopyChecklistDialogOptions() {
  761. let _ret = {};
  762. if (this.profile && this.profile.copyChecklistDialog) {
  763. _ret = this.profile.copyChecklistDialog;
  764. }
  765. return _ret;
  766. },
  767. hasTag(tag) {
  768. const { tags = [] } = this.profile || {};
  769. return _.contains(tags, tag);
  770. },
  771. hasNotification(activityId) {
  772. const { notifications = [] } = this.profile || {};
  773. return _.contains(notifications, activityId);
  774. },
  775. notifications() {
  776. const { notifications = [] } = this.profile || {};
  777. for (const index in notifications) {
  778. if (!notifications.hasOwnProperty(index)) continue;
  779. const notification = notifications[index];
  780. // this preserves their db sort order for editing
  781. notification.dbIndex = index;
  782. notification.activity = Activities.findOne(notification.activity);
  783. }
  784. // this sorts them newest to oldest to match Trello's behavior
  785. notifications.reverse();
  786. return notifications;
  787. },
  788. hasShowDesktopDragHandles() {
  789. const profile = this.profile || {};
  790. return profile.showDesktopDragHandles || false;
  791. },
  792. hasHideCheckedItems() {
  793. const profile = this.profile || {};
  794. return profile.hideCheckedItems || false;
  795. },
  796. hasHiddenSystemMessages() {
  797. const profile = this.profile || {};
  798. return profile.hiddenSystemMessages || false;
  799. },
  800. hasCustomFieldsGrid() {
  801. const profile = this.profile || {};
  802. return profile.customFieldsGrid || false;
  803. },
  804. hasCardMaximized() {
  805. const profile = this.profile || {};
  806. return profile.cardMaximized || false;
  807. },
  808. hasHiddenMinicardLabelText() {
  809. const profile = this.profile || {};
  810. return profile.hiddenMinicardLabelText || false;
  811. },
  812. hasRescuedCardDescription() {
  813. const profile = this.profile || {};
  814. return profile.rescueCardDescription || false;
  815. },
  816. getEmailBuffer() {
  817. const { emailBuffer = [] } = this.profile || {};
  818. return emailBuffer;
  819. },
  820. getInitials() {
  821. const profile = this.profile || {};
  822. if (profile.initials) return profile.initials;
  823. else if (profile.fullname) {
  824. return profile.fullname
  825. .split(/\s+/)
  826. .reduce((memo, word) => {
  827. return memo + word[0];
  828. }, '')
  829. .toUpperCase();
  830. } else {
  831. return this.username[0].toUpperCase();
  832. }
  833. },
  834. getLimitToShowCardsCount() {
  835. const profile = this.profile || {};
  836. return profile.showCardsCountAt;
  837. },
  838. getName() {
  839. const profile = this.profile || {};
  840. return profile.fullname || this.username;
  841. },
  842. getLanguage() {
  843. const profile = this.profile || {};
  844. return profile.language || 'en';
  845. },
  846. getStartDayOfWeek() {
  847. const profile = this.profile || {};
  848. if (typeof profile.startDayOfWeek === 'undefined') {
  849. // default is 'Monday' (1)
  850. return 1;
  851. }
  852. return profile.startDayOfWeek;
  853. },
  854. getTemplatesBoardId() {
  855. return (this.profile || {}).templatesBoardId;
  856. },
  857. getTemplatesBoardSlug() {
  858. //return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  859. return 'templates';
  860. },
  861. remove() {
  862. User.remove({
  863. _id: this._id,
  864. });
  865. },
  866. });
  867. Users.mutations({
  868. /** set the confirmed board id/swimlane id/list id of a board
  869. * @param boardId the current board id
  870. * @param options an object with the confirmed field values
  871. */
  872. setMoveAndCopyDialogOption(boardId, options) {
  873. let currentOptions = this.getMoveAndCopyDialogOptions();
  874. currentOptions[boardId] = options;
  875. return {
  876. $set: {
  877. 'profile.moveAndCopyDialog': currentOptions,
  878. },
  879. };
  880. },
  881. /** set the confirmed board id/swimlane id/list id/card id of a board (move checklist)
  882. * @param boardId the current board id
  883. * @param options an object with the confirmed field values
  884. */
  885. setMoveChecklistDialogOption(boardId, options) {
  886. let currentOptions = this.getMoveChecklistDialogOptions();
  887. currentOptions[boardId] = options;
  888. return {
  889. $set: {
  890. 'profile.moveChecklistDialog': currentOptions,
  891. },
  892. };
  893. },
  894. /** set the confirmed board id/swimlane id/list id/card id of a board (copy checklist)
  895. * @param boardId the current board id
  896. * @param options an object with the confirmed field values
  897. */
  898. setCopyChecklistDialogOption(boardId, options) {
  899. let currentOptions = this.getCopyChecklistDialogOptions();
  900. currentOptions[boardId] = options;
  901. return {
  902. $set: {
  903. 'profile.copyChecklistDialog': currentOptions,
  904. },
  905. };
  906. },
  907. toggleBoardStar(boardId) {
  908. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  909. return {
  910. [queryKind]: {
  911. 'profile.starredBoards': boardId,
  912. },
  913. };
  914. },
  915. addInvite(boardId) {
  916. return {
  917. $addToSet: {
  918. 'profile.invitedBoards': boardId,
  919. },
  920. };
  921. },
  922. removeInvite(boardId) {
  923. return {
  924. $pull: {
  925. 'profile.invitedBoards': boardId,
  926. },
  927. };
  928. },
  929. addTag(tag) {
  930. return {
  931. $addToSet: {
  932. 'profile.tags': tag,
  933. },
  934. };
  935. },
  936. removeTag(tag) {
  937. return {
  938. $pull: {
  939. 'profile.tags': tag,
  940. },
  941. };
  942. },
  943. toggleTag(tag) {
  944. if (this.hasTag(tag)) this.removeTag(tag);
  945. else this.addTag(tag);
  946. },
  947. setListSortBy(value) {
  948. return {
  949. $set: {
  950. 'profile.listSortBy': value,
  951. },
  952. };
  953. },
  954. setName(value) {
  955. return {
  956. $set: {
  957. 'profile.fullname': value,
  958. },
  959. };
  960. },
  961. toggleDesktopHandles(value = false) {
  962. return {
  963. $set: {
  964. 'profile.showDesktopDragHandles': !value,
  965. },
  966. };
  967. },
  968. toggleHideCheckedItems() {
  969. const value = this.hasHideCheckedItems();
  970. return {
  971. $set: {
  972. 'profile.hideCheckedItems': !value,
  973. },
  974. };
  975. },
  976. toggleSystem(value = false) {
  977. return {
  978. $set: {
  979. 'profile.hiddenSystemMessages': !value,
  980. },
  981. };
  982. },
  983. toggleFieldsGrid(value = false) {
  984. return {
  985. $set: {
  986. 'profile.customFieldsGrid': !value,
  987. },
  988. };
  989. },
  990. toggleCardMaximized(value = false) {
  991. return {
  992. $set: {
  993. 'profile.cardMaximized': !value,
  994. },
  995. };
  996. },
  997. toggleLabelText(value = false) {
  998. return {
  999. $set: {
  1000. 'profile.hiddenMinicardLabelText': !value,
  1001. },
  1002. };
  1003. },
  1004. toggleRescueCardDescription(value = false) {
  1005. return {
  1006. $set: {
  1007. 'profile.rescueCardDescription': !value,
  1008. },
  1009. };
  1010. },
  1011. addNotification(activityId) {
  1012. return {
  1013. $addToSet: {
  1014. 'profile.notifications': {
  1015. activity: activityId,
  1016. },
  1017. },
  1018. };
  1019. },
  1020. removeNotification(activityId) {
  1021. return {
  1022. $pull: {
  1023. 'profile.notifications': {
  1024. activity: activityId,
  1025. },
  1026. },
  1027. };
  1028. },
  1029. addEmailBuffer(text) {
  1030. return {
  1031. $addToSet: {
  1032. 'profile.emailBuffer': text,
  1033. },
  1034. };
  1035. },
  1036. clearEmailBuffer() {
  1037. return {
  1038. $set: {
  1039. 'profile.emailBuffer': [],
  1040. },
  1041. };
  1042. },
  1043. setAvatarUrl(avatarUrl) {
  1044. return {
  1045. $set: {
  1046. 'profile.avatarUrl': avatarUrl,
  1047. },
  1048. };
  1049. },
  1050. setShowCardsCountAt(limit) {
  1051. return {
  1052. $set: {
  1053. 'profile.showCardsCountAt': limit,
  1054. },
  1055. };
  1056. },
  1057. setStartDayOfWeek(startDay) {
  1058. return {
  1059. $set: {
  1060. 'profile.startDayOfWeek': startDay,
  1061. },
  1062. };
  1063. },
  1064. setBoardView(view) {
  1065. return {
  1066. $set: {
  1067. 'profile.boardView': view,
  1068. },
  1069. };
  1070. },
  1071. });
  1072. Meteor.methods({
  1073. setListSortBy(value) {
  1074. check(value, String);
  1075. Meteor.user().setListSortBy(value);
  1076. },
  1077. toggleDesktopDragHandles() {
  1078. const user = Meteor.user();
  1079. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  1080. },
  1081. toggleHideCheckedItems() {
  1082. const user = Meteor.user();
  1083. user.toggleHideCheckedItems();
  1084. },
  1085. toggleSystemMessages() {
  1086. const user = Meteor.user();
  1087. user.toggleSystem(user.hasHiddenSystemMessages());
  1088. },
  1089. toggleCustomFieldsGrid() {
  1090. const user = Meteor.user();
  1091. user.toggleFieldsGrid(user.hasCustomFieldsGrid());
  1092. },
  1093. toggleCardMaximized() {
  1094. const user = Meteor.user();
  1095. user.toggleCardMaximized(user.hasCardMaximized());
  1096. },
  1097. toggleMinicardLabelText() {
  1098. const user = Meteor.user();
  1099. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  1100. },
  1101. toggleRescueCardDescription() {
  1102. const user = Meteor.user();
  1103. user.toggleRescueCardDescription(user.hasRescuedCardDescription());
  1104. },
  1105. changeLimitToShowCardsCount(limit) {
  1106. check(limit, Number);
  1107. Meteor.user().setShowCardsCountAt(limit);
  1108. },
  1109. changeStartDayOfWeek(startDay) {
  1110. check(startDay, Number);
  1111. Meteor.user().setStartDayOfWeek(startDay);
  1112. },
  1113. });
  1114. if (Meteor.isServer) {
  1115. Meteor.methods({
  1116. setAllUsersHideSystemMessages() {
  1117. if (Meteor.user() && Meteor.user().isAdmin) {
  1118. // If setting is missing, add it
  1119. Users.update(
  1120. {
  1121. 'profile.hiddenSystemMessages': {
  1122. $exists: false,
  1123. },
  1124. },
  1125. {
  1126. $set: {
  1127. 'profile.hiddenSystemMessages': true,
  1128. },
  1129. },
  1130. {
  1131. multi: true,
  1132. },
  1133. );
  1134. // If setting is false, set it to true
  1135. Users.update(
  1136. {
  1137. 'profile.hiddenSystemMessages': false,
  1138. },
  1139. {
  1140. $set: {
  1141. 'profile.hiddenSystemMessages': true,
  1142. },
  1143. },
  1144. {
  1145. multi: true,
  1146. },
  1147. );
  1148. return true;
  1149. } else {
  1150. return false;
  1151. }
  1152. },
  1153. setCreateUser(
  1154. fullname,
  1155. username,
  1156. initials,
  1157. password,
  1158. isAdmin,
  1159. isActive,
  1160. email,
  1161. importUsernames,
  1162. userOrgsArray,
  1163. userTeamsArray,
  1164. ) {
  1165. check(fullname, String);
  1166. check(username, String);
  1167. check(initials, String);
  1168. check(password, String);
  1169. check(isAdmin, String);
  1170. check(isActive, String);
  1171. check(email, String);
  1172. check(importUsernames, Array);
  1173. check(userOrgsArray, Array);
  1174. check(userTeamsArray, Array);
  1175. if (Meteor.user() && Meteor.user().isAdmin) {
  1176. const nUsersWithUsername = Users.find({
  1177. username,
  1178. }).count();
  1179. const nUsersWithEmail = Users.find({
  1180. email,
  1181. }).count();
  1182. if (nUsersWithUsername > 0) {
  1183. throw new Meteor.Error('username-already-taken');
  1184. } else if (nUsersWithEmail > 0) {
  1185. throw new Meteor.Error('email-already-taken');
  1186. } else {
  1187. Accounts.createUser({
  1188. username,
  1189. password,
  1190. isAdmin,
  1191. isActive,
  1192. email: email.toLowerCase(),
  1193. from: 'admin',
  1194. });
  1195. const user =
  1196. Users.findOne(username) ||
  1197. Users.findOne({
  1198. username,
  1199. });
  1200. if (user) {
  1201. Users.update(user._id, {
  1202. $set: {
  1203. 'profile.fullname': fullname,
  1204. importUsernames,
  1205. 'profile.initials': initials,
  1206. orgs: userOrgsArray,
  1207. teams: userTeamsArray,
  1208. },
  1209. });
  1210. }
  1211. }
  1212. }
  1213. },
  1214. setUsername(username, userId) {
  1215. check(username, String);
  1216. check(userId, String);
  1217. if (Meteor.user() && Meteor.user().isAdmin) {
  1218. const nUsersWithUsername = Users.find({
  1219. username,
  1220. }).count();
  1221. if (nUsersWithUsername > 0) {
  1222. throw new Meteor.Error('username-already-taken');
  1223. } else {
  1224. Users.update(userId, {
  1225. $set: {
  1226. username,
  1227. },
  1228. });
  1229. }
  1230. }
  1231. },
  1232. setEmail(email, userId) {
  1233. check(email, String);
  1234. check(username, String);
  1235. if (Meteor.user() && Meteor.user().isAdmin) {
  1236. if (Array.isArray(email)) {
  1237. email = email.shift();
  1238. }
  1239. const existingUser = Users.findOne(
  1240. {
  1241. 'emails.address': email,
  1242. },
  1243. {
  1244. fields: {
  1245. _id: 1,
  1246. },
  1247. },
  1248. );
  1249. if (existingUser) {
  1250. throw new Meteor.Error('email-already-taken');
  1251. } else {
  1252. Users.update(userId, {
  1253. $set: {
  1254. emails: [
  1255. {
  1256. address: email,
  1257. verified: false,
  1258. },
  1259. ],
  1260. },
  1261. });
  1262. }
  1263. }
  1264. },
  1265. setUsernameAndEmail(username, email, userId) {
  1266. check(username, String);
  1267. check(email, String);
  1268. check(userId, String);
  1269. if (Meteor.user() && Meteor.user().isAdmin) {
  1270. if (Array.isArray(email)) {
  1271. email = email.shift();
  1272. }
  1273. Meteor.call('setUsername', username, userId);
  1274. Meteor.call('setEmail', email, userId);
  1275. }
  1276. },
  1277. setPassword(newPassword, userId) {
  1278. check(userId, String);
  1279. check(newPassword, String);
  1280. if (Meteor.user() && Meteor.user().isAdmin) {
  1281. if (Meteor.user().isAdmin) {
  1282. Accounts.setPassword(userId, newPassword);
  1283. }
  1284. }
  1285. },
  1286. setEmailVerified(email, verified, userId) {
  1287. check(email, String);
  1288. check(verified, Boolean);
  1289. check(userId, String);
  1290. if (Meteor.user() && Meteor.user().isAdmin) {
  1291. Users.update(userId, {
  1292. $set: {
  1293. emails: [
  1294. {
  1295. address: email,
  1296. verified,
  1297. },
  1298. ],
  1299. },
  1300. });
  1301. }
  1302. },
  1303. setInitials(initials, userId) {
  1304. check(initials, String);
  1305. check(userId, String);
  1306. if (Meteor.user() && Meteor.user().isAdmin) {
  1307. Users.update(userId, {
  1308. $set: {
  1309. 'profile.initials': initials,
  1310. },
  1311. });
  1312. }
  1313. },
  1314. // we accept userId, username, email
  1315. inviteUserToBoard(username, boardId) {
  1316. check(username, String);
  1317. check(boardId, String);
  1318. const inviter = Meteor.user();
  1319. const board = Boards.findOne(boardId);
  1320. const allowInvite =
  1321. inviter &&
  1322. board &&
  1323. board.members &&
  1324. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  1325. _.where(board.members, {
  1326. userId: inviter._id,
  1327. })[0].isActive;
  1328. // GitHub issue 2060
  1329. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  1330. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  1331. this.unblock();
  1332. const posAt = username.indexOf('@');
  1333. let user = null;
  1334. if (posAt >= 0) {
  1335. user = Users.findOne({
  1336. emails: {
  1337. $elemMatch: {
  1338. address: username,
  1339. },
  1340. },
  1341. });
  1342. } else {
  1343. user =
  1344. Users.findOne(username) ||
  1345. Users.findOne({
  1346. username,
  1347. });
  1348. }
  1349. if (user) {
  1350. if (user._id === inviter._id)
  1351. throw new Meteor.Error('error-user-notAllowSelf');
  1352. } else {
  1353. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  1354. if (
  1355. Settings.findOne({
  1356. disableRegistration: true,
  1357. })
  1358. ) {
  1359. throw new Meteor.Error('error-user-notCreated');
  1360. }
  1361. // Set in lowercase email before creating account
  1362. const email = username.toLowerCase();
  1363. username = email.substring(0, posAt);
  1364. const newUserId = Accounts.createUser({
  1365. username,
  1366. email,
  1367. });
  1368. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  1369. // assume new user speak same language with inviter
  1370. if (inviter.profile && inviter.profile.language) {
  1371. Users.update(newUserId, {
  1372. $set: {
  1373. 'profile.language': inviter.profile.language,
  1374. },
  1375. });
  1376. }
  1377. Accounts.sendEnrollmentEmail(newUserId);
  1378. user = Users.findOne(newUserId);
  1379. }
  1380. board.addMember(user._id);
  1381. user.addInvite(boardId);
  1382. //Check if there is a subtasks board
  1383. if (board.subtasksDefaultBoardId) {
  1384. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  1385. //If there is, also add user to that board
  1386. if (subBoard) {
  1387. subBoard.addMember(user._id);
  1388. user.addInvite(subBoard._id);
  1389. }
  1390. }
  1391. try {
  1392. const fullName =
  1393. inviter.profile !== undefined &&
  1394. inviter.profile.fullname !== undefined
  1395. ? inviter.profile.fullname
  1396. : '';
  1397. const userFullName =
  1398. user.profile !== undefined && user.profile.fullname !== undefined
  1399. ? user.profile.fullname
  1400. : '';
  1401. const params = {
  1402. user:
  1403. userFullName != ''
  1404. ? userFullName + ' (' + user.username + ' )'
  1405. : user.username,
  1406. inviter:
  1407. fullName != ''
  1408. ? fullName + ' (' + inviter.username + ' )'
  1409. : inviter.username,
  1410. board: board.title,
  1411. url: board.absoluteUrl(),
  1412. };
  1413. const lang = user.getLanguage();
  1414. /*
  1415. if (process.env.MAIL_SERVICE !== '') {
  1416. let transporter = nodemailer.createTransport({
  1417. service: process.env.MAIL_SERVICE,
  1418. auth: {
  1419. user: process.env.MAIL_SERVICE_USER,
  1420. pass: process.env.MAIL_SERVICE_PASSWORD
  1421. },
  1422. })
  1423. let info = transporter.sendMail({
  1424. to: user.emails[0].address.toLowerCase(),
  1425. from: Accounts.emailTemplates.from,
  1426. subject: TAPi18n.__('email-invite-subject', params, lang),
  1427. text: TAPi18n.__('email-invite-text', params, lang),
  1428. })
  1429. } else {
  1430. Email.send({
  1431. to: user.emails[0].address.toLowerCase(),
  1432. from: Accounts.emailTemplates.from,
  1433. subject: TAPi18n.__('email-invite-subject', params, lang),
  1434. text: TAPi18n.__('email-invite-text', params, lang),
  1435. });
  1436. }
  1437. */
  1438. Email.send({
  1439. to: user.emails[0].address.toLowerCase(),
  1440. from: Accounts.emailTemplates.from,
  1441. subject: TAPi18n.__('email-invite-subject', params, lang),
  1442. text: TAPi18n.__('email-invite-text', params, lang),
  1443. });
  1444. } catch (e) {
  1445. throw new Meteor.Error('email-fail', e.message);
  1446. }
  1447. return {
  1448. username: user.username,
  1449. email: user.emails[0].address,
  1450. };
  1451. },
  1452. impersonate(userId) {
  1453. check(userId, String);
  1454. if (!Meteor.users.findOne(userId))
  1455. throw new Meteor.Error(404, 'User not found');
  1456. if (!Meteor.user().isAdmin)
  1457. throw new Meteor.Error(403, 'Permission denied');
  1458. ImpersonatedUsers.insert({
  1459. adminId: Meteor.user()._id,
  1460. userId: userId,
  1461. reason: 'clickedImpersonate',
  1462. });
  1463. this.setUserId(userId);
  1464. },
  1465. isImpersonated(userId) {
  1466. check(userId, String);
  1467. const isImpersonated = ImpersonatedUsers.findOne({
  1468. userId: userId,
  1469. });
  1470. return isImpersonated;
  1471. },
  1472. setUsersTeamsTeamDisplayName(teamId, teamDisplayName) {
  1473. check(teamId, String);
  1474. check(teamDisplayName, String);
  1475. if (Meteor.user() && Meteor.user().isAdmin) {
  1476. Users.find({
  1477. teams: {
  1478. $elemMatch: { teamId: teamId },
  1479. },
  1480. }).forEach((user) => {
  1481. Users.update(
  1482. {
  1483. _id: user._id,
  1484. teams: {
  1485. $elemMatch: { teamId: teamId },
  1486. },
  1487. },
  1488. {
  1489. $set: {
  1490. 'teams.$.teamDisplayName': teamDisplayName,
  1491. },
  1492. },
  1493. );
  1494. });
  1495. }
  1496. },
  1497. setUsersOrgsOrgDisplayName(orgId, orgDisplayName) {
  1498. check(orgId, String);
  1499. check(orgDisplayName, String);
  1500. if (Meteor.user() && Meteor.user().isAdmin) {
  1501. Users.find({
  1502. orgs: {
  1503. $elemMatch: { orgId: orgId },
  1504. },
  1505. }).forEach((user) => {
  1506. Users.update(
  1507. {
  1508. _id: user._id,
  1509. orgs: {
  1510. $elemMatch: { orgId: orgId },
  1511. },
  1512. },
  1513. {
  1514. $set: {
  1515. 'orgs.$.orgDisplayName': orgDisplayName,
  1516. },
  1517. },
  1518. );
  1519. });
  1520. }
  1521. },
  1522. });
  1523. Accounts.onCreateUser((options, user) => {
  1524. const userCount = Users.find().count();
  1525. if (userCount === 0) {
  1526. user.isAdmin = true;
  1527. }
  1528. if (user.services.oidc) {
  1529. let email = user.services.oidc.email;
  1530. if (Array.isArray(email)) {
  1531. email = email.shift();
  1532. }
  1533. email = email.toLowerCase();
  1534. user.username = user.services.oidc.username;
  1535. user.emails = [
  1536. {
  1537. address: email,
  1538. verified: true,
  1539. },
  1540. ];
  1541. const initials = user.services.oidc.fullname
  1542. .split(/\s+/)
  1543. .reduce((memo, word) => {
  1544. return memo + word[0];
  1545. }, '')
  1546. .toUpperCase();
  1547. user.profile = {
  1548. initials,
  1549. fullname: user.services.oidc.fullname,
  1550. boardView: 'board-view-swimlanes',
  1551. };
  1552. user.authenticationMethod = 'oauth2';
  1553. // see if any existing user has this email address or username, otherwise create new
  1554. const existingUser = Meteor.users.findOne({
  1555. $or: [
  1556. {
  1557. 'emails.address': email,
  1558. },
  1559. {
  1560. username: user.username,
  1561. },
  1562. ],
  1563. });
  1564. if (!existingUser) return user;
  1565. // copy across new service info
  1566. const service = _.keys(user.services)[0];
  1567. existingUser.services[service] = user.services[service];
  1568. existingUser.emails = user.emails;
  1569. existingUser.username = user.username;
  1570. existingUser.profile = user.profile;
  1571. existingUser.authenticationMethod = user.authenticationMethod;
  1572. Meteor.users.remove({
  1573. _id: user._id,
  1574. });
  1575. Meteor.users.remove({
  1576. _id: existingUser._id,
  1577. }); // is going to be created again
  1578. return existingUser;
  1579. }
  1580. if (options.from === 'admin') {
  1581. user.createdThroughApi = true;
  1582. return user;
  1583. }
  1584. const disableRegistration = Settings.findOne().disableRegistration;
  1585. // If this is the first Authentication by the ldap and self registration disabled
  1586. if (disableRegistration && options && options.ldap) {
  1587. user.authenticationMethod = 'ldap';
  1588. return user;
  1589. }
  1590. // If self registration enabled
  1591. if (!disableRegistration) {
  1592. return user;
  1593. }
  1594. if (!options || !options.profile) {
  1595. throw new Meteor.Error(
  1596. 'error-invitation-code-blank',
  1597. 'The invitation code is required',
  1598. );
  1599. }
  1600. const invitationCode = InvitationCodes.findOne({
  1601. code: options.profile.invitationcode,
  1602. email: options.email,
  1603. valid: true,
  1604. });
  1605. if (!invitationCode) {
  1606. throw new Meteor.Error(
  1607. 'error-invitation-code-not-exist',
  1608. // eslint-disable-next-line quotes
  1609. "The invitation code doesn't exist",
  1610. );
  1611. } else {
  1612. user.profile = {
  1613. icode: options.profile.invitationcode,
  1614. };
  1615. user.profile.boardView = 'board-view-swimlanes';
  1616. // Deletes the invitation code after the user was created successfully.
  1617. setTimeout(
  1618. Meteor.bindEnvironment(() => {
  1619. InvitationCodes.remove({
  1620. _id: invitationCode._id,
  1621. });
  1622. }),
  1623. 200,
  1624. );
  1625. return user;
  1626. }
  1627. });
  1628. }
  1629. const addCronJob = _.debounce(
  1630. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  1631. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  1632. const envRemoveAge =
  1633. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  1634. // default notifications will be removed 2 days after they are read
  1635. const defaultRemoveAge = 2;
  1636. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  1637. SyncedCron.add({
  1638. name: 'notification_cleanup',
  1639. schedule: (parser) => parser.text('every 1 days'),
  1640. job: () => {
  1641. for (const user of Users.find()) {
  1642. if (!user.profile || !user.profile.notifications) continue;
  1643. for (const notification of user.profile.notifications) {
  1644. if (notification.read) {
  1645. const removeDate = new Date(notification.read);
  1646. removeDate.setDate(removeDate.getDate() + removeAge);
  1647. if (removeDate <= new Date()) {
  1648. user.removeNotification(notification.activity);
  1649. }
  1650. }
  1651. }
  1652. }
  1653. },
  1654. });
  1655. SyncedCron.start();
  1656. }),
  1657. 500,
  1658. );
  1659. if (Meteor.isServer) {
  1660. // Let mongoDB ensure username unicity
  1661. Meteor.startup(() => {
  1662. allowedSortValues.forEach((value) => {
  1663. Lists._collection.createIndex(value);
  1664. });
  1665. Users._collection.createIndex({
  1666. modifiedAt: -1,
  1667. });
  1668. /* Commented out extra index because of IndexOptionsConflict.
  1669. Users._collection.createIndex(
  1670. {
  1671. username: 1,
  1672. },
  1673. {
  1674. unique: true,
  1675. },
  1676. );
  1677. */
  1678. Meteor.defer(() => {
  1679. addCronJob();
  1680. });
  1681. });
  1682. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  1683. // if admin is removed, board is removed.
  1684. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  1685. // to use that board, and not have board deleted.
  1686. // Someone can be later changed to be admin of board, by making change to database.
  1687. // TODO: Add UI for changing someone as board admin.
  1688. //Users.before.remove((userId, doc) => {
  1689. // Boards
  1690. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  1691. // .forEach((board) => {
  1692. // // If only one admin for the board
  1693. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  1694. // Boards.remove(board._id);
  1695. // }
  1696. // });
  1697. //});
  1698. // Each board document contains the de-normalized number of users that have
  1699. // starred it. If the user star or unstar a board, we need to update this
  1700. // counter.
  1701. // We need to run this code on the server only, otherwise the incrementation
  1702. // will be done twice.
  1703. Users.after.update(function (userId, user, fieldNames) {
  1704. // The `starredBoards` list is hosted on the `profile` field. If this
  1705. // field hasn't been modificated we don't need to run this hook.
  1706. if (!_.contains(fieldNames, 'profile')) return;
  1707. // To calculate a diff of board starred ids, we get both the previous
  1708. // and the newly board ids list
  1709. function getStarredBoardsIds(doc) {
  1710. return doc.profile && doc.profile.starredBoards;
  1711. }
  1712. const oldIds = getStarredBoardsIds(this.previous);
  1713. const newIds = getStarredBoardsIds(user);
  1714. // The _.difference(a, b) method returns the values from a that are not in
  1715. // b. We use it to find deleted and newly inserted ids by using it in one
  1716. // direction and then in the other.
  1717. function incrementBoards(boardsIds, inc) {
  1718. boardsIds.forEach((boardId) => {
  1719. Boards.update(boardId, {
  1720. $inc: {
  1721. stars: inc,
  1722. },
  1723. });
  1724. });
  1725. }
  1726. incrementBoards(_.difference(oldIds, newIds), -1);
  1727. incrementBoards(_.difference(newIds, oldIds), +1);
  1728. });
  1729. // Override getUserId so that we can TODO get the current userId
  1730. const fakeUserId = new Meteor.EnvironmentVariable();
  1731. const getUserId = CollectionHooks.getUserId;
  1732. CollectionHooks.getUserId = () => {
  1733. return fakeUserId.get() || getUserId();
  1734. };
  1735. if (!isSandstorm) {
  1736. Users.after.insert((userId, doc) => {
  1737. const fakeUser = {
  1738. extendAutoValueContext: {
  1739. userId: doc._id,
  1740. },
  1741. };
  1742. fakeUserId.withValue(doc._id, () => {
  1743. /*
  1744. // Insert the Welcome Board
  1745. Boards.insert({
  1746. title: TAPi18n.__('welcome-board'),
  1747. permission: 'private',
  1748. }, fakeUser, (err, boardId) => {
  1749. Swimlanes.insert({
  1750. title: TAPi18n.__('welcome-swimlane'),
  1751. boardId,
  1752. sort: 1,
  1753. }, fakeUser);
  1754. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1755. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1756. });
  1757. });
  1758. */
  1759. // Insert Template Container
  1760. const Future = require('fibers/future');
  1761. const future1 = new Future();
  1762. const future2 = new Future();
  1763. const future3 = new Future();
  1764. Boards.insert(
  1765. {
  1766. title: TAPi18n.__('templates'),
  1767. permission: 'private',
  1768. type: 'template-container',
  1769. },
  1770. fakeUser,
  1771. (err, boardId) => {
  1772. // Insert the reference to our templates board
  1773. Users.update(fakeUserId.get(), {
  1774. $set: {
  1775. 'profile.templatesBoardId': boardId,
  1776. },
  1777. });
  1778. // Insert the card templates swimlane
  1779. Swimlanes.insert(
  1780. {
  1781. title: TAPi18n.__('card-templates-swimlane'),
  1782. boardId,
  1783. sort: 1,
  1784. type: 'template-container',
  1785. },
  1786. fakeUser,
  1787. (err, swimlaneId) => {
  1788. // Insert the reference to out card templates swimlane
  1789. Users.update(fakeUserId.get(), {
  1790. $set: {
  1791. 'profile.cardTemplatesSwimlaneId': swimlaneId,
  1792. },
  1793. });
  1794. future1.return();
  1795. },
  1796. );
  1797. // Insert the list templates swimlane
  1798. Swimlanes.insert(
  1799. {
  1800. title: TAPi18n.__('list-templates-swimlane'),
  1801. boardId,
  1802. sort: 2,
  1803. type: 'template-container',
  1804. },
  1805. fakeUser,
  1806. (err, swimlaneId) => {
  1807. // Insert the reference to out list templates swimlane
  1808. Users.update(fakeUserId.get(), {
  1809. $set: {
  1810. 'profile.listTemplatesSwimlaneId': swimlaneId,
  1811. },
  1812. });
  1813. future2.return();
  1814. },
  1815. );
  1816. // Insert the board templates swimlane
  1817. Swimlanes.insert(
  1818. {
  1819. title: TAPi18n.__('board-templates-swimlane'),
  1820. boardId,
  1821. sort: 3,
  1822. type: 'template-container',
  1823. },
  1824. fakeUser,
  1825. (err, swimlaneId) => {
  1826. // Insert the reference to out board templates swimlane
  1827. Users.update(fakeUserId.get(), {
  1828. $set: {
  1829. 'profile.boardTemplatesSwimlaneId': swimlaneId,
  1830. },
  1831. });
  1832. future3.return();
  1833. },
  1834. );
  1835. },
  1836. );
  1837. // HACK
  1838. future1.wait();
  1839. future2.wait();
  1840. future3.wait();
  1841. // End of Insert Template Container
  1842. });
  1843. });
  1844. }
  1845. Users.after.insert((userId, doc) => {
  1846. // HACK
  1847. doc = Users.findOne({
  1848. _id: doc._id,
  1849. });
  1850. if (doc.createdThroughApi) {
  1851. // The admin user should be able to create a user despite disabling registration because
  1852. // it is two different things (registration and creation).
  1853. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1854. // the disableRegistration check.
  1855. // Issue : https://github.com/wekan/wekan/issues/1232
  1856. // PR : https://github.com/wekan/wekan/pull/1251
  1857. Users.update(doc._id, {
  1858. $set: {
  1859. createdThroughApi: '',
  1860. },
  1861. });
  1862. return;
  1863. }
  1864. //invite user to corresponding boards
  1865. const disableRegistration = Settings.findOne().disableRegistration;
  1866. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1867. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1868. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1869. let invitationCode = null;
  1870. if (doc.authenticationMethod.toLowerCase() == 'oauth2') {
  1871. // OIDC authentication mode
  1872. invitationCode = InvitationCodes.findOne({
  1873. email: doc.emails[0].address.toLowerCase(),
  1874. valid: true,
  1875. });
  1876. } else {
  1877. invitationCode = InvitationCodes.findOne({
  1878. code: doc.profile.icode,
  1879. valid: true,
  1880. });
  1881. }
  1882. if (!invitationCode) {
  1883. throw new Meteor.Error('error-invitation-code-not-exist');
  1884. } else {
  1885. invitationCode.boardsToBeInvited.forEach((boardId) => {
  1886. const board = Boards.findOne(boardId);
  1887. board.addMember(doc._id);
  1888. });
  1889. if (!doc.profile) {
  1890. doc.profile = {};
  1891. }
  1892. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1893. Users.update(doc._id, {
  1894. $set: {
  1895. profile: doc.profile,
  1896. },
  1897. });
  1898. InvitationCodes.update(invitationCode._id, {
  1899. $set: {
  1900. valid: false,
  1901. },
  1902. });
  1903. }
  1904. }
  1905. });
  1906. }
  1907. // USERS REST API
  1908. if (Meteor.isServer) {
  1909. // Middleware which checks that API is enabled.
  1910. JsonRoutes.Middleware.use(function (req, res, next) {
  1911. const api = req.url.startsWith('/api');
  1912. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1913. return next();
  1914. } else {
  1915. res.writeHead(301, {
  1916. Location: '/',
  1917. });
  1918. return res.end();
  1919. }
  1920. });
  1921. /**
  1922. * @operation get_current_user
  1923. *
  1924. * @summary returns the current user
  1925. * @return_type Users
  1926. */
  1927. JsonRoutes.add('GET', '/api/user', function (req, res) {
  1928. try {
  1929. Authentication.checkLoggedIn(req.userId);
  1930. const data = Meteor.users.findOne({
  1931. _id: req.userId,
  1932. });
  1933. delete data.services;
  1934. // get all boards where the user is member of
  1935. let boards = Boards.find(
  1936. {
  1937. type: 'board',
  1938. 'members.userId': req.userId,
  1939. },
  1940. {
  1941. fields: {
  1942. _id: 1,
  1943. members: 1,
  1944. },
  1945. },
  1946. );
  1947. boards = boards.map((b) => {
  1948. const u = b.members.find((m) => m.userId === req.userId);
  1949. delete u.userId;
  1950. u.boardId = b._id;
  1951. return u;
  1952. });
  1953. data.boards = boards;
  1954. JsonRoutes.sendResult(res, {
  1955. code: 200,
  1956. data,
  1957. });
  1958. } catch (error) {
  1959. JsonRoutes.sendResult(res, {
  1960. code: 200,
  1961. data: error,
  1962. });
  1963. }
  1964. });
  1965. /**
  1966. * @operation get_all_users
  1967. *
  1968. * @summary return all the users
  1969. *
  1970. * @description Only the admin user (the first user) can call the REST API.
  1971. * @return_type [{ _id: string,
  1972. * username: string}]
  1973. */
  1974. JsonRoutes.add('GET', '/api/users', function (req, res) {
  1975. try {
  1976. Authentication.checkUserId(req.userId);
  1977. JsonRoutes.sendResult(res, {
  1978. code: 200,
  1979. data: Meteor.users.find({}).map(function (doc) {
  1980. return {
  1981. _id: doc._id,
  1982. username: doc.username,
  1983. };
  1984. }),
  1985. });
  1986. } catch (error) {
  1987. JsonRoutes.sendResult(res, {
  1988. code: 200,
  1989. data: error,
  1990. });
  1991. }
  1992. });
  1993. /**
  1994. * @operation get_user
  1995. *
  1996. * @summary get a given user
  1997. *
  1998. * @description Only the admin user (the first user) can call the REST API.
  1999. *
  2000. * @param {string} userId the user ID or username
  2001. * @return_type Users
  2002. */
  2003. JsonRoutes.add('GET', '/api/users/:userId', function (req, res) {
  2004. try {
  2005. Authentication.checkUserId(req.userId);
  2006. let id = req.params.userId;
  2007. let user = Meteor.users.findOne({
  2008. _id: id,
  2009. });
  2010. if (!user) {
  2011. user = Meteor.users.findOne({
  2012. username: id,
  2013. });
  2014. id = user._id;
  2015. }
  2016. // get all boards where the user is member of
  2017. let boards = Boards.find(
  2018. {
  2019. type: 'board',
  2020. 'members.userId': id,
  2021. },
  2022. {
  2023. fields: {
  2024. _id: 1,
  2025. members: 1,
  2026. },
  2027. },
  2028. );
  2029. boards = boards.map((b) => {
  2030. const u = b.members.find((m) => m.userId === id);
  2031. delete u.userId;
  2032. u.boardId = b._id;
  2033. return u;
  2034. });
  2035. user.boards = boards;
  2036. JsonRoutes.sendResult(res, {
  2037. code: 200,
  2038. data: user,
  2039. });
  2040. } catch (error) {
  2041. JsonRoutes.sendResult(res, {
  2042. code: 200,
  2043. data: error,
  2044. });
  2045. }
  2046. });
  2047. /**
  2048. * @operation edit_user
  2049. *
  2050. * @summary edit a given user
  2051. *
  2052. * @description Only the admin user (the first user) can call the REST API.
  2053. *
  2054. * Possible values for *action*:
  2055. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  2056. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  2057. * - `enableLogin`: Enable a user
  2058. *
  2059. * @param {string} userId the user ID
  2060. * @param {string} action the action
  2061. * @return_type {_id: string,
  2062. * title: string}
  2063. */
  2064. JsonRoutes.add('PUT', '/api/users/:userId', function (req, res) {
  2065. try {
  2066. Authentication.checkUserId(req.userId);
  2067. const id = req.params.userId;
  2068. const action = req.body.action;
  2069. let data = Meteor.users.findOne({
  2070. _id: id,
  2071. });
  2072. if (data !== undefined) {
  2073. if (action === 'takeOwnership') {
  2074. data = Boards.find(
  2075. {
  2076. 'members.userId': id,
  2077. 'members.isAdmin': true,
  2078. },
  2079. {
  2080. sort: {
  2081. sort: 1 /* boards default sorting */,
  2082. },
  2083. },
  2084. ).map(function (board) {
  2085. if (board.hasMember(req.userId)) {
  2086. board.removeMember(req.userId);
  2087. }
  2088. board.changeOwnership(id, req.userId);
  2089. return {
  2090. _id: board._id,
  2091. title: board.title,
  2092. };
  2093. });
  2094. } else {
  2095. if (action === 'disableLogin' && id !== req.userId) {
  2096. Users.update(
  2097. {
  2098. _id: id,
  2099. },
  2100. {
  2101. $set: {
  2102. loginDisabled: true,
  2103. 'services.resume.loginTokens': '',
  2104. },
  2105. },
  2106. );
  2107. } else if (action === 'enableLogin') {
  2108. Users.update(
  2109. {
  2110. _id: id,
  2111. },
  2112. {
  2113. $set: {
  2114. loginDisabled: '',
  2115. },
  2116. },
  2117. );
  2118. }
  2119. data = Meteor.users.findOne({
  2120. _id: id,
  2121. });
  2122. }
  2123. }
  2124. JsonRoutes.sendResult(res, {
  2125. code: 200,
  2126. data,
  2127. });
  2128. } catch (error) {
  2129. JsonRoutes.sendResult(res, {
  2130. code: 200,
  2131. data: error,
  2132. });
  2133. }
  2134. });
  2135. /**
  2136. * @operation add_board_member
  2137. * @tag Boards
  2138. *
  2139. * @summary Add New Board Member with Role
  2140. *
  2141. * @description Only the admin user (the first user) can call the REST API.
  2142. *
  2143. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  2144. * to later change the permissions.
  2145. *
  2146. * @param {string} boardId the board ID
  2147. * @param {string} userId the user ID
  2148. * @param {string} action the action (needs to be `add`)
  2149. * @param {boolean} isAdmin is the user an admin of the board
  2150. * @param {boolean} isNoComments disable comments
  2151. * @param {boolean} isCommentOnly only enable comments
  2152. * @param {boolean} isWorker is the user a board worker
  2153. * @return_type {_id: string,
  2154. * title: string}
  2155. */
  2156. JsonRoutes.add(
  2157. 'POST',
  2158. '/api/boards/:boardId/members/:userId/add',
  2159. function (req, res) {
  2160. try {
  2161. Authentication.checkUserId(req.userId);
  2162. const userId = req.params.userId;
  2163. const boardId = req.params.boardId;
  2164. const action = req.body.action;
  2165. const { isAdmin, isNoComments, isCommentOnly, isWorker } = req.body;
  2166. let data = Meteor.users.findOne({
  2167. _id: userId,
  2168. });
  2169. if (data !== undefined) {
  2170. if (action === 'add') {
  2171. data = Boards.find({
  2172. _id: boardId,
  2173. }).map(function (board) {
  2174. if (!board.hasMember(userId)) {
  2175. board.addMember(userId);
  2176. function isTrue(data) {
  2177. return data.toLowerCase() === 'true';
  2178. }
  2179. board.setMemberPermission(
  2180. userId,
  2181. isTrue(isAdmin),
  2182. isTrue(isNoComments),
  2183. isTrue(isCommentOnly),
  2184. isTrue(isWorker),
  2185. userId,
  2186. );
  2187. }
  2188. return {
  2189. _id: board._id,
  2190. title: board.title,
  2191. };
  2192. });
  2193. }
  2194. }
  2195. JsonRoutes.sendResult(res, { code: 200, data });
  2196. } catch (error) {
  2197. JsonRoutes.sendResult(res, {
  2198. code: 200,
  2199. data: error,
  2200. });
  2201. }
  2202. },
  2203. );
  2204. /**
  2205. * @operation remove_board_member
  2206. * @tag Boards
  2207. *
  2208. * @summary Remove Member from Board
  2209. *
  2210. * @description Only the admin user (the first user) can call the REST API.
  2211. *
  2212. * @param {string} boardId the board ID
  2213. * @param {string} userId the user ID
  2214. * @param {string} action the action (needs to be `remove`)
  2215. * @return_type {_id: string,
  2216. * title: string}
  2217. */
  2218. JsonRoutes.add(
  2219. 'POST',
  2220. '/api/boards/:boardId/members/:userId/remove',
  2221. function (req, res) {
  2222. try {
  2223. Authentication.checkUserId(req.userId);
  2224. const userId = req.params.userId;
  2225. const boardId = req.params.boardId;
  2226. const action = req.body.action;
  2227. let data = Meteor.users.findOne({
  2228. _id: userId,
  2229. });
  2230. if (data !== undefined) {
  2231. if (action === 'remove') {
  2232. data = Boards.find({
  2233. _id: boardId,
  2234. }).map(function (board) {
  2235. if (board.hasMember(userId)) {
  2236. board.removeMember(userId);
  2237. }
  2238. return {
  2239. _id: board._id,
  2240. title: board.title,
  2241. };
  2242. });
  2243. }
  2244. }
  2245. JsonRoutes.sendResult(res, { code: 200, data });
  2246. } catch (error) {
  2247. JsonRoutes.sendResult(res, {
  2248. code: 200,
  2249. data: error,
  2250. });
  2251. }
  2252. },
  2253. );
  2254. /**
  2255. * @operation new_user
  2256. *
  2257. * @summary Create a new user
  2258. *
  2259. * @description Only the admin user (the first user) can call the REST API.
  2260. *
  2261. * @param {string} username the new username
  2262. * @param {string} email the email of the new user
  2263. * @param {string} password the password of the new user
  2264. * @return_type {_id: string}
  2265. */
  2266. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  2267. try {
  2268. Authentication.checkUserId(req.userId);
  2269. const id = Accounts.createUser({
  2270. username: req.body.username,
  2271. email: req.body.email,
  2272. password: req.body.password,
  2273. from: 'admin',
  2274. });
  2275. JsonRoutes.sendResult(res, {
  2276. code: 200,
  2277. data: {
  2278. _id: id,
  2279. },
  2280. });
  2281. } catch (error) {
  2282. JsonRoutes.sendResult(res, {
  2283. code: 200,
  2284. data: error,
  2285. });
  2286. }
  2287. });
  2288. /**
  2289. * @operation delete_user
  2290. *
  2291. * @summary Delete a user
  2292. *
  2293. * @description Only the admin user (the first user) can call the REST API.
  2294. *
  2295. * @param {string} userId the ID of the user to delete
  2296. * @return_type {_id: string}
  2297. */
  2298. JsonRoutes.add('DELETE', '/api/users/:userId', function (req, res) {
  2299. try {
  2300. Authentication.checkUserId(req.userId);
  2301. const id = req.params.userId;
  2302. // Delete user is enabled, but is still has bug of leaving empty user avatars
  2303. // to boards: boards members, card members and assignees have
  2304. // empty users. So it would be better to delete user from all boards before
  2305. // deleting user.
  2306. // See:
  2307. // - wekan/client/components/settings/peopleBody.jade deleteButton
  2308. // - wekan/client/components/settings/peopleBody.js deleteButton
  2309. // - wekan/client/components/sidebar/sidebar.js Popup.afterConfirm('removeMember'
  2310. // that does now remove member from board, card members and assignees correctly,
  2311. // but that should be used to remove user from all boards similarly
  2312. // - wekan/models/users.js Delete is not enabled
  2313. Meteor.users.remove({ _id: id });
  2314. JsonRoutes.sendResult(res, {
  2315. code: 200,
  2316. data: {
  2317. _id: id,
  2318. },
  2319. });
  2320. } catch (error) {
  2321. JsonRoutes.sendResult(res, {
  2322. code: 200,
  2323. data: error,
  2324. });
  2325. }
  2326. });
  2327. /**
  2328. * @operation create_user_token
  2329. *
  2330. * @summary Create a user token
  2331. *
  2332. * @description Only the admin user (the first user) can call the REST API.
  2333. *
  2334. * @param {string} userId the ID of the user to create token for.
  2335. * @return_type {_id: string}
  2336. */
  2337. JsonRoutes.add('POST', '/api/createtoken/:userId', function (req, res) {
  2338. try {
  2339. Authentication.checkUserId(req.userId);
  2340. const id = req.params.userId;
  2341. const token = Accounts._generateStampedLoginToken();
  2342. Accounts._insertLoginToken(id, token);
  2343. JsonRoutes.sendResult(res, {
  2344. code: 200,
  2345. data: {
  2346. _id: id,
  2347. authToken: token.token,
  2348. },
  2349. });
  2350. } catch (error) {
  2351. JsonRoutes.sendResult(res, {
  2352. code: 200,
  2353. data: error,
  2354. });
  2355. }
  2356. });
  2357. /**
  2358. * @operation delete_user_token
  2359. *
  2360. * @summary Delete one or all user token.
  2361. *
  2362. * @description Only the admin user (the first user) can call the REST API.
  2363. *
  2364. * @param {string} userId the user ID
  2365. * @param {string} token the user hashedToken
  2366. * @return_type {message: string}
  2367. */
  2368. JsonRoutes.add('POST', '/api/deletetoken', function (req, res) {
  2369. try {
  2370. const { userId, token } = req.body;
  2371. Authentication.checkUserId(req.userId);
  2372. let data = {
  2373. message: 'Expected a userId to be set but received none.',
  2374. };
  2375. if (token && userId) {
  2376. Accounts.destroyToken(userId, token);
  2377. data.message = 'Delete token: [' + token + '] from user: ' + userId;
  2378. } else if (userId) {
  2379. check(userId, String);
  2380. Users.update(
  2381. {
  2382. _id: userId,
  2383. },
  2384. {
  2385. $set: {
  2386. 'services.resume.loginTokens': '',
  2387. },
  2388. },
  2389. );
  2390. data.message = 'Delete all token from user: ' + userId;
  2391. }
  2392. JsonRoutes.sendResult(res, {
  2393. code: 200,
  2394. data,
  2395. });
  2396. } catch (error) {
  2397. JsonRoutes.sendResult(res, {
  2398. code: 200,
  2399. data: error,
  2400. });
  2401. }
  2402. });
  2403. }
  2404. export default Users;