ProjectListController.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. const _ = require('lodash')
  2. const Metrics = require('@overleaf/metrics')
  3. const Settings = require('@overleaf/settings')
  4. const ProjectHelper = require('./ProjectHelper')
  5. const ProjectGetter = require('./ProjectGetter')
  6. const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
  7. const SessionManager = require('../Authentication/SessionManager')
  8. const Sources = require('../Authorization/Sources')
  9. const UserGetter = require('../User/UserGetter')
  10. const SurveyHandler = require('../Survey/SurveyHandler')
  11. const TagsHandler = require('../Tags/TagsHandler')
  12. const { expressify } = require('../../util/promises')
  13. const logger = require('@overleaf/logger')
  14. const Features = require('../../infrastructure/Features')
  15. const SubscriptionViewModelBuilder = require('../Subscription/SubscriptionViewModelBuilder')
  16. const NotificationsHandler = require('../Notifications/NotificationsHandler')
  17. const Modules = require('../../infrastructure/Modules')
  18. const { OError, V1ConnectionError } = require('../Errors/Errors')
  19. const { User } = require('../../models/User')
  20. const SplitTestHandler = require('../SplitTests/SplitTestHandler')
  21. const UserPrimaryEmailCheckHandler = require('../User/UserPrimaryEmailCheckHandler')
  22. const UserController = require('../User/UserController')
  23. /** @typedef {import("./types").GetProjectsRequest} GetProjectsRequest */
  24. /** @typedef {import("./types").GetProjectsResponse} GetProjectsResponse */
  25. /** @typedef {import("../../../../types/project/dashboard/api").ProjectApi} ProjectApi */
  26. /** @typedef {import("../../../../types/project/dashboard/api").Filters} Filters */
  27. /** @typedef {import("../../../../types/project/dashboard/api").Page} Page */
  28. /** @typedef {import("../../../../types/project/dashboard/api").Sort} Sort */
  29. /** @typedef {import("./types").AllUsersProjects} AllUsersProjects */
  30. /** @typedef {import("./types").MongoProject} MongoProject */
  31. /** @typedef {import("../Tags/types").Tag} Tag */
  32. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  33. if (!affiliation.institution) return false
  34. // institution.confirmed is for the domain being confirmed, not the email
  35. // Do not show SSO UI for unconfirmed domains
  36. if (!affiliation.institution.confirmed) return false
  37. // Could have multiple emails at the same institution, and if any are
  38. // linked to the institution then do not show notification for others
  39. if (
  40. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  41. ) {
  42. if (affiliation.institution.ssoEnabled) return true
  43. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  44. return false
  45. }
  46. return false
  47. }
  48. const _buildPortalTemplatesList = affiliations => {
  49. if (affiliations == null) {
  50. affiliations = []
  51. }
  52. const portalTemplates = []
  53. const uniqueAffiliations = _.uniqBy(affiliations, 'institution.id')
  54. for (const aff of uniqueAffiliations) {
  55. const hasSlug = aff.portal?.slug
  56. const hasTemplates = aff.portal?.templates_count > 0
  57. if (hasSlug && hasTemplates) {
  58. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  59. const portalTemplateURL = Settings.siteUrl + portalPath + aff.portal?.slug
  60. portalTemplates.push({
  61. name: aff.institution.name,
  62. url: portalTemplateURL,
  63. })
  64. }
  65. }
  66. return portalTemplates
  67. }
  68. /**
  69. * @param {import("express").Request} req
  70. * @param {import("express").Response} res
  71. * @param {import("express").NextFunction} next
  72. * @returns {Promise<void>}
  73. */
  74. async function projectListReactPage(req, res, next) {
  75. // can have two values:
  76. // - undefined - when there's no "saas" feature or couldn't get subscription data
  77. // - object - the subscription data object
  78. let usersBestSubscription
  79. let survey
  80. const userId = SessionManager.getLoggedInUserId(req.session)
  81. const projectsBlobPending = _getProjects(userId).catch(err => {
  82. logger.err({ err, userId }, 'projects listing in background failed')
  83. return undefined
  84. })
  85. const user = await User.findById(
  86. userId,
  87. 'email emails features lastPrimaryEmailCheck signUpDate'
  88. )
  89. // Handle case of deleted user
  90. if (user == null) {
  91. UserController.logout(req, res, next)
  92. return
  93. }
  94. if (Features.hasFeature('saas')) {
  95. try {
  96. usersBestSubscription =
  97. await SubscriptionViewModelBuilder.promises.getBestSubscription({
  98. _id: userId,
  99. })
  100. } catch (error) {
  101. logger.err(
  102. { err: error, userId },
  103. "Failed to get user's best subscription"
  104. )
  105. }
  106. try {
  107. survey = await SurveyHandler.promises.getSurvey(userId)
  108. } catch (error) {
  109. logger.err({ err: error, userId }, 'Failed to load the active survey')
  110. }
  111. try {
  112. const assignment = await SplitTestHandler.promises.getAssignment(
  113. req,
  114. res,
  115. 'primary-email-check'
  116. )
  117. const primaryEmailCheckActive = assignment.variant === 'active'
  118. if (
  119. user &&
  120. primaryEmailCheckActive &&
  121. UserPrimaryEmailCheckHandler.requiresPrimaryEmailCheck(user)
  122. ) {
  123. return res.redirect('/user/emails/primary-email-check')
  124. }
  125. } catch (error) {
  126. logger.warn(
  127. { err: error },
  128. 'failed to get "primary-email-check" split test assignment'
  129. )
  130. }
  131. }
  132. const tags = await TagsHandler.promises.getAllTags(userId)
  133. let userEmailsData = { list: [], allInReconfirmNotificationPeriods: [] }
  134. try {
  135. const fullEmails = await UserGetter.promises.getUserFullEmails(userId)
  136. if (!Features.hasFeature('affiliations')) {
  137. userEmailsData.list = fullEmails
  138. } else {
  139. try {
  140. const results = await Modules.promises.hooks.fire(
  141. 'allInReconfirmNotificationPeriodsForUser',
  142. fullEmails
  143. )
  144. const allInReconfirmNotificationPeriods = (results && results[0]) || []
  145. userEmailsData = {
  146. list: fullEmails,
  147. allInReconfirmNotificationPeriods,
  148. }
  149. } catch (error) {
  150. userEmailsData = error
  151. }
  152. }
  153. } catch (error) {
  154. if (!(error instanceof V1ConnectionError)) {
  155. logger.error({ err: error, userId }, 'Failed to get user full emails')
  156. }
  157. }
  158. const userEmails = userEmailsData.list || []
  159. const userAffiliations = userEmails
  160. .filter(emailData => !!emailData.affiliation)
  161. .map(emailData => {
  162. const result = emailData.affiliation
  163. result.email = emailData.email
  164. return result
  165. })
  166. const portalTemplates = _buildPortalTemplatesList(userAffiliations)
  167. const { allInReconfirmNotificationPeriods } = userEmailsData
  168. const notifications =
  169. await NotificationsHandler.promises.getUserNotifications(userId)
  170. for (const notification of notifications) {
  171. notification.html = req.i18n.translate(
  172. notification.templateKey,
  173. notification.messageOpts
  174. )
  175. }
  176. const notificationsInstitution = []
  177. // Institution SSO Notifications
  178. let reconfirmedViaSAML
  179. if (Features.hasFeature('saml')) {
  180. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  181. const samlSession = req.session.saml
  182. // Notification: SSO Available
  183. const linkedInstitutionIds = []
  184. userEmails.forEach(email => {
  185. if (email.samlProviderId) {
  186. linkedInstitutionIds.push(email.samlProviderId)
  187. }
  188. })
  189. if (Array.isArray(userAffiliations)) {
  190. userAffiliations.forEach(affiliation => {
  191. if (_ssoAvailable(affiliation, req.session, linkedInstitutionIds)) {
  192. notificationsInstitution.push({
  193. email: affiliation.email,
  194. institutionId: affiliation.institution.id,
  195. institutionName: affiliation.institution.name,
  196. templateKey: 'notification_institution_sso_available',
  197. })
  198. }
  199. })
  200. }
  201. if (samlSession) {
  202. // Notification: After SSO Linked
  203. if (samlSession.linked) {
  204. notificationsInstitution.push({
  205. email: samlSession.institutionEmail,
  206. institutionName: samlSession.linked.universityName,
  207. templateKey: 'notification_institution_sso_linked',
  208. })
  209. }
  210. // Notification: After SSO Linked or Logging in
  211. // The requested email does not match primary email returned from
  212. // the institution
  213. if (
  214. samlSession.requestedEmail &&
  215. samlSession.emailNonCanonical &&
  216. !samlSession.error
  217. ) {
  218. notificationsInstitution.push({
  219. institutionEmail: samlSession.emailNonCanonical,
  220. requestedEmail: samlSession.requestedEmail,
  221. templateKey: 'notification_institution_sso_non_canonical',
  222. })
  223. }
  224. // Notification: Tried to register, but account already existed
  225. // registerIntercept is set before the institution callback.
  226. // institutionEmail is set after institution callback.
  227. // Check for both in case SSO flow was abandoned
  228. if (
  229. samlSession.registerIntercept &&
  230. samlSession.institutionEmail &&
  231. !samlSession.error
  232. ) {
  233. notificationsInstitution.push({
  234. email: samlSession.institutionEmail,
  235. templateKey: 'notification_institution_sso_already_registered',
  236. })
  237. }
  238. // Notification: When there is a session error
  239. if (samlSession.error) {
  240. notificationsInstitution.push({
  241. templateKey: 'notification_institution_sso_error',
  242. error: samlSession.error,
  243. })
  244. }
  245. }
  246. delete req.session.saml
  247. }
  248. const prefetchedProjectsBlob = await Promise.race([
  249. projectsBlobPending,
  250. Promise.resolve(undefined),
  251. ])
  252. Metrics.inc('project-list-prefetch-projects', 1, {
  253. status: prefetchedProjectsBlob ? 'success' : 'too-slow',
  254. })
  255. res.render('project/list-react', {
  256. title: 'your_projects',
  257. usersBestSubscription,
  258. notifications,
  259. notificationsInstitution,
  260. user,
  261. userAffiliations,
  262. userEmails,
  263. reconfirmedViaSAML,
  264. allInReconfirmNotificationPeriods,
  265. survey,
  266. tags,
  267. portalTemplates,
  268. prefetchedProjectsBlob,
  269. })
  270. }
  271. /**
  272. * Load user's projects with pagination, sorting and filters
  273. *
  274. * @param {GetProjectsRequest} req the request
  275. * @param {GetProjectsResponse} res the response
  276. * @returns {Promise<void>}
  277. */
  278. async function getProjectsJson(req, res) {
  279. const { filters, page, sort } = req.body
  280. const userId = SessionManager.getLoggedInUserId(req.session)
  281. const projectsPage = await _getProjects(userId, filters, sort, page)
  282. res.json(projectsPage)
  283. }
  284. /**
  285. * @param {string} userId
  286. * @param {Filters} filters
  287. * @param {Sort} sort
  288. * @param {Page} page
  289. * @returns {Promise<{totalSize: number, projects: ProjectApi[]}>}
  290. * @private
  291. */
  292. async function _getProjects(
  293. userId,
  294. filters = {},
  295. sort = { by: 'lastUpdated', order: 'desc' },
  296. page = { size: 20 }
  297. ) {
  298. const [
  299. /** @type {AllUsersProjects} **/ allProjects,
  300. /** @type {Tag[]} **/ tags,
  301. ] = await Promise.all([
  302. ProjectGetter.promises.findAllUsersProjects(
  303. userId,
  304. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens'
  305. ),
  306. TagsHandler.promises.getAllTags(userId),
  307. ])
  308. const formattedProjects = _formatProjects(allProjects, userId)
  309. const filteredProjects = _applyFilters(
  310. formattedProjects,
  311. tags,
  312. filters,
  313. userId
  314. )
  315. const pagedProjects = _sortAndPaginate(filteredProjects, sort, page)
  316. await _injectProjectUsers(pagedProjects)
  317. return {
  318. totalSize: filteredProjects.length,
  319. projects: pagedProjects,
  320. }
  321. }
  322. /**
  323. * @param {AllUsersProjects} projects
  324. * @param {string} userId
  325. * @returns {Project[]}
  326. * @private
  327. */
  328. function _formatProjects(projects, userId) {
  329. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  330. projects
  331. const formattedProjects = /** @type {Project[]} **/ []
  332. for (const project of owned) {
  333. formattedProjects.push(
  334. _formatProjectInfo(project, 'owner', Sources.OWNER, userId)
  335. )
  336. }
  337. // Invite-access
  338. for (const project of readAndWrite) {
  339. formattedProjects.push(
  340. _formatProjectInfo(project, 'readWrite', Sources.INVITE, userId)
  341. )
  342. }
  343. for (const project of readOnly) {
  344. formattedProjects.push(
  345. _formatProjectInfo(project, 'readOnly', Sources.INVITE, userId)
  346. )
  347. }
  348. // Token-access
  349. // Only add these formattedProjects if they're not already present, this gives us cascading access
  350. // from 'owner' => 'token-read-only'
  351. for (const project of tokenReadAndWrite) {
  352. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  353. formattedProjects.push(
  354. _formatProjectInfo(project, 'readAndWrite', Sources.TOKEN, userId)
  355. )
  356. }
  357. }
  358. for (const project of tokenReadOnly) {
  359. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  360. formattedProjects.push(
  361. _formatProjectInfo(project, 'readOnly', Sources.TOKEN, userId)
  362. )
  363. }
  364. }
  365. return formattedProjects
  366. }
  367. /**
  368. * @param {Project[]} projects
  369. * @param {Tag[]} tags
  370. * @param {Filters} filters
  371. * @param {string} userId
  372. * @returns {Project[]}
  373. * @private
  374. */
  375. function _applyFilters(projects, tags, filters, userId) {
  376. if (!_hasActiveFilter(filters)) {
  377. return projects
  378. }
  379. return projects.filter(project => _matchesFilters(project, tags, filters))
  380. }
  381. /**
  382. * @param {Project[]} projects
  383. * @param {Sort} sort
  384. * @param {Page} page
  385. * @returns {Project[]}
  386. * @private
  387. */
  388. function _sortAndPaginate(projects, sort, page) {
  389. if (
  390. (sort.by && !['lastUpdated', 'title', 'owner'].includes(sort.by)) ||
  391. (sort.order && !['asc', 'desc'].includes(sort.order))
  392. ) {
  393. throw new OError('Invalid sorting criteria', { sort })
  394. }
  395. const sortedProjects = _.orderBy(
  396. projects,
  397. [sort.by || 'lastUpdated'],
  398. [sort.order || 'desc']
  399. )
  400. // TODO handle pagination
  401. return sortedProjects
  402. }
  403. /**
  404. * @param {MongoProject} project
  405. * @param {string} accessLevel
  406. * @param {'owner' | 'invite' | 'token'} source
  407. * @param {string} userId
  408. * @returns {object}
  409. * @private
  410. */
  411. function _formatProjectInfo(project, accessLevel, source, userId) {
  412. const archived = ProjectHelper.isArchived(project, userId)
  413. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  414. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  415. const model = {
  416. id: project._id.toString(),
  417. name: project.name,
  418. owner_ref: project.owner_ref,
  419. lastUpdated: project.lastUpdated,
  420. lastUpdatedBy: project.lastUpdatedBy,
  421. accessLevel,
  422. source,
  423. archived,
  424. trashed,
  425. }
  426. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  427. model.owner_ref = null
  428. model.lastUpdatedBy = null
  429. }
  430. return model
  431. }
  432. /**
  433. * @param {Project[]} projects
  434. * @returns {Promise<void>}
  435. * @private
  436. */
  437. async function _injectProjectUsers(projects) {
  438. const userIds = new Set()
  439. for (const project of projects) {
  440. if (project.owner_ref != null) {
  441. userIds.add(project.owner_ref.toString())
  442. }
  443. if (project.lastUpdatedBy != null) {
  444. userIds.add(project.lastUpdatedBy.toString())
  445. }
  446. }
  447. const projection = {
  448. first_name: 1,
  449. last_name: 1,
  450. email: 1,
  451. }
  452. const users = {}
  453. for (const user of await UserGetter.promises.getUsers(userIds, projection)) {
  454. const userId = user._id.toString()
  455. users[userId] = {
  456. id: userId,
  457. email: user.email,
  458. firstName: user.first_name,
  459. lastName: user.last_name,
  460. }
  461. }
  462. for (const project of projects) {
  463. if (project.owner_ref != null) {
  464. project.owner = users[project.owner_ref.toString()]
  465. }
  466. if (project.lastUpdatedBy != null) {
  467. project.lastUpdatedBy = users[project.lastUpdatedBy.toString()] || null
  468. }
  469. delete project.owner_ref
  470. }
  471. }
  472. /**
  473. * @param {any} project
  474. * @param {Tag[]} tags
  475. * @param {Filters} filters
  476. * @private
  477. */
  478. function _matchesFilters(project, tags, filters) {
  479. if (filters.ownedByUser && project.accessLevel !== 'owner') {
  480. return false
  481. }
  482. if (filters.sharedWithUser && project.accessLevel === 'owner') {
  483. return false
  484. }
  485. if (filters.archived && !project.archived) {
  486. return false
  487. }
  488. if (filters.trashed && !project.trashed) {
  489. return false
  490. }
  491. if (
  492. filters.tag &&
  493. !_.find(
  494. tags,
  495. tag =>
  496. filters.tag === tag.name && (tag.project_ids || []).includes(project.id)
  497. )
  498. ) {
  499. return false
  500. }
  501. if (
  502. filters.search?.length &&
  503. project.name.toLowerCase().indexOf(filters.search.toLowerCase()) === -1
  504. ) {
  505. return false
  506. }
  507. return true
  508. }
  509. /**
  510. * @param {Filters} filters
  511. * @returns {boolean}
  512. * @private
  513. */
  514. function _hasActiveFilter(filters) {
  515. return (
  516. filters.ownedByUser ||
  517. filters.sharedWithUser ||
  518. filters.archived ||
  519. filters.trashed ||
  520. filters.tag === null ||
  521. filters.tag?.length ||
  522. filters.search?.length
  523. )
  524. }
  525. module.exports = {
  526. projectListReactPage: expressify(projectListReactPage),
  527. getProjectsJson: expressify(getProjectsJson),
  528. }