ProjectListController.mjs 26 KB

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