users.js 69 KB

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