ProjectListController.mjs 26 KB

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