ProjectListController.js 22 KB

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