ProjectListController.mjs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. // ts-check
  2. import _ from 'lodash'
  3. import Metrics from '@overleaf/metrics'
  4. import Settings from '@overleaf/settings'
  5. import ProjectHelper from './ProjectHelper.js'
  6. import ProjectGetter from './ProjectGetter.js'
  7. import PrivilegeLevels from '../Authorization/PrivilegeLevels.js'
  8. import SessionManager from '../Authentication/SessionManager.js'
  9. import Sources from '../Authorization/Sources.js'
  10. import UserGetter from '../User/UserGetter.js'
  11. import SurveyHandler from '../Survey/SurveyHandler.mjs'
  12. import TagsHandler from '../Tags/TagsHandler.js'
  13. import { expressify } from '@overleaf/promise-utils'
  14. import logger from '@overleaf/logger'
  15. import Features from '../../infrastructure/Features.js'
  16. import SubscriptionViewModelBuilder from '../Subscription/SubscriptionViewModelBuilder.js'
  17. import NotificationsHandler from '../Notifications/NotificationsHandler.js'
  18. import Modules from '../../infrastructure/Modules.js'
  19. import { OError, V1ConnectionError } from '../Errors/Errors.js'
  20. import { User } from '../../models/User.js'
  21. import UserPrimaryEmailCheckHandler from '../User/UserPrimaryEmailCheckHandler.js'
  22. import UserController from '../User/UserController.js'
  23. import LimitationsManager from '../Subscription/LimitationsManager.js'
  24. import NotificationsBuilder from '../Notifications/NotificationsBuilder.js'
  25. import GeoIpLookup from '../../infrastructure/GeoIpLookup.js'
  26. import SplitTestHandler from '../SplitTests/SplitTestHandler.js'
  27. import SplitTestSessionHandler from '../SplitTests/SplitTestSessionHandler.js'
  28. import SubscriptionLocator from '../Subscription/SubscriptionLocator.js'
  29. import TutorialHandler from '../Tutorial/TutorialHandler.js'
  30. /**
  31. * @import { GetProjectsRequest, GetProjectsResponse, AllUsersProjects, MongoProject } from "./types"
  32. * @import { ProjectApi, Filters, Page, Sort } from "../../../../types/project/dashboard/api"
  33. * @import { Tag } from "../Tags/types"
  34. */
  35. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  36. if (!affiliation.institution) return false
  37. // institution.confirmed is for the domain being confirmed, not the email
  38. // Do not show SSO UI for unconfirmed domains
  39. if (!affiliation.institution.confirmed) return false
  40. // Could have multiple emails at the same institution, and if any are
  41. // linked to the institution then do not show notification for others
  42. if (
  43. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  44. ) {
  45. if (affiliation.institution.ssoEnabled) return true
  46. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  47. return false
  48. }
  49. return false
  50. }
  51. const _buildPortalTemplatesList = affiliations => {
  52. if (affiliations == null) {
  53. affiliations = []
  54. }
  55. const portalTemplates = []
  56. const uniqueAffiliations = _.uniqBy(affiliations, 'institution.id')
  57. for (const aff of uniqueAffiliations) {
  58. const hasSlug = aff.portal?.slug
  59. const hasTemplates = aff.portal?.templates_count > 0
  60. if (hasSlug && hasTemplates) {
  61. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  62. const portalTemplateURL = Settings.siteUrl + portalPath + aff.portal?.slug
  63. portalTemplates.push({
  64. name: aff.institution.name,
  65. url: portalTemplateURL,
  66. })
  67. }
  68. }
  69. return portalTemplates
  70. }
  71. function cleanupSession(req) {
  72. // cleanup redirects at the end of the redirect chain
  73. delete req.session.postCheckoutRedirect
  74. delete req.session.postLoginRedirect
  75. delete req.session.postOnboardingRedirect
  76. // cleanup details from register page
  77. delete req.session.sharedProjectData
  78. delete req.session.templateData
  79. }
  80. /**
  81. * @param {import("express").Request} req
  82. * @param {import("express").Response} res
  83. * @param {import("express").NextFunction} next
  84. * @returns {Promise<void>}
  85. */
  86. async function projectListPage(req, res, next) {
  87. cleanupSession(req)
  88. // can have two values:
  89. // - undefined - when there's no "saas" feature or couldn't get subscription data
  90. // - object - the subscription data object
  91. let usersBestSubscription
  92. let survey
  93. let userIsMemberOfGroupSubscription = false
  94. let groupSubscriptionsPendingEnrollment = []
  95. const isSaas = Features.hasFeature('saas')
  96. const userId = SessionManager.getLoggedInUserId(req.session)
  97. const projectsBlobPending = _getProjects(userId).catch(err => {
  98. logger.err({ err, userId }, 'projects listing in background failed')
  99. return undefined
  100. })
  101. const user = await User.findById(
  102. userId,
  103. `email emails features alphaProgram betaProgram lastPrimaryEmailCheck signUpDate${
  104. isSaas ? ' enrollment writefull completedTutorials' : ''
  105. }`
  106. )
  107. // Handle case of deleted user
  108. if (user == null) {
  109. UserController.logout(req, res, next)
  110. return
  111. }
  112. if (isSaas) {
  113. await SplitTestSessionHandler.promises.sessionMaintenance(req, user)
  114. try {
  115. usersBestSubscription =
  116. await SubscriptionViewModelBuilder.promises.getBestSubscription({
  117. _id: userId,
  118. })
  119. } catch (error) {
  120. logger.err(
  121. { err: error, userId },
  122. "Failed to get user's best subscription"
  123. )
  124. }
  125. try {
  126. const { isMember, subscriptions } =
  127. await LimitationsManager.promises.userIsMemberOfGroupSubscription(user)
  128. userIsMemberOfGroupSubscription = isMember
  129. // TODO use helper function
  130. if (!user.enrollment?.managedBy) {
  131. groupSubscriptionsPendingEnrollment = subscriptions.filter(
  132. subscription => subscription.groupPlan && subscription.groupPolicy
  133. )
  134. }
  135. } catch (error) {
  136. logger.error(
  137. { err: error },
  138. 'Failed to check whether user is a member of group subscription'
  139. )
  140. }
  141. try {
  142. survey = await SurveyHandler.promises.getSurvey(userId)
  143. } catch (error) {
  144. logger.err({ err: error, userId }, 'Failed to load the active survey')
  145. }
  146. if (user && UserPrimaryEmailCheckHandler.requiresPrimaryEmailCheck(user)) {
  147. return res.redirect('/user/emails/primary-email-check')
  148. }
  149. }
  150. const tags = await TagsHandler.promises.getAllTags(userId)
  151. let userEmailsData = { list: [], allInReconfirmNotificationPeriods: [] }
  152. try {
  153. const fullEmails = await UserGetter.promises.getUserFullEmails(userId)
  154. if (!Features.hasFeature('affiliations')) {
  155. userEmailsData.list = fullEmails
  156. } else {
  157. try {
  158. const results = await Modules.promises.hooks.fire(
  159. 'allInReconfirmNotificationPeriodsForUser',
  160. fullEmails
  161. )
  162. const allInReconfirmNotificationPeriods = (results && results[0]) || []
  163. userEmailsData = {
  164. list: fullEmails,
  165. allInReconfirmNotificationPeriods,
  166. }
  167. } catch (error) {
  168. userEmailsData = error
  169. }
  170. }
  171. } catch (error) {
  172. if (!(error instanceof V1ConnectionError)) {
  173. logger.error({ err: error, userId }, 'Failed to get user full emails')
  174. }
  175. }
  176. const userEmails = userEmailsData.list || []
  177. const userAffiliations = userEmails
  178. .filter(emailData => !!emailData.affiliation)
  179. .map(emailData => {
  180. const result = emailData.affiliation
  181. result.email = emailData.email
  182. return result
  183. })
  184. const portalTemplates = _buildPortalTemplatesList(userAffiliations)
  185. const { allInReconfirmNotificationPeriods } = userEmailsData
  186. const notifications =
  187. await NotificationsHandler.promises.getUserNotifications(userId)
  188. for (const notification of notifications) {
  189. notification.html = req.i18n.translate(
  190. notification.templateKey,
  191. notification.messageOpts
  192. )
  193. }
  194. const notificationsInstitution = []
  195. // Institution and group SSO Notifications
  196. let groupSsoSetupSuccess
  197. let reconfirmedViaSAML
  198. if (Features.hasFeature('saml')) {
  199. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  200. const samlSession = req.session.saml
  201. // Notification: SSO Available
  202. const linkedInstitutionIds = []
  203. userEmails.forEach(email => {
  204. if (email.samlProviderId) {
  205. linkedInstitutionIds.push(email.samlProviderId)
  206. }
  207. })
  208. if (Array.isArray(userAffiliations)) {
  209. userAffiliations.forEach(affiliation => {
  210. if (_ssoAvailable(affiliation, req.session, linkedInstitutionIds)) {
  211. notificationsInstitution.push({
  212. email: affiliation.email,
  213. institutionId: affiliation.institution.id,
  214. institutionName: affiliation.institution.name,
  215. templateKey: 'notification_institution_sso_available',
  216. })
  217. }
  218. })
  219. }
  220. if (samlSession) {
  221. // Notification institution SSO: After SSO Linked
  222. if (samlSession.linked) {
  223. notificationsInstitution.push({
  224. email: samlSession.institutionEmail,
  225. institutionName:
  226. samlSession.linked.universityName ||
  227. samlSession.linked.providerName,
  228. templateKey: 'notification_institution_sso_linked',
  229. })
  230. }
  231. // Notification group SSO: After SSO Linked
  232. if (samlSession.linkedGroup) {
  233. groupSsoSetupSuccess = true
  234. }
  235. // Notification institution SSO: After SSO Linked or Logging in
  236. // The requested email does not match primary email returned from
  237. // the institution
  238. if (
  239. samlSession.requestedEmail &&
  240. samlSession.emailNonCanonical &&
  241. !samlSession.error
  242. ) {
  243. notificationsInstitution.push({
  244. institutionEmail: samlSession.emailNonCanonical,
  245. requestedEmail: samlSession.requestedEmail,
  246. templateKey: 'notification_institution_sso_non_canonical',
  247. })
  248. }
  249. // Notification institution SSO: Tried to register, but account already existed
  250. // registerIntercept is set before the institution callback.
  251. // institutionEmail is set after institution callback.
  252. // Check for both in case SSO flow was abandoned
  253. if (
  254. samlSession.registerIntercept &&
  255. samlSession.institutionEmail &&
  256. !samlSession.error
  257. ) {
  258. notificationsInstitution.push({
  259. email: samlSession.institutionEmail,
  260. templateKey: 'notification_institution_sso_already_registered',
  261. })
  262. }
  263. // Notification: When there is a session error
  264. if (samlSession.error) {
  265. notificationsInstitution.push({
  266. templateKey: 'notification_institution_sso_error',
  267. error: samlSession.error,
  268. })
  269. }
  270. }
  271. delete req.session.saml
  272. }
  273. function fakeDelay() {
  274. return new Promise(resolve => {
  275. setTimeout(() => resolve(undefined), 0)
  276. })
  277. }
  278. const prefetchedProjectsBlob = await Promise.race([
  279. projectsBlobPending,
  280. fakeDelay(),
  281. ])
  282. Metrics.inc('project-list-prefetch-projects', 1, {
  283. status: prefetchedProjectsBlob ? 'success' : 'too-slow',
  284. })
  285. // in v2 add notifications for matching university IPs
  286. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  287. try {
  288. await NotificationsBuilder.promises
  289. .ipMatcherAffiliation(user._id)
  290. .create(req.ip)
  291. } catch (err) {
  292. logger.error(
  293. { err },
  294. 'failed to create institutional IP match notification'
  295. )
  296. }
  297. }
  298. const hasPaidAffiliation = userAffiliations.some(
  299. affiliation => affiliation.licence && affiliation.licence !== 'free'
  300. )
  301. const inactiveTutorials = TutorialHandler.getInactiveTutorials(user)
  302. const usGovBannerHooksResponse = await Modules.promises.hooks.fire(
  303. 'getUSGovBanner',
  304. userEmails,
  305. hasPaidAffiliation,
  306. inactiveTutorials.includes('us-gov-banner')
  307. )
  308. const usGovBanner = (usGovBannerHooksResponse &&
  309. usGovBannerHooksResponse[0]) || {
  310. showUSGovBanner: false,
  311. usGovBannerVariant: null,
  312. }
  313. const { showUSGovBanner, usGovBannerVariant } = usGovBanner
  314. const showGroupsAndEnterpriseBanner =
  315. Features.hasFeature('saas') &&
  316. !showUSGovBanner &&
  317. !userIsMemberOfGroupSubscription &&
  318. !hasPaidAffiliation
  319. const groupsAndEnterpriseBannerVariant =
  320. showGroupsAndEnterpriseBanner &&
  321. _.sample(['on-premise', 'FOMO', 'FOMO', 'FOMO'])
  322. let showWritefullPromoBanner = false
  323. if (Features.hasFeature('saas') && !req.session.justRegistered) {
  324. try {
  325. const { variant } = await SplitTestHandler.promises.getAssignment(
  326. req,
  327. res,
  328. 'writefull-promo-banner'
  329. )
  330. showWritefullPromoBanner = variant === 'enabled'
  331. } catch (error) {
  332. logger.warn(
  333. { err: error },
  334. 'failed to get "writefull-promo-banner" split test assignment'
  335. )
  336. }
  337. }
  338. let showInrGeoBanner = false
  339. let showBrlGeoBanner = false
  340. let showLATAMBanner = false
  341. let recommendedCurrency
  342. if (
  343. usersBestSubscription?.type === 'free' ||
  344. usersBestSubscription?.type === 'standalone-ai-add-on'
  345. ) {
  346. const { countryCode, currencyCode } =
  347. await GeoIpLookup.promises.getCurrencyCode(req.ip)
  348. if (countryCode === 'IN') {
  349. showInrGeoBanner = true
  350. }
  351. showBrlGeoBanner = countryCode === 'BR'
  352. showLATAMBanner = ['MX', 'CO', 'CL', 'PE'].includes(countryCode)
  353. // LATAM Banner needs to know which currency to display
  354. if (showLATAMBanner) {
  355. recommendedCurrency = currencyCode
  356. }
  357. }
  358. let hasIndividualRecurlySubscription = false
  359. try {
  360. const individualSubscription =
  361. await SubscriptionLocator.promises.getUsersSubscription(userId)
  362. hasIndividualRecurlySubscription =
  363. individualSubscription?.groupPlan === false &&
  364. individualSubscription?.recurlyStatus?.state !== 'canceled' &&
  365. individualSubscription?.recurlySubscription_id !== ''
  366. } catch (error) {
  367. logger.error({ err: error }, 'Failed to get individual subscription')
  368. }
  369. try {
  370. await SplitTestHandler.promises.getAssignment(req, res, 'paywall-cta')
  371. } catch (error) {
  372. logger.error(
  373. { err: error },
  374. 'failed to get "paywall-cta" split test assignment'
  375. )
  376. }
  377. // Get the user's assignment for the DS unified nav split test, which
  378. // populates splitTestVariants with a value for the split test name and allows
  379. // Pug to send it to the browser
  380. await SplitTestHandler.promises.getAssignment(
  381. req,
  382. res,
  383. 'sidebar-navigation-ui-update'
  384. )
  385. res.render('project/list-react', {
  386. title: 'your_projects',
  387. usersBestSubscription,
  388. notifications,
  389. notificationsInstitution,
  390. user,
  391. userAffiliations,
  392. userEmails,
  393. reconfirmedViaSAML,
  394. allInReconfirmNotificationPeriods,
  395. survey,
  396. tags,
  397. portalTemplates,
  398. prefetchedProjectsBlob,
  399. showGroupsAndEnterpriseBanner,
  400. groupsAndEnterpriseBannerVariant,
  401. showUSGovBanner,
  402. usGovBannerVariant,
  403. showWritefullPromoBanner,
  404. showLATAMBanner,
  405. recommendedCurrency,
  406. showInrGeoBanner,
  407. showBrlGeoBanner,
  408. projectDashboardReact: true, // used in navbar
  409. groupSsoSetupSuccess,
  410. groupSubscriptionsPendingEnrollment:
  411. groupSubscriptionsPendingEnrollment.map(subscription => ({
  412. groupId: subscription._id,
  413. groupName: subscription.teamName,
  414. })),
  415. hasIndividualRecurlySubscription,
  416. userRestrictions: Array.from(req.userRestrictions || []),
  417. })
  418. }
  419. /**
  420. * Load user's projects with pagination, sorting and filters
  421. *
  422. * @param {GetProjectsRequest} req the request
  423. * @param {GetProjectsResponse} res the response
  424. * @returns {Promise<void>}
  425. */
  426. async function getProjectsJson(req, res) {
  427. const { filters, page, sort } = req.body
  428. const userId = SessionManager.getLoggedInUserId(req.session)
  429. const projectsPage = await _getProjects(userId, filters, sort, page)
  430. res.json(projectsPage)
  431. }
  432. /**
  433. * @param {string} userId
  434. * @param {Filters} filters
  435. * @param {Sort} sort
  436. * @param {Page} page
  437. * @returns {Promise<{totalSize: number, projects: ProjectApi[]}>}
  438. * @private
  439. */
  440. async function _getProjects(
  441. userId,
  442. filters = {},
  443. sort = { by: 'lastUpdated', order: 'desc' },
  444. page = { size: 20 }
  445. ) {
  446. const [
  447. /** @type {AllUsersProjects} **/ allProjects,
  448. /** @type {Tag[]} **/ tags,
  449. ] = await Promise.all([
  450. ProjectGetter.promises.findAllUsersProjects(
  451. userId,
  452. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens'
  453. ),
  454. TagsHandler.promises.getAllTags(userId),
  455. ])
  456. const formattedProjects = _formatProjects(allProjects, userId)
  457. const filteredProjects = _applyFilters(
  458. formattedProjects,
  459. tags,
  460. filters,
  461. userId
  462. )
  463. const pagedProjects = _sortAndPaginate(filteredProjects, sort, page)
  464. await _injectProjectUsers(pagedProjects)
  465. return {
  466. totalSize: filteredProjects.length,
  467. projects: pagedProjects,
  468. }
  469. }
  470. /**
  471. * @param {AllUsersProjects} projects
  472. * @param {string} userId
  473. * @returns {Project[]}
  474. * @private
  475. */
  476. function _formatProjects(projects, userId) {
  477. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  478. projects
  479. const formattedProjects = /** @type {Project[]} **/ []
  480. for (const project of owned) {
  481. formattedProjects.push(
  482. _formatProjectInfo(project, 'owner', Sources.OWNER, userId)
  483. )
  484. }
  485. // Invite-access
  486. for (const project of readAndWrite) {
  487. formattedProjects.push(
  488. _formatProjectInfo(project, 'readWrite', Sources.INVITE, userId)
  489. )
  490. }
  491. for (const project of readOnly) {
  492. formattedProjects.push(
  493. _formatProjectInfo(project, 'readOnly', Sources.INVITE, userId)
  494. )
  495. }
  496. // Token-access
  497. // Only add these formattedProjects if they're not already present, this gives us cascading access
  498. // from 'owner' => 'token-read-only'
  499. for (const project of tokenReadAndWrite) {
  500. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  501. formattedProjects.push(
  502. _formatProjectInfo(project, 'readAndWrite', Sources.TOKEN, userId)
  503. )
  504. }
  505. }
  506. for (const project of tokenReadOnly) {
  507. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  508. formattedProjects.push(
  509. _formatProjectInfo(project, 'readOnly', Sources.TOKEN, userId)
  510. )
  511. }
  512. }
  513. return formattedProjects
  514. }
  515. /**
  516. * @param {Project[]} projects
  517. * @param {Tag[]} tags
  518. * @param {Filters} filters
  519. * @param {string} userId
  520. * @returns {Project[]}
  521. * @private
  522. */
  523. function _applyFilters(projects, tags, filters, userId) {
  524. if (!_hasActiveFilter(filters)) {
  525. return projects
  526. }
  527. return projects.filter(project => _matchesFilters(project, tags, filters))
  528. }
  529. /**
  530. * @param {Project[]} projects
  531. * @param {Sort} sort
  532. * @param {Page} page
  533. * @returns {Project[]}
  534. * @private
  535. */
  536. function _sortAndPaginate(projects, sort, page) {
  537. if (
  538. (sort.by && !['lastUpdated', 'title', 'owner'].includes(sort.by)) ||
  539. (sort.order && !['asc', 'desc'].includes(sort.order))
  540. ) {
  541. throw new OError('Invalid sorting criteria', { sort })
  542. }
  543. const sortedProjects = _.orderBy(
  544. projects,
  545. [sort.by || 'lastUpdated'],
  546. [sort.order || 'desc']
  547. )
  548. // TODO handle pagination
  549. return sortedProjects
  550. }
  551. /**
  552. * @param {MongoProject} project
  553. * @param {string} accessLevel
  554. * @param {'owner' | 'invite' | 'token'} source
  555. * @param {string} userId
  556. * @returns {object}
  557. * @private
  558. */
  559. function _formatProjectInfo(project, accessLevel, source, userId) {
  560. const archived = ProjectHelper.isArchived(project, userId)
  561. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  562. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  563. const model = {
  564. id: project._id.toString(),
  565. name: project.name,
  566. owner_ref: project.owner_ref,
  567. lastUpdated: project.lastUpdated,
  568. lastUpdatedBy: project.lastUpdatedBy,
  569. accessLevel,
  570. source,
  571. archived,
  572. trashed,
  573. }
  574. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  575. model.owner_ref = null
  576. model.lastUpdatedBy = null
  577. }
  578. return model
  579. }
  580. /**
  581. * @param {Project[]} projects
  582. * @returns {Promise<void>}
  583. * @private
  584. */
  585. async function _injectProjectUsers(projects) {
  586. const userIds = new Set()
  587. for (const project of projects) {
  588. if (project.owner_ref != null) {
  589. userIds.add(project.owner_ref.toString())
  590. }
  591. if (project.lastUpdatedBy != null) {
  592. userIds.add(project.lastUpdatedBy.toString())
  593. }
  594. }
  595. const projection = {
  596. first_name: 1,
  597. last_name: 1,
  598. email: 1,
  599. }
  600. const users = {}
  601. for (const user of await UserGetter.promises.getUsers(userIds, projection)) {
  602. const userId = user._id.toString()
  603. users[userId] = {
  604. id: userId,
  605. email: user.email,
  606. firstName: user.first_name,
  607. lastName: user.last_name,
  608. }
  609. }
  610. for (const project of projects) {
  611. if (project.owner_ref != null) {
  612. project.owner = users[project.owner_ref.toString()]
  613. }
  614. if (project.lastUpdatedBy != null) {
  615. project.lastUpdatedBy = users[project.lastUpdatedBy.toString()] || null
  616. }
  617. delete project.owner_ref
  618. }
  619. }
  620. /**
  621. * @param {any} project
  622. * @param {Tag[]} tags
  623. * @param {Filters} filters
  624. * @private
  625. */
  626. function _matchesFilters(project, tags, filters) {
  627. if (filters.ownedByUser && project.accessLevel !== 'owner') {
  628. return false
  629. }
  630. if (filters.sharedWithUser && project.accessLevel === 'owner') {
  631. return false
  632. }
  633. if (filters.archived && !project.archived) {
  634. return false
  635. }
  636. if (filters.trashed && !project.trashed) {
  637. return false
  638. }
  639. if (
  640. filters.tag &&
  641. !_.find(
  642. tags,
  643. tag =>
  644. filters.tag === tag.name && (tag.project_ids || []).includes(project.id)
  645. )
  646. ) {
  647. return false
  648. }
  649. if (
  650. filters.search?.length &&
  651. project.name.toLowerCase().indexOf(filters.search.toLowerCase()) === -1
  652. ) {
  653. return false
  654. }
  655. return true
  656. }
  657. /**
  658. * @param {Filters} filters
  659. * @returns {boolean}
  660. * @private
  661. */
  662. function _hasActiveFilter(filters) {
  663. return (
  664. filters.ownedByUser ||
  665. filters.sharedWithUser ||
  666. filters.archived ||
  667. filters.trashed ||
  668. filters.tag === null ||
  669. filters.tag?.length ||
  670. filters.search?.length
  671. )
  672. }
  673. export default {
  674. projectListPage: expressify(projectListPage),
  675. getProjectsJson: expressify(getProjectsJson),
  676. }