ProjectListController.mjs 26 KB

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