UserPagesController.mjs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import UserGetter from './UserGetter.js'
  2. import OError from '@overleaf/o-error'
  3. import UserSessionsManager from './UserSessionsManager.js'
  4. import logger from '@overleaf/logger'
  5. import Settings from '@overleaf/settings'
  6. import AuthenticationController from '../Authentication/AuthenticationController.js'
  7. import SessionManager from '../Authentication/SessionManager.js'
  8. import NewsletterManager from '../Newsletter/NewsletterManager.js'
  9. import SubscriptionLocator from '../Subscription/SubscriptionLocator.js'
  10. import _ from 'lodash'
  11. import { expressify } from '@overleaf/promise-utils'
  12. import Features from '../../infrastructure/Features.js'
  13. import SplitTestHandler from '../SplitTests/SplitTestHandler.js'
  14. import Modules from '../../infrastructure/Modules.js'
  15. async function settingsPage(req, res) {
  16. const userId = SessionManager.getLoggedInUserId(req.session)
  17. const reconfirmationRemoveEmail = req.query.remove
  18. // SSO
  19. const ssoError = req.session.ssoError
  20. if (ssoError) {
  21. delete req.session.ssoError
  22. }
  23. const ssoErrorMessage = req.session.ssoErrorMessage
  24. if (ssoErrorMessage) {
  25. delete req.session.ssoErrorMessage
  26. }
  27. const projectSyncSuccessMessage = req.session.projectSyncSuccessMessage
  28. if (projectSyncSuccessMessage) {
  29. delete req.session.projectSyncSuccessMessage
  30. }
  31. // Institution SSO
  32. let institutionLinked = _.get(req.session, ['saml', 'linked'])
  33. if (institutionLinked) {
  34. // copy object if exists because _.get does not
  35. institutionLinked = Object.assign(
  36. {
  37. hasEntitlement: _.get(req.session, ['saml', 'hasEntitlement']),
  38. },
  39. institutionLinked
  40. )
  41. }
  42. const samlError = _.get(req.session, ['saml', 'error'])
  43. const institutionEmailNonCanonical = _.get(req.session, [
  44. 'saml',
  45. 'emailNonCanonical',
  46. ])
  47. const institutionRequestedEmail = _.get(req.session, [
  48. 'saml',
  49. 'requestedEmail',
  50. ])
  51. const reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  52. delete req.session.saml
  53. let shouldAllowEditingDetails = true
  54. if (Settings.ldap && Settings.ldap.updateUserDetailsOnLogin) {
  55. shouldAllowEditingDetails = false
  56. }
  57. if (Settings.saml && Settings.saml.updateUserDetailsOnLogin) {
  58. shouldAllowEditingDetails = false
  59. }
  60. const oauthProviders = Settings.oauthProviders || {}
  61. const user = await UserGetter.promises.getUser(userId)
  62. if (!user) {
  63. // The user has just deleted their account.
  64. return UserSessionsManager.removeSessionsFromRedis(
  65. { _id: userId },
  66. null,
  67. () => res.redirect('/')
  68. )
  69. }
  70. let personalAccessTokens
  71. try {
  72. const results = await Modules.promises.hooks.fire(
  73. 'listPersonalAccessTokens',
  74. user._id
  75. )
  76. personalAccessTokens = results?.[0] ?? []
  77. } catch (error) {
  78. logger.error(OError.tag(error))
  79. }
  80. let currentManagedUserAdminEmail
  81. try {
  82. currentManagedUserAdminEmail =
  83. await SubscriptionLocator.promises.getAdminEmail(req.managedBy)
  84. } catch (err) {
  85. logger.error({ err }, 'error getting subscription admin email')
  86. }
  87. let memberOfSSOEnabledGroups = []
  88. try {
  89. memberOfSSOEnabledGroups =
  90. (
  91. await Modules.promises.hooks.fire(
  92. 'getUserGroupsSSOEnrollmentStatus',
  93. user._id,
  94. { teamName: 1 },
  95. ['email']
  96. )
  97. )?.[0] || []
  98. memberOfSSOEnabledGroups = memberOfSSOEnabledGroups.map(group => {
  99. return {
  100. groupId: group._id.toString(),
  101. linked: group.linked,
  102. groupName: group.teamName,
  103. adminEmail: group.admin_id?.email,
  104. }
  105. })
  106. } catch (error) {
  107. logger.error(
  108. { err: error },
  109. 'error fetching groups with Group SSO enabled the user may be member of'
  110. )
  111. }
  112. // Get the user's assignment for this page's Bootstrap 5 split test, which
  113. // populates splitTestVariants with a value for the split test name and allows
  114. // Pug to read it
  115. await SplitTestHandler.promises.getAssignment(req, res, 'bootstrap-5')
  116. // Get the users write-and-cite assignment to switch between translation strings
  117. await SplitTestHandler.promises.getAssignment(req, res, 'write-and-cite')
  118. res.render('user/settings', {
  119. title: 'account_settings',
  120. user: {
  121. id: user._id,
  122. isAdmin: user.isAdmin,
  123. email: user.email,
  124. allowedFreeTrial: user.allowedFreeTrial,
  125. first_name: user.first_name,
  126. last_name: user.last_name,
  127. alphaProgram: user.alphaProgram,
  128. betaProgram: user.betaProgram,
  129. labsProgram: user.labsProgram,
  130. features: {
  131. dropbox: user.features.dropbox,
  132. github: user.features.github,
  133. mendeley: user.features.mendeley,
  134. zotero: user.features.zotero,
  135. references: user.features.references,
  136. },
  137. refProviders: {
  138. mendeley: Boolean(user.refProviders?.mendeley),
  139. zotero: Boolean(user.refProviders?.zotero),
  140. },
  141. writefull: {
  142. enabled: Boolean(user.writefull?.enabled),
  143. },
  144. },
  145. hasPassword: !!user.hashedPassword,
  146. shouldAllowEditingDetails,
  147. oauthProviders: UserPagesController._translateProviderDescriptions(
  148. oauthProviders,
  149. req
  150. ),
  151. institutionLinked,
  152. samlError,
  153. institutionEmailNonCanonical:
  154. institutionEmailNonCanonical && institutionRequestedEmail
  155. ? institutionEmailNonCanonical
  156. : undefined,
  157. reconfirmedViaSAML,
  158. reconfirmationRemoveEmail,
  159. samlBeta: req.session.samlBeta,
  160. ssoErrorMessage,
  161. thirdPartyIds: UserPagesController._restructureThirdPartyIds(user),
  162. projectSyncSuccessMessage,
  163. personalAccessTokens,
  164. emailAddressLimit: Settings.emailAddressLimit,
  165. isManagedAccount: !!req.managedBy,
  166. userRestrictions: Array.from(req.userRestrictions || []),
  167. currentManagedUserAdminEmail,
  168. gitBridgeEnabled: Settings.enableGitBridge,
  169. isSaas: Features.hasFeature('saas'),
  170. memberOfSSOEnabledGroups,
  171. })
  172. }
  173. async function accountSuspended(req, res) {
  174. if (SessionManager.isUserLoggedIn(req.session)) {
  175. return res.redirect('/project')
  176. }
  177. res.render('user/accountSuspended', {
  178. title: 'your_account_is_suspended',
  179. })
  180. }
  181. const UserPagesController = {
  182. accountSuspended: expressify(accountSuspended),
  183. registerPage(req, res) {
  184. const sharedProjectData = req.session.sharedProjectData || {}
  185. const newTemplateData = {}
  186. if (req.session.templateData != null) {
  187. newTemplateData.templateName = req.session.templateData.templateName
  188. }
  189. res.render('user/register', {
  190. title: 'register',
  191. sharedProjectData,
  192. newTemplateData,
  193. samlBeta: req.session.samlBeta,
  194. })
  195. },
  196. loginPage(req, res) {
  197. // if user is being sent to /login with explicit redirect (redir=/foo),
  198. // such as being sent from the editor to /login, then set the redirect explicitly
  199. if (
  200. req.query.redir != null &&
  201. AuthenticationController.getRedirectFromSession(req) == null
  202. ) {
  203. AuthenticationController.setRedirectInSession(req, req.query.redir)
  204. }
  205. res.render('user/login', {
  206. title: 'login',
  207. })
  208. },
  209. /**
  210. * Landing page for users who may have received one-time login
  211. * tokens from the read-only maintenance site.
  212. *
  213. * We tell them that Overleaf is back up and that they can login normally.
  214. */
  215. oneTimeLoginPage(req, res, next) {
  216. res.render('user/one_time_login')
  217. },
  218. renderReconfirmAccountPage(req, res) {
  219. const pageData = {
  220. reconfirm_email: req.session.reconfirm_email,
  221. }
  222. // when a user must reconfirm their account
  223. res.render('user/reconfirm', pageData)
  224. },
  225. settingsPage: expressify(settingsPage),
  226. sessionsPage(req, res, next) {
  227. const user = SessionManager.getSessionUser(req.session)
  228. logger.debug({ userId: user._id }, 'loading sessions page')
  229. const currentSession = {
  230. ip_address: user.ip_address,
  231. session_created: user.session_created,
  232. }
  233. UserSessionsManager.getAllUserSessions(
  234. user,
  235. [req.sessionID],
  236. (err, sessions) => {
  237. if (err != null) {
  238. OError.tag(err, 'error getting all user sessions', {
  239. userId: user._id,
  240. })
  241. return next(err)
  242. }
  243. res.render('user/sessions', {
  244. title: 'sessions',
  245. currentSession,
  246. sessions,
  247. })
  248. }
  249. )
  250. },
  251. emailPreferencesPage(req, res, next) {
  252. const userId = SessionManager.getLoggedInUserId(req.session)
  253. UserGetter.getUser(
  254. userId,
  255. { _id: 1, email: 1, first_name: 1, last_name: 1 },
  256. (err, user) => {
  257. if (err != null) {
  258. return next(err)
  259. }
  260. NewsletterManager.subscribed(user, (err, subscribed) => {
  261. if (err != null) {
  262. OError.tag(err, 'error getting newsletter subscription status')
  263. return next(err)
  264. }
  265. res.render('user/email-preferences', {
  266. title: 'newsletter_info_title',
  267. subscribed,
  268. })
  269. })
  270. }
  271. )
  272. },
  273. compromisedPasswordPage(_, res) {
  274. res.render('user/compromised_password')
  275. },
  276. _restructureThirdPartyIds(user) {
  277. // 3rd party identifiers are an array of objects
  278. // this turn them into a single object, which
  279. // makes data easier to use in template
  280. if (
  281. !user.thirdPartyIdentifiers ||
  282. user.thirdPartyIdentifiers.length === 0
  283. ) {
  284. return null
  285. }
  286. return user.thirdPartyIdentifiers.reduce((obj, identifier) => {
  287. obj[identifier.providerId] = identifier.externalUserId
  288. return obj
  289. }, {})
  290. },
  291. _translateProviderDescriptions(providers, req) {
  292. const result = {}
  293. if (providers) {
  294. for (const provider in providers) {
  295. const data = providers[provider]
  296. data.description = req.i18n.translate(
  297. data.descriptionKey,
  298. Object.assign({}, data.descriptionOptions)
  299. )
  300. result[provider] = data
  301. }
  302. }
  303. return result
  304. },
  305. }
  306. export default UserPagesController