ProjectListController.mjs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. // @ts-check
  2. import _ from 'lodash'
  3. import moment from 'moment'
  4. import Metrics from '@overleaf/metrics'
  5. import Settings from '@overleaf/settings'
  6. import ProjectHelper from './ProjectHelper.mjs'
  7. import ProjectGetter from './ProjectGetter.mjs'
  8. import PrivilegeLevels from '../Authorization/PrivilegeLevels.mjs'
  9. import SessionManager from '../Authentication/SessionManager.mjs'
  10. import Sources from '../Authorization/Sources.mjs'
  11. import UserGetter from '../User/UserGetter.mjs'
  12. import SurveyHandler from '../Survey/SurveyHandler.mjs'
  13. import TagsHandler from '../Tags/TagsHandler.mjs'
  14. import { expressify } from '@overleaf/promise-utils'
  15. import logger from '@overleaf/logger'
  16. import Features from '../../infrastructure/Features.mjs'
  17. import SubscriptionViewModelBuilder from '../Subscription/SubscriptionViewModelBuilder.mjs'
  18. import NotificationsHandler from '../Notifications/NotificationsHandler.mjs'
  19. import Modules from '../../infrastructure/Modules.mjs'
  20. import { OError, V1ConnectionError } from '../Errors/Errors.js'
  21. import { User } from '../../models/User.mjs'
  22. import UserPrimaryEmailCheckHandler from '../User/UserPrimaryEmailCheckHandler.mjs'
  23. import UserController from '../User/UserController.mjs'
  24. import NotificationsBuilder from '../Notifications/NotificationsBuilder.mjs'
  25. import GeoIpLookup from '../../infrastructure/GeoIpLookup.mjs'
  26. import SplitTestHandler from '../SplitTests/SplitTestHandler.mjs'
  27. import SplitTestSessionHandler from '../SplitTests/SplitTestSessionHandler.mjs'
  28. import TutorialHandler from '../Tutorial/TutorialHandler.mjs'
  29. import SubscriptionHelper from '../Subscription/SubscriptionHelper.mjs'
  30. import PermissionsManager from '../Authorization/PermissionsManager.mjs'
  31. import AnalyticsManager from '../Analytics/AnalyticsManager.mjs'
  32. import { OnboardingDataCollection } from '../../models/OnboardingDataCollection.mjs'
  33. import UserSettingsHelper from './UserSettingsHelper.mjs'
  34. /**
  35. * @import { GetProjectsRequest, GetProjectsResponse, AllUsersProjects, MongoProject, FormattedProject, MongoTag } from "./types"
  36. * @import { Project, ProjectApi, ProjectAccessLevel, Filters, Page, Sort, UserRef } from "../../../../types/project/dashboard/api"
  37. * @import { Affiliation } from "../../../../types/affiliation"
  38. * @import { Source } from "../Authorization/types"
  39. */
  40. /**
  41. * @param {Affiliation} affiliation
  42. * @param session
  43. * @param linkedInstitutionIds
  44. * @returns {boolean}
  45. * @private
  46. */
  47. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  48. if (!affiliation.institution) return false
  49. // institution.confirmed is for the domain being confirmed, not the email
  50. // Do not show SSO UI for unconfirmed domains
  51. if (!affiliation.institution.confirmed) return false
  52. // If ssoEnabled = true and group.domainCaptureEnabled = true
  53. // then Commons is migrating to group subscription and we do not want to prompt
  54. // linking through Commons SSO
  55. if (affiliation?.group?.domainCaptureEnabled) return false
  56. // Could have multiple emails at the same institution, and if any are
  57. // linked to the institution then do not show notification for others
  58. if (
  59. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  60. ) {
  61. if (affiliation.institution.ssoEnabled) return true
  62. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  63. return false
  64. }
  65. return false
  66. }
  67. /**
  68. * @param {Affiliation[]} affiliations
  69. * @returns {Array<{ name: string, url: string }>}
  70. */
  71. const _buildPortalTemplatesList = affiliations => {
  72. if (affiliations == null) {
  73. affiliations = []
  74. }
  75. const portalTemplates = []
  76. const uniqueAffiliations = _.uniqBy(affiliations, 'institution.id')
  77. for (const aff of uniqueAffiliations) {
  78. const hasSlug = aff.portal?.slug
  79. const hasTemplates = (aff.portal?.templates_count || 0) > 0
  80. if (hasSlug && hasTemplates) {
  81. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  82. const portalTemplateURL = Settings.siteUrl + portalPath + aff.portal?.slug
  83. portalTemplates.push({
  84. name: aff.institution.name,
  85. url: portalTemplateURL,
  86. })
  87. }
  88. }
  89. return portalTemplates
  90. }
  91. function cleanupSession(req) {
  92. // cleanup redirects at the end of the redirect chain
  93. delete req.session.postCheckoutRedirect
  94. delete req.session.postLoginRedirect
  95. delete req.session.postOnboardingRedirect
  96. // cleanup details from register page
  97. delete req.session.sharedProjectData
  98. delete req.session.templateData
  99. }
  100. /**
  101. * @param {import("express").Request} req
  102. * @param {import("express").Response} res
  103. * @param {import("express").NextFunction} next
  104. * @returns {Promise<void>}
  105. */
  106. async function projectListPage(req, res, next) {
  107. cleanupSession(req)
  108. // can have two values:
  109. // - undefined - when there's no "saas" feature or couldn't get subscription data
  110. // - object - the subscription data object
  111. let usersBestSubscription
  112. let usersIndividualSubscription
  113. let usersGroupSubscriptions = []
  114. let usersManagedGroupSubscriptions = []
  115. let survey
  116. let userIsMemberOfGroupSubscription = false
  117. let groupSubscriptionsPendingEnrollment = []
  118. const isSaas = Features.hasFeature('saas')
  119. const userId = SessionManager.getLoggedInUserId(req.session)
  120. if (isSaas) {
  121. const { variant: domainCaptureRedirect } =
  122. await SplitTestHandler.promises.getAssignment(
  123. req,
  124. res,
  125. 'domain-capture-redirect'
  126. )
  127. if (domainCaptureRedirect === 'enabled') {
  128. const groupsWithEmails = (
  129. await Modules.promises.hooks.fire(
  130. 'findDomainCaptureGroupsUserCouldBePartOf',
  131. userId
  132. )
  133. )?.[0]
  134. if (groupsWithEmails && groupsWithEmails.length > 0) {
  135. if (
  136. groupsWithEmails.some(
  137. ({ subscription }) => subscription.managedUsersEnabled
  138. )
  139. ) {
  140. return res.redirect('/domain-capture')
  141. } else {
  142. // TODO show notification or anything else
  143. }
  144. }
  145. }
  146. }
  147. const projectsBlobPending = _getProjects(userId).catch(err => {
  148. logger.err({ err, userId }, 'projects listing in background failed')
  149. return undefined
  150. })
  151. const user = await User.findById(
  152. userId,
  153. `email isAdmin emails features alphaProgram betaProgram lastPrimaryEmailCheck lastActive signUpDate ace refProviders${
  154. isSaas
  155. ? ' enrollment writefull completedTutorials aiFeatures aiErrorAssistant'
  156. : ''
  157. }`
  158. )
  159. // Handle case of deleted user
  160. if (user == null) {
  161. UserController.logout(req, res, next)
  162. return
  163. }
  164. user.refProviders = _.mapValues(user.refProviders, Boolean)
  165. let onboardingDataCollection
  166. let customerIoEnabled = false
  167. let subjectArea
  168. let usedLatex
  169. let primaryOccupation
  170. let role
  171. if (isSaas) {
  172. if (user.isAdmin) await _checkForOldDebugProjects(userId)
  173. await SplitTestSessionHandler.promises.sessionMaintenance(req, user)
  174. try {
  175. ;({
  176. bestSubscription: usersBestSubscription,
  177. individualSubscription: usersIndividualSubscription,
  178. memberGroupSubscriptions: usersGroupSubscriptions,
  179. managedGroupSubscriptions: usersManagedGroupSubscriptions,
  180. } = await SubscriptionViewModelBuilder.promises.getUsersSubscriptionDetails(
  181. { _id: userId }
  182. ))
  183. } catch (error) {
  184. logger.err(
  185. { err: error, userId },
  186. "Failed to get user's best subscription"
  187. )
  188. }
  189. userIsMemberOfGroupSubscription =
  190. usersGroupSubscriptions.length > 0 ||
  191. usersManagedGroupSubscriptions.length > 0
  192. // TODO use helper function
  193. if (!user.enrollment?.managedBy) {
  194. groupSubscriptionsPendingEnrollment = usersGroupSubscriptions.filter(
  195. subscription =>
  196. subscription.groupPlan && subscription.managedUsersEnabled
  197. )
  198. }
  199. try {
  200. survey = await SurveyHandler.promises.getSurvey(userId)
  201. } catch (error) {
  202. logger.err({ err: error, userId }, 'Failed to load the active survey')
  203. }
  204. if (
  205. user &&
  206. UserPrimaryEmailCheckHandler.requiresPrimaryEmailCheck({
  207. email: user.email,
  208. emails: user.emails,
  209. lastPrimaryEmailCheck: user.lastPrimaryEmailCheck,
  210. signUpDate: user.signUpDate,
  211. })
  212. ) {
  213. return res.redirect('/user/emails/primary-email-check')
  214. }
  215. onboardingDataCollection = await OnboardingDataCollection.findById(
  216. userId,
  217. 'subjectArea usedLatex primaryOccupation role'
  218. )
  219. if (onboardingDataCollection) {
  220. subjectArea = onboardingDataCollection.subjectArea
  221. usedLatex = onboardingDataCollection.usedLatex
  222. primaryOccupation = onboardingDataCollection.primaryOccupation
  223. role = onboardingDataCollection.role
  224. }
  225. customerIoEnabled = true
  226. AnalyticsManager.setUserPropertyForUserInBackground(
  227. userId,
  228. 'customer-io-integration',
  229. true
  230. )
  231. }
  232. const tags = await TagsHandler.promises.getAllTags(userId)
  233. /** @type {{ list: any[], allInReconfirmNotificationPeriods?: any[], error?: any }} */
  234. let userEmailsData = {
  235. list: [],
  236. }
  237. try {
  238. const fullEmails = await UserGetter.promises.getUserFullEmails(userId)
  239. if (!Features.hasFeature('affiliations')) {
  240. userEmailsData.list = fullEmails
  241. } else {
  242. try {
  243. const results = await Modules.promises.hooks.fire(
  244. 'allInReconfirmNotificationPeriodsForUser',
  245. fullEmails
  246. )
  247. const allInReconfirmNotificationPeriods = (results && results[0]) || []
  248. userEmailsData = {
  249. list: fullEmails,
  250. allInReconfirmNotificationPeriods,
  251. }
  252. } catch (error) {
  253. userEmailsData.error = error
  254. }
  255. }
  256. } catch (error) {
  257. if (!(error instanceof V1ConnectionError)) {
  258. logger.error({ err: error, userId }, 'Failed to get user full emails')
  259. }
  260. }
  261. const userEmails = userEmailsData.list || []
  262. const userAffiliations = userEmails
  263. .filter(emailData => !!emailData.affiliation)
  264. .map(emailData => {
  265. const result = emailData.affiliation
  266. result.email = emailData.email
  267. return result
  268. })
  269. const commonsInstitution = userAffiliations.find(
  270. affiliation => affiliation.institution?.commonsAccount
  271. )?.institution?.name
  272. const portalTemplates = _buildPortalTemplatesList(userAffiliations)
  273. const { allInReconfirmNotificationPeriods } = userEmailsData
  274. const notifications =
  275. await NotificationsHandler.promises.getUserNotifications(userId)
  276. for (const notification of notifications) {
  277. notification.html = req.i18n.translate(
  278. notification.templateKey,
  279. notification.messageOpts
  280. )
  281. }
  282. const notificationsInstitution = []
  283. // Institution and group SSO Notifications
  284. let groupSsoSetupSuccess
  285. let viaDomainCapture
  286. let joinedGroupName = ''
  287. let reconfirmedViaSAML
  288. if (Features.hasFeature('saml')) {
  289. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  290. const samlSession = req.session.saml
  291. // Notification: SSO Available
  292. const linkedInstitutionIds = []
  293. userEmails.forEach(email => {
  294. if (email.samlProviderId) {
  295. linkedInstitutionIds.push(email.samlProviderId)
  296. }
  297. })
  298. if (Array.isArray(userAffiliations)) {
  299. userAffiliations.forEach(affiliation => {
  300. if (_ssoAvailable(affiliation, req.session, linkedInstitutionIds)) {
  301. notificationsInstitution.push({
  302. email: affiliation.email,
  303. institutionId: affiliation.institution.id,
  304. institutionName: affiliation.institution.name,
  305. templateKey: 'notification_institution_sso_available',
  306. })
  307. }
  308. })
  309. }
  310. if (samlSession) {
  311. // Notification institution SSO: After SSO Linked
  312. if (samlSession.linked) {
  313. let templateKey = 'notification_institution_sso_linked'
  314. if (
  315. samlSession.userCreatedViaDomainCapture &&
  316. samlSession.managedUsersEnabled
  317. ) {
  318. templateKey =
  319. 'notification_account_created_via_group_domain_capture_and_managed_users_enabled'
  320. } else if (samlSession.domainCaptureEnabled) {
  321. templateKey = 'notification_group_sso_linked'
  322. }
  323. notificationsInstitution.push({
  324. email: samlSession.institutionEmail,
  325. institutionName:
  326. samlSession.linked.universityName ||
  327. samlSession.linked.providerName,
  328. templateKey,
  329. })
  330. }
  331. // Notification group SSO: After SSO Linked
  332. if (samlSession.linkedGroup) {
  333. groupSsoSetupSuccess = true
  334. viaDomainCapture = samlSession.domainCaptureJoin
  335. joinedGroupName = samlSession.universityName
  336. }
  337. // Notification institution SSO: After SSO Linked or Logging in
  338. // The requested email does not match primary email returned from
  339. // the institution
  340. if (
  341. samlSession.requestedEmail &&
  342. samlSession.emailNonCanonical &&
  343. !samlSession.error
  344. ) {
  345. notificationsInstitution.push({
  346. institutionEmail: samlSession.emailNonCanonical,
  347. requestedEmail: samlSession.requestedEmail,
  348. templateKey: 'notification_institution_sso_non_canonical',
  349. })
  350. }
  351. // Notification institution SSO: Tried to register, but account already existed
  352. // registerIntercept is set before the institution callback.
  353. // institutionEmail is set after institution callback.
  354. // Check for both in case SSO flow was abandoned
  355. if (
  356. samlSession.registerIntercept &&
  357. samlSession.institutionEmail &&
  358. !samlSession.error
  359. ) {
  360. notificationsInstitution.push({
  361. email: samlSession.institutionEmail,
  362. templateKey: 'notification_institution_sso_already_registered',
  363. })
  364. }
  365. // Notification: When there is a session error
  366. if (samlSession.error) {
  367. notificationsInstitution.push({
  368. templateKey: 'notification_institution_sso_error',
  369. error: samlSession.error,
  370. })
  371. }
  372. }
  373. delete req.session.saml
  374. }
  375. const prefetchedProjectsBlob = await projectsBlobPending
  376. Metrics.inc('project-list-prefetch-projects', 1, {
  377. status: prefetchedProjectsBlob ? 'success' : 'error',
  378. })
  379. // in v2 add notifications for matching university IPs
  380. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  381. try {
  382. await NotificationsBuilder.promises
  383. .ipMatcherAffiliation(user._id.toString())
  384. .create(req.ip)
  385. } catch (err) {
  386. logger.error(
  387. { err },
  388. 'failed to create institutional IP match notification'
  389. )
  390. }
  391. }
  392. const hasPaidAffiliation = userAffiliations.some(
  393. affiliation => affiliation.licence && affiliation.licence !== 'free'
  394. )
  395. const inactiveTutorials = TutorialHandler.getInactiveTutorials(user)
  396. const usGovBannerHooksResponse = await Modules.promises.hooks.fire(
  397. 'getUSGovBanner',
  398. userEmails,
  399. hasPaidAffiliation,
  400. inactiveTutorials
  401. )
  402. const usGovBanner = (usGovBannerHooksResponse &&
  403. usGovBannerHooksResponse[0]) || {
  404. showUSGovBanner: false,
  405. usGovBannerVariant: null,
  406. }
  407. const { showUSGovBanner, usGovBannerVariant } = usGovBanner
  408. const isUser30DaysOld = moment.utc().diff(user.signUpDate, 'days') > 30
  409. const showGroupsAndEnterpriseBanner =
  410. Features.hasFeature('saas') &&
  411. !showUSGovBanner &&
  412. !userIsMemberOfGroupSubscription &&
  413. !hasPaidAffiliation &&
  414. !inactiveTutorials.includes('groups-enterprise-banner-repeat') &&
  415. isUser30DaysOld
  416. const groupsAndEnterpriseBannerVariant =
  417. showGroupsAndEnterpriseBanner &&
  418. _.sample(['on-premise', 'FOMO', 'FOMO', 'FOMO'])
  419. let showInrGeoBanner = false
  420. let showLATAMBanner = false
  421. let recommendedCurrency
  422. const { countryCode, currencyCode } =
  423. await GeoIpLookup.promises.getCurrencyCode(req.ip)
  424. if (
  425. usersBestSubscription?.type === 'free' ||
  426. usersBestSubscription?.type === 'standalone-ai-add-on'
  427. ) {
  428. if (countryCode === 'IN') {
  429. showInrGeoBanner = true
  430. }
  431. showLATAMBanner = ['MX', 'CO', 'CL', 'PE'].includes(countryCode)
  432. // LATAM Banner needs to know which currency to display
  433. if (showLATAMBanner) {
  434. recommendedCurrency = currencyCode
  435. }
  436. }
  437. let hasIndividualPaidSubscription = false
  438. try {
  439. hasIndividualPaidSubscription =
  440. SubscriptionHelper.isIndividualActivePaidSubscription(
  441. usersIndividualSubscription
  442. )
  443. } catch (error) {
  444. logger.error({ err: error }, 'Failed to get individual subscription')
  445. }
  446. const aiBlocked =
  447. Features.hasFeature('saas') && !(await _canUseAIAssist(user))
  448. const hasAiAssist =
  449. Features.hasFeature('saas') && (await _userHasAIAssist(user))
  450. await SplitTestHandler.promises.getAssignment(
  451. req,
  452. res,
  453. 'themed-project-dashboard'
  454. )
  455. const userSettings = await UserSettingsHelper.buildUserSettings(
  456. req,
  457. res,
  458. user
  459. )
  460. const groupRole = userIsMemberOfGroupSubscription
  461. ? usersManagedGroupSubscriptions?.length > 0 ||
  462. usersGroupSubscriptions.some(sub => sub.userIsGroupManager)
  463. ? 'admin'
  464. : 'member'
  465. : undefined
  466. Modules.promises.hooks
  467. .fire('setUserProperties', userId, {
  468. overleafId: userId,
  469. lastActive: user.lastActive
  470. ? Math.floor(user.lastActive.getTime() / 1000)
  471. : null,
  472. signUpDate: user.signUpDate
  473. ? Math.floor(user.signUpDate.getTime() / 1000)
  474. : null,
  475. ...(usersBestSubscription?.type && {
  476. 'best-subscription-type': usersBestSubscription.type,
  477. }),
  478. aiBlocked,
  479. hasAiAssist,
  480. ...(subjectArea && { subjectArea }),
  481. ...(role && { role }),
  482. ...(primaryOccupation && { primaryOccupation }),
  483. ...(usedLatex && { usedLatex }),
  484. ...(countryCode && { country: countryCode }),
  485. ...(commonsInstitution && { commonsInstitution }),
  486. ...(groupRole && { groupRole }),
  487. isManagedUser: Boolean(user.enrollment?.managedBy),
  488. ...(user.email && { email: user.email }),
  489. })
  490. .catch(err => {
  491. logger.error({ err }, 'Failed to set user properties for customer.io')
  492. })
  493. res.render('project/list-react', {
  494. title: 'your_projects',
  495. usersBestSubscription,
  496. notifications,
  497. notificationsInstitution,
  498. user,
  499. userAffiliations,
  500. userEmails,
  501. userSettings,
  502. reconfirmedViaSAML,
  503. allInReconfirmNotificationPeriods,
  504. survey,
  505. tags,
  506. portalTemplates,
  507. prefetchedProjectsBlob,
  508. showGroupsAndEnterpriseBanner,
  509. groupsAndEnterpriseBannerVariant,
  510. showUSGovBanner,
  511. usGovBannerVariant,
  512. showLATAMBanner,
  513. recommendedCurrency,
  514. showInrGeoBanner,
  515. projectDashboardReact: true, // used in navbar
  516. groupSsoSetupSuccess,
  517. joinedGroupName,
  518. viaDomainCapture,
  519. groupSubscriptionsPendingEnrollment:
  520. groupSubscriptionsPendingEnrollment.map(subscription => ({
  521. groupId: subscription._id,
  522. groupName: subscription.teamName,
  523. })),
  524. hasIndividualPaidSubscription,
  525. userRestrictions: Array.from(req.userRestrictions || []),
  526. customerIoEnabled,
  527. inactiveTutorials,
  528. })
  529. }
  530. /**
  531. * Load user's projects with pagination, sorting and filters
  532. *
  533. * @param {GetProjectsRequest} req the request
  534. * @param {GetProjectsResponse} res the response
  535. * @returns {Promise<void>}
  536. */
  537. async function getProjectsJson(req, res) {
  538. const { filters, page, sort } = req.body
  539. const userId = SessionManager.getLoggedInUserId(req.session)
  540. const projectsPage = await _getProjects(userId, filters, sort, page)
  541. res.json(projectsPage)
  542. }
  543. /**
  544. * @param {string} userId
  545. * @private
  546. */
  547. async function _checkForOldDebugProjects(userId) {
  548. const exists = await ProjectGetter.promises.existUsersDebugProjectsOlderThan(
  549. userId,
  550. 7
  551. )
  552. if (exists) {
  553. await NotificationsBuilder.promises.oldDebugProjects(userId).create(userId)
  554. }
  555. }
  556. /**
  557. * @param {string} userId
  558. * @param {Filters} filters
  559. * @param {Sort} sort
  560. * @param {Page} page
  561. * @returns {Promise<{totalSize: number, projects: Project[]}>}
  562. * @private
  563. */
  564. async function _getProjects(
  565. userId,
  566. filters = {},
  567. sort = { by: 'lastUpdated', order: 'desc' },
  568. page = { size: 20 }
  569. ) {
  570. /** @type {[AllUsersProjects, MongoTag[]]} */
  571. const results = await Promise.all([
  572. ProjectGetter.promises.findAllUsersProjects(
  573. userId,
  574. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens'
  575. ),
  576. TagsHandler.promises.getAllTags(userId),
  577. ])
  578. const [allProjects, tags] = results
  579. const formattedProjects = _formatProjects(allProjects, userId)
  580. const filteredProjects = _applyFilters(
  581. formattedProjects,
  582. tags,
  583. filters,
  584. userId
  585. )
  586. const pagedProjects = _sortAndPaginate(filteredProjects, sort, page)
  587. const projects = await _injectProjectUsers(pagedProjects)
  588. return {
  589. totalSize: filteredProjects.length,
  590. projects,
  591. }
  592. }
  593. /**
  594. * @param {AllUsersProjects} projects
  595. * @param {string} userId
  596. * @returns {FormattedProject[]}
  597. * @private
  598. */
  599. function _formatProjects(projects, userId) {
  600. const {
  601. owned,
  602. review,
  603. readAndWrite,
  604. readOnly,
  605. tokenReadAndWrite,
  606. tokenReadOnly,
  607. } = projects
  608. const formattedProjects = /** @type {FormattedProject[]} **/ []
  609. for (const project of owned) {
  610. formattedProjects.push(
  611. _formatProjectInfo(project, 'owner', Sources.OWNER, userId)
  612. )
  613. }
  614. // Invite-access
  615. for (const project of readAndWrite) {
  616. formattedProjects.push(
  617. _formatProjectInfo(project, 'readWrite', Sources.INVITE, userId)
  618. )
  619. }
  620. for (const project of review) {
  621. formattedProjects.push(
  622. _formatProjectInfo(project, 'review', Sources.INVITE, userId)
  623. )
  624. }
  625. for (const project of readOnly) {
  626. formattedProjects.push(
  627. _formatProjectInfo(project, 'readOnly', Sources.INVITE, userId)
  628. )
  629. }
  630. // Token-access
  631. // Only add these formattedProjects if they're not already present, this gives us cascading access
  632. // from 'owner' => 'token-read-only'
  633. for (const project of tokenReadAndWrite) {
  634. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  635. formattedProjects.push(
  636. _formatProjectInfo(project, 'readAndWrite', Sources.TOKEN, userId)
  637. )
  638. }
  639. }
  640. for (const project of tokenReadOnly) {
  641. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  642. formattedProjects.push(
  643. _formatProjectInfo(project, 'readOnly', Sources.TOKEN, userId)
  644. )
  645. }
  646. }
  647. return formattedProjects
  648. }
  649. /**
  650. * @param {FormattedProject[]} projects
  651. * @param {MongoTag[]} tags
  652. * @param {Filters} filters
  653. * @param {string} userId
  654. * @returns {FormattedProject[]}
  655. * @private
  656. */
  657. function _applyFilters(projects, tags, filters, userId) {
  658. if (!_hasActiveFilter(filters)) {
  659. return projects
  660. }
  661. return projects.filter(project => _matchesFilters(project, tags, filters))
  662. }
  663. /**
  664. * @param {FormattedProject[]} projects
  665. * @param {Sort} sort
  666. * @param {Page} page
  667. * @returns {FormattedProject[]}
  668. * @private
  669. */
  670. function _sortAndPaginate(projects, sort, page) {
  671. if (
  672. (sort.by && !['lastUpdated', 'title', 'owner'].includes(sort.by)) ||
  673. (sort.order && !['asc', 'desc'].includes(sort.order))
  674. ) {
  675. throw new OError('Invalid sorting criteria', { sort })
  676. }
  677. const sortedProjects = _.orderBy(
  678. projects,
  679. [sort.by || 'lastUpdated'],
  680. [sort.order || 'desc']
  681. )
  682. // TODO handle pagination
  683. return sortedProjects
  684. }
  685. /**
  686. * @param {MongoProject} project
  687. * @param {ProjectAccessLevel} accessLevel
  688. * @param {Source} source
  689. * @param {string} userId
  690. * @returns {FormattedProject}
  691. * @private
  692. */
  693. function _formatProjectInfo(project, accessLevel, source, userId) {
  694. const archived = ProjectHelper.isArchived(project, userId)
  695. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  696. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  697. const readOnlyTokenAccess =
  698. accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN
  699. return {
  700. id: project._id.toString(),
  701. name: project.name,
  702. owner_ref: readOnlyTokenAccess ? null : project.owner_ref,
  703. lastUpdated: project.lastUpdated,
  704. lastUpdatedBy: readOnlyTokenAccess ? null : project.lastUpdatedBy,
  705. accessLevel,
  706. source,
  707. archived,
  708. trashed,
  709. }
  710. }
  711. /**
  712. * @param {FormattedProject[]} projects
  713. * @returns {Promise<Project[]>}
  714. * @private
  715. */
  716. async function _injectProjectUsers(projects) {
  717. const userIds = new Set()
  718. for (const project of projects) {
  719. if (project.owner_ref != null) {
  720. userIds.add(project.owner_ref.toString())
  721. }
  722. if (project.lastUpdatedBy != null) {
  723. userIds.add(project.lastUpdatedBy.toString())
  724. }
  725. }
  726. const projection = {
  727. first_name: 1,
  728. last_name: 1,
  729. email: 1,
  730. }
  731. /** @type {Record<string, UserRef>} */
  732. const users = {}
  733. for (const user of await UserGetter.promises.getUsers(userIds, projection)) {
  734. const userId = user._id.toString()
  735. users[userId] = {
  736. id: userId,
  737. email: user.email,
  738. firstName: user.first_name,
  739. lastName: user.last_name,
  740. }
  741. }
  742. return projects.map(project => ({
  743. id: project.id,
  744. name: project.name,
  745. archived: project.archived,
  746. trashed: project.trashed,
  747. accessLevel: project.accessLevel,
  748. source: project.source,
  749. lastUpdated: project.lastUpdated.toISOString(),
  750. lastUpdatedBy:
  751. project.lastUpdatedBy == null
  752. ? null
  753. : users[project.lastUpdatedBy.toString()] || null,
  754. owner:
  755. project.owner_ref == null
  756. ? undefined
  757. : users[project.owner_ref.toString()],
  758. owner_ref: undefined,
  759. }))
  760. }
  761. /**
  762. * @param {any} project
  763. * @param {MongoTag[]} tags
  764. * @param {Filters} filters
  765. * @private
  766. */
  767. function _matchesFilters(project, tags, filters) {
  768. if (filters.ownedByUser && project.accessLevel !== 'owner') {
  769. return false
  770. }
  771. if (filters.sharedWithUser && project.accessLevel === 'owner') {
  772. return false
  773. }
  774. if (filters.archived && !project.archived) {
  775. return false
  776. }
  777. if (filters.trashed && !project.trashed) {
  778. return false
  779. }
  780. if (
  781. filters.tag &&
  782. !_.find(
  783. tags,
  784. tag =>
  785. filters.tag === tag.name && (tag.project_ids || []).includes(project.id)
  786. )
  787. ) {
  788. return false
  789. }
  790. if (
  791. filters.search?.length &&
  792. project.name.toLowerCase().indexOf(filters.search.toLowerCase()) === -1
  793. ) {
  794. return false
  795. }
  796. return true
  797. }
  798. /**
  799. * @param {Filters} filters
  800. * @returns {boolean}
  801. * @private
  802. */
  803. function _hasActiveFilter(filters) {
  804. return Boolean(
  805. filters.ownedByUser ||
  806. filters.sharedWithUser ||
  807. filters.archived ||
  808. filters.trashed ||
  809. filters.tag === null ||
  810. filters.tag?.length ||
  811. filters.search?.length
  812. )
  813. }
  814. // todo: quota clean-up: rename function and vars
  815. async function _userHasAIAssist(user) {
  816. let hasPremiumAiFeatures
  817. const inQuotaSplitTest =
  818. await SplitTestHandler.promises.featureFlagEnabledForUser(
  819. user._id,
  820. 'plans-2026-phase-1'
  821. )
  822. if (inQuotaSplitTest) {
  823. hasPremiumAiFeatures =
  824. user.features?.aiUsageQuota === Settings.aiFeatures.unlimitedQuota
  825. } else {
  826. hasPremiumAiFeatures = user.features?.aiErrorAssistant === true
  827. }
  828. // Check if the user has a non free trial version of our AI features
  829. if (hasPremiumAiFeatures) {
  830. return true
  831. }
  832. // Check if the user has AI Assist enabled via Writefull
  833. const { isPremium: hasAiAssistViaWritefull } =
  834. await UserGetter.promises.getWritefullData(user._id)
  835. if (hasAiAssistViaWritefull) {
  836. return true
  837. }
  838. return false
  839. }
  840. // Determines if user is able to enable AI assist
  841. // based on their permissions and settings
  842. // It does NOT determine if the user has AI Assist enabled
  843. async function _canUseAIAssist(user) {
  844. // Check if the assistant has been manually disabled by the user
  845. // post https://github.com/overleaf/internal/pull/31273 we can rely on user.aiFeatures being populated
  846. if (user.aiFeatures?.enabled === false) {
  847. return false
  848. }
  849. // Check if the user can use AI features (policy check)
  850. return await PermissionsManager.promises.checkUserPermissions(user, [
  851. 'use-ai',
  852. ])
  853. }
  854. export default {
  855. projectListPage: expressify(projectListPage),
  856. getProjectsJson: expressify(getProjectsJson),
  857. }