users.js 67 KB

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