users.js 69 KB

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