ProjectListController.mjs 26 KB

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