ProjectListController.mjs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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 labsProgram 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. } else {
  150. if (!process.env.OVERLEAF_IS_SERVER_PRO) {
  151. // temporary survey for CE: https://github.com/overleaf/internal/issues/19710
  152. survey = {
  153. name: 'ce-survey',
  154. preText: 'Help us improve Overleaf',
  155. linkText: 'by filling out this quick survey',
  156. url: 'https://docs.google.com/forms/d/e/1FAIpQLSdPAS-731yaLOvRM8HW7j6gVeOpcmB_X5A5qwgNJT7Oj09lLA/viewform?usp=sf_link',
  157. }
  158. }
  159. }
  160. const tags = await TagsHandler.promises.getAllTags(userId)
  161. let userEmailsData = { list: [], allInReconfirmNotificationPeriods: [] }
  162. try {
  163. const fullEmails = await UserGetter.promises.getUserFullEmails(userId)
  164. if (!Features.hasFeature('affiliations')) {
  165. userEmailsData.list = fullEmails
  166. } else {
  167. try {
  168. const results = await Modules.promises.hooks.fire(
  169. 'allInReconfirmNotificationPeriodsForUser',
  170. fullEmails
  171. )
  172. const allInReconfirmNotificationPeriods = (results && results[0]) || []
  173. userEmailsData = {
  174. list: fullEmails,
  175. allInReconfirmNotificationPeriods,
  176. }
  177. } catch (error) {
  178. userEmailsData = error
  179. }
  180. }
  181. } catch (error) {
  182. if (!(error instanceof V1ConnectionError)) {
  183. logger.error({ err: error, userId }, 'Failed to get user full emails')
  184. }
  185. }
  186. const userEmails = userEmailsData.list || []
  187. const userAffiliations = userEmails
  188. .filter(emailData => !!emailData.affiliation)
  189. .map(emailData => {
  190. const result = emailData.affiliation
  191. result.email = emailData.email
  192. return result
  193. })
  194. const portalTemplates = _buildPortalTemplatesList(userAffiliations)
  195. const { allInReconfirmNotificationPeriods } = userEmailsData
  196. const notifications =
  197. await NotificationsHandler.promises.getUserNotifications(userId)
  198. for (const notification of notifications) {
  199. notification.html = req.i18n.translate(
  200. notification.templateKey,
  201. notification.messageOpts
  202. )
  203. }
  204. const notificationsInstitution = []
  205. // Institution and group SSO Notifications
  206. let groupSsoSetupSuccess
  207. let reconfirmedViaSAML
  208. if (Features.hasFeature('saml')) {
  209. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  210. const samlSession = req.session.saml
  211. // Notification: SSO Available
  212. const linkedInstitutionIds = []
  213. userEmails.forEach(email => {
  214. if (email.samlProviderId) {
  215. linkedInstitutionIds.push(email.samlProviderId)
  216. }
  217. })
  218. if (Array.isArray(userAffiliations)) {
  219. userAffiliations.forEach(affiliation => {
  220. if (_ssoAvailable(affiliation, req.session, linkedInstitutionIds)) {
  221. notificationsInstitution.push({
  222. email: affiliation.email,
  223. institutionId: affiliation.institution.id,
  224. institutionName: affiliation.institution.name,
  225. templateKey: 'notification_institution_sso_available',
  226. })
  227. }
  228. })
  229. }
  230. if (samlSession) {
  231. // Notification institution SSO: After SSO Linked
  232. if (samlSession.linked) {
  233. notificationsInstitution.push({
  234. email: samlSession.institutionEmail,
  235. institutionName:
  236. samlSession.linked.universityName ||
  237. samlSession.linked.providerName,
  238. templateKey: 'notification_institution_sso_linked',
  239. })
  240. }
  241. // Notification group SSO: After SSO Linked
  242. if (samlSession.linkedGroup) {
  243. groupSsoSetupSuccess = true
  244. }
  245. // Notification institution SSO: After SSO Linked or Logging in
  246. // The requested email does not match primary email returned from
  247. // the institution
  248. if (
  249. samlSession.requestedEmail &&
  250. samlSession.emailNonCanonical &&
  251. !samlSession.error
  252. ) {
  253. notificationsInstitution.push({
  254. institutionEmail: samlSession.emailNonCanonical,
  255. requestedEmail: samlSession.requestedEmail,
  256. templateKey: 'notification_institution_sso_non_canonical',
  257. })
  258. }
  259. // Notification institution SSO: Tried to register, but account already existed
  260. // registerIntercept is set before the institution callback.
  261. // institutionEmail is set after institution callback.
  262. // Check for both in case SSO flow was abandoned
  263. if (
  264. samlSession.registerIntercept &&
  265. samlSession.institutionEmail &&
  266. !samlSession.error
  267. ) {
  268. notificationsInstitution.push({
  269. email: samlSession.institutionEmail,
  270. templateKey: 'notification_institution_sso_already_registered',
  271. })
  272. }
  273. // Notification: When there is a session error
  274. if (samlSession.error) {
  275. notificationsInstitution.push({
  276. templateKey: 'notification_institution_sso_error',
  277. error: samlSession.error,
  278. })
  279. }
  280. }
  281. delete req.session.saml
  282. }
  283. function fakeDelay() {
  284. return new Promise(resolve => {
  285. setTimeout(() => resolve(undefined), 0)
  286. })
  287. }
  288. const prefetchedProjectsBlob = await Promise.race([
  289. projectsBlobPending,
  290. fakeDelay(),
  291. ])
  292. Metrics.inc('project-list-prefetch-projects', 1, {
  293. status: prefetchedProjectsBlob ? 'success' : 'too-slow',
  294. })
  295. // in v2 add notifications for matching university IPs
  296. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  297. try {
  298. await NotificationsBuilder.promises
  299. .ipMatcherAffiliation(user._id)
  300. .create(req.ip)
  301. } catch (err) {
  302. logger.error(
  303. { err },
  304. 'failed to create institutional IP match notification'
  305. )
  306. }
  307. }
  308. const hasPaidAffiliation = userAffiliations.some(
  309. affiliation => affiliation.licence && affiliation.licence !== 'free'
  310. )
  311. const inactiveTutorials = TutorialHandler.getInactiveTutorials(user)
  312. const usGovBannerHooksResponse = await Modules.promises.hooks.fire(
  313. 'getUSGovBanner',
  314. userEmails,
  315. hasPaidAffiliation,
  316. inactiveTutorials.includes('us-gov-banner')
  317. )
  318. const usGovBanner = (usGovBannerHooksResponse &&
  319. usGovBannerHooksResponse[0]) || {
  320. showUSGovBanner: false,
  321. usGovBannerVariant: null,
  322. }
  323. const { showUSGovBanner, usGovBannerVariant } = usGovBanner
  324. const showGroupsAndEnterpriseBanner =
  325. Features.hasFeature('saas') &&
  326. !showUSGovBanner &&
  327. !userIsMemberOfGroupSubscription &&
  328. !hasPaidAffiliation
  329. const groupsAndEnterpriseBannerVariant =
  330. showGroupsAndEnterpriseBanner &&
  331. _.sample(['on-premise', 'FOMO', 'FOMO', 'FOMO'])
  332. let showWritefullPromoBanner = false
  333. if (Features.hasFeature('saas') && !req.session.justRegistered) {
  334. try {
  335. const { variant } = await SplitTestHandler.promises.getAssignment(
  336. req,
  337. res,
  338. 'writefull-promo-banner'
  339. )
  340. showWritefullPromoBanner = variant === 'enabled'
  341. } catch (error) {
  342. logger.warn(
  343. { err: error },
  344. 'failed to get "writefull-promo-banner" split test assignment'
  345. )
  346. }
  347. }
  348. let showInrGeoBanner = false
  349. let showBrlGeoBanner = false
  350. let showLATAMBanner = false
  351. let recommendedCurrency
  352. if (usersBestSubscription?.type === 'free') {
  353. const latamGeoPricingAssignment =
  354. await SplitTestHandler.promises.getAssignment(
  355. req,
  356. res,
  357. 'geo-pricing-latam-v2'
  358. )
  359. const { countryCode, currencyCode } =
  360. await GeoIpLookup.promises.getCurrencyCode(req.ip)
  361. if (countryCode === 'IN') {
  362. showInrGeoBanner = true
  363. }
  364. showBrlGeoBanner = countryCode === 'BR'
  365. showLATAMBanner =
  366. latamGeoPricingAssignment.variant === 'latam' &&
  367. ['MX', 'CO', 'CL', 'PE'].includes(countryCode)
  368. // LATAM Banner needs to know which currency to display
  369. if (showLATAMBanner) {
  370. recommendedCurrency = currencyCode
  371. }
  372. }
  373. let hasIndividualRecurlySubscription = false
  374. try {
  375. const individualSubscription =
  376. await SubscriptionLocator.promises.getUsersSubscription(userId)
  377. hasIndividualRecurlySubscription =
  378. individualSubscription?.groupPlan === false &&
  379. individualSubscription?.recurlyStatus?.state !== 'canceled' &&
  380. individualSubscription?.recurlySubscription_id !== ''
  381. } catch (error) {
  382. logger.error({ err: error }, 'Failed to get individual subscription')
  383. }
  384. try {
  385. await SplitTestHandler.promises.getAssignment(req, res, 'paywall-cta')
  386. } catch (error) {
  387. logger.error(
  388. { err: error },
  389. 'failed to get "paywall-cta" split test assignment'
  390. )
  391. }
  392. // Get the user's assignment for this page's Bootstrap 5 split test, which
  393. // populates splitTestVariants with a value for the split test name and allows
  394. // Pug to read it
  395. await SplitTestHandler.promises.getAssignment(
  396. req,
  397. res,
  398. 'bootstrap-5-project-dashboard'
  399. )
  400. res.render('project/list-react', {
  401. title: 'your_projects',
  402. usersBestSubscription,
  403. notifications,
  404. notificationsInstitution,
  405. user,
  406. userAffiliations,
  407. userEmails,
  408. reconfirmedViaSAML,
  409. allInReconfirmNotificationPeriods,
  410. survey,
  411. tags,
  412. portalTemplates,
  413. prefetchedProjectsBlob,
  414. showGroupsAndEnterpriseBanner,
  415. groupsAndEnterpriseBannerVariant,
  416. showUSGovBanner,
  417. usGovBannerVariant,
  418. showWritefullPromoBanner,
  419. showLATAMBanner,
  420. recommendedCurrency,
  421. showInrGeoBanner,
  422. showBrlGeoBanner,
  423. projectDashboardReact: true, // used in navbar
  424. groupSsoSetupSuccess,
  425. groupSubscriptionsPendingEnrollment:
  426. groupSubscriptionsPendingEnrollment.map(subscription => ({
  427. groupId: subscription._id,
  428. groupName: subscription.teamName,
  429. })),
  430. hasIndividualRecurlySubscription,
  431. userRestrictions: Array.from(req.userRestrictions || []),
  432. })
  433. }
  434. /**
  435. * Load user's projects with pagination, sorting and filters
  436. *
  437. * @param {GetProjectsRequest} req the request
  438. * @param {GetProjectsResponse} res the response
  439. * @returns {Promise<void>}
  440. */
  441. async function getProjectsJson(req, res) {
  442. const { filters, page, sort } = req.body
  443. const userId = SessionManager.getLoggedInUserId(req.session)
  444. const projectsPage = await _getProjects(userId, filters, sort, page)
  445. res.json(projectsPage)
  446. }
  447. /**
  448. * @param {string} userId
  449. * @param {Filters} filters
  450. * @param {Sort} sort
  451. * @param {Page} page
  452. * @returns {Promise<{totalSize: number, projects: ProjectApi[]}>}
  453. * @private
  454. */
  455. async function _getProjects(
  456. userId,
  457. filters = {},
  458. sort = { by: 'lastUpdated', order: 'desc' },
  459. page = { size: 20 }
  460. ) {
  461. const [
  462. /** @type {AllUsersProjects} **/ allProjects,
  463. /** @type {Tag[]} **/ tags,
  464. ] = await Promise.all([
  465. ProjectGetter.promises.findAllUsersProjects(
  466. userId,
  467. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens'
  468. ),
  469. TagsHandler.promises.getAllTags(userId),
  470. ])
  471. const formattedProjects = _formatProjects(allProjects, userId)
  472. const filteredProjects = _applyFilters(
  473. formattedProjects,
  474. tags,
  475. filters,
  476. userId
  477. )
  478. const pagedProjects = _sortAndPaginate(filteredProjects, sort, page)
  479. await _injectProjectUsers(pagedProjects)
  480. return {
  481. totalSize: filteredProjects.length,
  482. projects: pagedProjects,
  483. }
  484. }
  485. /**
  486. * @param {AllUsersProjects} projects
  487. * @param {string} userId
  488. * @returns {Project[]}
  489. * @private
  490. */
  491. function _formatProjects(projects, userId) {
  492. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  493. projects
  494. const formattedProjects = /** @type {Project[]} **/ []
  495. for (const project of owned) {
  496. formattedProjects.push(
  497. _formatProjectInfo(project, 'owner', Sources.OWNER, userId)
  498. )
  499. }
  500. // Invite-access
  501. for (const project of readAndWrite) {
  502. formattedProjects.push(
  503. _formatProjectInfo(project, 'readWrite', Sources.INVITE, userId)
  504. )
  505. }
  506. for (const project of readOnly) {
  507. formattedProjects.push(
  508. _formatProjectInfo(project, 'readOnly', Sources.INVITE, userId)
  509. )
  510. }
  511. // Token-access
  512. // Only add these formattedProjects if they're not already present, this gives us cascading access
  513. // from 'owner' => 'token-read-only'
  514. for (const project of tokenReadAndWrite) {
  515. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  516. formattedProjects.push(
  517. _formatProjectInfo(project, 'readAndWrite', Sources.TOKEN, userId)
  518. )
  519. }
  520. }
  521. for (const project of tokenReadOnly) {
  522. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  523. formattedProjects.push(
  524. _formatProjectInfo(project, 'readOnly', Sources.TOKEN, userId)
  525. )
  526. }
  527. }
  528. return formattedProjects
  529. }
  530. /**
  531. * @param {Project[]} projects
  532. * @param {Tag[]} tags
  533. * @param {Filters} filters
  534. * @param {string} userId
  535. * @returns {Project[]}
  536. * @private
  537. */
  538. function _applyFilters(projects, tags, filters, userId) {
  539. if (!_hasActiveFilter(filters)) {
  540. return projects
  541. }
  542. return projects.filter(project => _matchesFilters(project, tags, filters))
  543. }
  544. /**
  545. * @param {Project[]} projects
  546. * @param {Sort} sort
  547. * @param {Page} page
  548. * @returns {Project[]}
  549. * @private
  550. */
  551. function _sortAndPaginate(projects, sort, page) {
  552. if (
  553. (sort.by && !['lastUpdated', 'title', 'owner'].includes(sort.by)) ||
  554. (sort.order && !['asc', 'desc'].includes(sort.order))
  555. ) {
  556. throw new OError('Invalid sorting criteria', { sort })
  557. }
  558. const sortedProjects = _.orderBy(
  559. projects,
  560. [sort.by || 'lastUpdated'],
  561. [sort.order || 'desc']
  562. )
  563. // TODO handle pagination
  564. return sortedProjects
  565. }
  566. /**
  567. * @param {MongoProject} project
  568. * @param {string} accessLevel
  569. * @param {'owner' | 'invite' | 'token'} source
  570. * @param {string} userId
  571. * @returns {object}
  572. * @private
  573. */
  574. function _formatProjectInfo(project, accessLevel, source, userId) {
  575. const archived = ProjectHelper.isArchived(project, userId)
  576. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  577. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  578. const model = {
  579. id: project._id.toString(),
  580. name: project.name,
  581. owner_ref: project.owner_ref,
  582. lastUpdated: project.lastUpdated,
  583. lastUpdatedBy: project.lastUpdatedBy,
  584. accessLevel,
  585. source,
  586. archived,
  587. trashed,
  588. }
  589. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  590. model.owner_ref = null
  591. model.lastUpdatedBy = null
  592. }
  593. return model
  594. }
  595. /**
  596. * @param {Project[]} projects
  597. * @returns {Promise<void>}
  598. * @private
  599. */
  600. async function _injectProjectUsers(projects) {
  601. const userIds = new Set()
  602. for (const project of projects) {
  603. if (project.owner_ref != null) {
  604. userIds.add(project.owner_ref.toString())
  605. }
  606. if (project.lastUpdatedBy != null) {
  607. userIds.add(project.lastUpdatedBy.toString())
  608. }
  609. }
  610. const projection = {
  611. first_name: 1,
  612. last_name: 1,
  613. email: 1,
  614. }
  615. const users = {}
  616. for (const user of await UserGetter.promises.getUsers(userIds, projection)) {
  617. const userId = user._id.toString()
  618. users[userId] = {
  619. id: userId,
  620. email: user.email,
  621. firstName: user.first_name,
  622. lastName: user.last_name,
  623. }
  624. }
  625. for (const project of projects) {
  626. if (project.owner_ref != null) {
  627. project.owner = users[project.owner_ref.toString()]
  628. }
  629. if (project.lastUpdatedBy != null) {
  630. project.lastUpdatedBy = users[project.lastUpdatedBy.toString()] || null
  631. }
  632. delete project.owner_ref
  633. }
  634. }
  635. /**
  636. * @param {any} project
  637. * @param {Tag[]} tags
  638. * @param {Filters} filters
  639. * @private
  640. */
  641. function _matchesFilters(project, tags, filters) {
  642. if (filters.ownedByUser && project.accessLevel !== 'owner') {
  643. return false
  644. }
  645. if (filters.sharedWithUser && project.accessLevel === 'owner') {
  646. return false
  647. }
  648. if (filters.archived && !project.archived) {
  649. return false
  650. }
  651. if (filters.trashed && !project.trashed) {
  652. return false
  653. }
  654. if (
  655. filters.tag &&
  656. !_.find(
  657. tags,
  658. tag =>
  659. filters.tag === tag.name && (tag.project_ids || []).includes(project.id)
  660. )
  661. ) {
  662. return false
  663. }
  664. if (
  665. filters.search?.length &&
  666. project.name.toLowerCase().indexOf(filters.search.toLowerCase()) === -1
  667. ) {
  668. return false
  669. }
  670. return true
  671. }
  672. /**
  673. * @param {Filters} filters
  674. * @returns {boolean}
  675. * @private
  676. */
  677. function _hasActiveFilter(filters) {
  678. return (
  679. filters.ownedByUser ||
  680. filters.sharedWithUser ||
  681. filters.archived ||
  682. filters.trashed ||
  683. filters.tag === null ||
  684. filters.tag?.length ||
  685. filters.search?.length
  686. )
  687. }
  688. export default {
  689. projectListPage: expressify(projectListPage),
  690. getProjectsJson: expressify(getProjectsJson),
  691. }