users.js 67 KB

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