users.js 67 KB

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