ProjectListController.mjs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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. res.render('project/list-react', {
  461. title: 'your_projects',
  462. usersBestSubscription,
  463. notifications,
  464. notificationsInstitution,
  465. user,
  466. userAffiliations,
  467. userEmails,
  468. userSettings,
  469. reconfirmedViaSAML,
  470. allInReconfirmNotificationPeriods,
  471. survey,
  472. tags,
  473. portalTemplates,
  474. prefetchedProjectsBlob,
  475. showGroupsAndEnterpriseBanner,
  476. groupsAndEnterpriseBannerVariant,
  477. showUSGovBanner,
  478. usGovBannerVariant,
  479. showLATAMBanner,
  480. recommendedCurrency,
  481. showInrGeoBanner,
  482. projectDashboardReact: true, // used in navbar
  483. groupSsoSetupSuccess,
  484. joinedGroupName,
  485. viaDomainCapture,
  486. groupSubscriptionsPendingEnrollment:
  487. groupSubscriptionsPendingEnrollment.map(subscription => ({
  488. groupId: subscription._id,
  489. groupName: subscription.teamName,
  490. })),
  491. hasIndividualPaidSubscription,
  492. userRestrictions: Array.from(req.userRestrictions || []),
  493. customerIoEnabled,
  494. aiBlocked,
  495. hasAiAssist,
  496. lastActive: user.lastActive
  497. ? Math.floor(user.lastActive.getTime() / 1000)
  498. : null,
  499. signUpDate: user.signUpDate
  500. ? Math.floor(user.signUpDate.getTime() / 1000)
  501. : null,
  502. subjectArea,
  503. primaryOccupation,
  504. role,
  505. usedLatex,
  506. inactiveTutorials,
  507. countryCode,
  508. commonsInstitution,
  509. groupRole,
  510. isManagedUser: Boolean(user.enrollment?.managedBy),
  511. })
  512. }
  513. /**
  514. * Load user's projects with pagination, sorting and filters
  515. *
  516. * @param {GetProjectsRequest} req the request
  517. * @param {GetProjectsResponse} res the response
  518. * @returns {Promise<void>}
  519. */
  520. async function getProjectsJson(req, res) {
  521. const { filters, page, sort } = req.body
  522. const userId = SessionManager.getLoggedInUserId(req.session)
  523. const projectsPage = await _getProjects(userId, filters, sort, page)
  524. res.json(projectsPage)
  525. }
  526. /**
  527. * @param {string} userId
  528. * @private
  529. */
  530. async function _checkForOldDebugProjects(userId) {
  531. const exists = await ProjectGetter.promises.existUsersDebugProjectsOlderThan(
  532. userId,
  533. 7
  534. )
  535. if (exists) {
  536. await NotificationsBuilder.promises.oldDebugProjects(userId).create(userId)
  537. }
  538. }
  539. /**
  540. * @param {string} userId
  541. * @param {Filters} filters
  542. * @param {Sort} sort
  543. * @param {Page} page
  544. * @returns {Promise<{totalSize: number, projects: Project[]}>}
  545. * @private
  546. */
  547. async function _getProjects(
  548. userId,
  549. filters = {},
  550. sort = { by: 'lastUpdated', order: 'desc' },
  551. page = { size: 20 }
  552. ) {
  553. /** @type {[AllUsersProjects, MongoTag[]]} */
  554. const results = await Promise.all([
  555. ProjectGetter.promises.findAllUsersProjects(
  556. userId,
  557. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens'
  558. ),
  559. TagsHandler.promises.getAllTags(userId),
  560. ])
  561. const [allProjects, tags] = results
  562. const formattedProjects = _formatProjects(allProjects, userId)
  563. const filteredProjects = _applyFilters(
  564. formattedProjects,
  565. tags,
  566. filters,
  567. userId
  568. )
  569. const pagedProjects = _sortAndPaginate(filteredProjects, sort, page)
  570. const projects = await _injectProjectUsers(pagedProjects)
  571. return {
  572. totalSize: filteredProjects.length,
  573. projects,
  574. }
  575. }
  576. /**
  577. * @param {AllUsersProjects} projects
  578. * @param {string} userId
  579. * @returns {FormattedProject[]}
  580. * @private
  581. */
  582. function _formatProjects(projects, userId) {
  583. const {
  584. owned,
  585. review,
  586. readAndWrite,
  587. readOnly,
  588. tokenReadAndWrite,
  589. tokenReadOnly,
  590. } = projects
  591. const formattedProjects = /** @type {FormattedProject[]} **/ []
  592. for (const project of owned) {
  593. formattedProjects.push(
  594. _formatProjectInfo(project, 'owner', Sources.OWNER, userId)
  595. )
  596. }
  597. // Invite-access
  598. for (const project of readAndWrite) {
  599. formattedProjects.push(
  600. _formatProjectInfo(project, 'readWrite', Sources.INVITE, userId)
  601. )
  602. }
  603. for (const project of review) {
  604. formattedProjects.push(
  605. _formatProjectInfo(project, 'review', Sources.INVITE, userId)
  606. )
  607. }
  608. for (const project of readOnly) {
  609. formattedProjects.push(
  610. _formatProjectInfo(project, 'readOnly', Sources.INVITE, userId)
  611. )
  612. }
  613. // Token-access
  614. // Only add these formattedProjects if they're not already present, this gives us cascading access
  615. // from 'owner' => 'token-read-only'
  616. for (const project of tokenReadAndWrite) {
  617. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  618. formattedProjects.push(
  619. _formatProjectInfo(project, 'readAndWrite', Sources.TOKEN, userId)
  620. )
  621. }
  622. }
  623. for (const project of tokenReadOnly) {
  624. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  625. formattedProjects.push(
  626. _formatProjectInfo(project, 'readOnly', Sources.TOKEN, userId)
  627. )
  628. }
  629. }
  630. return formattedProjects
  631. }
  632. /**
  633. * @param {FormattedProject[]} projects
  634. * @param {MongoTag[]} tags
  635. * @param {Filters} filters
  636. * @param {string} userId
  637. * @returns {FormattedProject[]}
  638. * @private
  639. */
  640. function _applyFilters(projects, tags, filters, userId) {
  641. if (!_hasActiveFilter(filters)) {
  642. return projects
  643. }
  644. return projects.filter(project => _matchesFilters(project, tags, filters))
  645. }
  646. /**
  647. * @param {FormattedProject[]} projects
  648. * @param {Sort} sort
  649. * @param {Page} page
  650. * @returns {FormattedProject[]}
  651. * @private
  652. */
  653. function _sortAndPaginate(projects, sort, page) {
  654. if (
  655. (sort.by && !['lastUpdated', 'title', 'owner'].includes(sort.by)) ||
  656. (sort.order && !['asc', 'desc'].includes(sort.order))
  657. ) {
  658. throw new OError('Invalid sorting criteria', { sort })
  659. }
  660. const sortedProjects = _.orderBy(
  661. projects,
  662. [sort.by || 'lastUpdated'],
  663. [sort.order || 'desc']
  664. )
  665. // TODO handle pagination
  666. return sortedProjects
  667. }
  668. /**
  669. * @param {MongoProject} project
  670. * @param {ProjectAccessLevel} accessLevel
  671. * @param {Source} source
  672. * @param {string} userId
  673. * @returns {FormattedProject}
  674. * @private
  675. */
  676. function _formatProjectInfo(project, accessLevel, source, userId) {
  677. const archived = ProjectHelper.isArchived(project, userId)
  678. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  679. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  680. const readOnlyTokenAccess =
  681. accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN
  682. return {
  683. id: project._id.toString(),
  684. name: project.name,
  685. owner_ref: readOnlyTokenAccess ? null : project.owner_ref,
  686. lastUpdated: project.lastUpdated,
  687. lastUpdatedBy: readOnlyTokenAccess ? null : project.lastUpdatedBy,
  688. accessLevel,
  689. source,
  690. archived,
  691. trashed,
  692. }
  693. }
  694. /**
  695. * @param {FormattedProject[]} projects
  696. * @returns {Promise<Project[]>}
  697. * @private
  698. */
  699. async function _injectProjectUsers(projects) {
  700. const userIds = new Set()
  701. for (const project of projects) {
  702. if (project.owner_ref != null) {
  703. userIds.add(project.owner_ref.toString())
  704. }
  705. if (project.lastUpdatedBy != null) {
  706. userIds.add(project.lastUpdatedBy.toString())
  707. }
  708. }
  709. const projection = {
  710. first_name: 1,
  711. last_name: 1,
  712. email: 1,
  713. }
  714. /** @type {Record<string, UserRef>} */
  715. const users = {}
  716. for (const user of await UserGetter.promises.getUsers(userIds, projection)) {
  717. const userId = user._id.toString()
  718. users[userId] = {
  719. id: userId,
  720. email: user.email,
  721. firstName: user.first_name,
  722. lastName: user.last_name,
  723. }
  724. }
  725. return projects.map(project => ({
  726. id: project.id,
  727. name: project.name,
  728. archived: project.archived,
  729. trashed: project.trashed,
  730. accessLevel: project.accessLevel,
  731. source: project.source,
  732. lastUpdated: project.lastUpdated.toISOString(),
  733. lastUpdatedBy:
  734. project.lastUpdatedBy == null
  735. ? null
  736. : users[project.lastUpdatedBy.toString()] || null,
  737. owner:
  738. project.owner_ref == null
  739. ? undefined
  740. : users[project.owner_ref.toString()],
  741. owner_ref: undefined,
  742. }))
  743. }
  744. /**
  745. * @param {any} project
  746. * @param {MongoTag[]} tags
  747. * @param {Filters} filters
  748. * @private
  749. */
  750. function _matchesFilters(project, tags, filters) {
  751. if (filters.ownedByUser && project.accessLevel !== 'owner') {
  752. return false
  753. }
  754. if (filters.sharedWithUser && project.accessLevel === 'owner') {
  755. return false
  756. }
  757. if (filters.archived && !project.archived) {
  758. return false
  759. }
  760. if (filters.trashed && !project.trashed) {
  761. return false
  762. }
  763. if (
  764. filters.tag &&
  765. !_.find(
  766. tags,
  767. tag =>
  768. filters.tag === tag.name && (tag.project_ids || []).includes(project.id)
  769. )
  770. ) {
  771. return false
  772. }
  773. if (
  774. filters.search?.length &&
  775. project.name.toLowerCase().indexOf(filters.search.toLowerCase()) === -1
  776. ) {
  777. return false
  778. }
  779. return true
  780. }
  781. /**
  782. * @param {Filters} filters
  783. * @returns {boolean}
  784. * @private
  785. */
  786. function _hasActiveFilter(filters) {
  787. return Boolean(
  788. filters.ownedByUser ||
  789. filters.sharedWithUser ||
  790. filters.archived ||
  791. filters.trashed ||
  792. filters.tag === null ||
  793. filters.tag?.length ||
  794. filters.search?.length
  795. )
  796. }
  797. async function _userHasAIAssist(user) {
  798. // Check if the user has AI Assist enabled via Overleaf
  799. if (user.features?.aiErrorAssistant) {
  800. return true
  801. }
  802. // Check if the user has AI Assist enabled via Writefull
  803. const { isPremium: hasAiAssistViaWritefull } =
  804. await UserGetter.promises.getWritefullData(user._id)
  805. if (hasAiAssistViaWritefull) {
  806. return true
  807. }
  808. return false
  809. }
  810. // Determines if user is able to enable AI assist
  811. // based on their permissions and settings
  812. // It does NOT determine if the user has AI Assist enabled
  813. async function _canUseAIAssist(user) {
  814. // Check if the assistant has been manually disabled by the user
  815. // todo: assist clean-up: remove other case once migration finishes
  816. if (
  817. user.aiErrorAssistant?.enabled === false ||
  818. user.aiFeatures?.enabled === false
  819. ) {
  820. return false
  821. }
  822. // Check if the user can use AI features (policy check)
  823. return await PermissionsManager.promises.checkUserPermissions(user, [
  824. 'use-ai',
  825. ])
  826. }
  827. export default {
  828. projectListPage: expressify(projectListPage),
  829. getProjectsJson: expressify(getProjectsJson),
  830. }