ProjectListController.mjs 27 KB

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