UserController.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. import UserHandler from './UserHandler.mjs'
  2. import UserDeleter from './UserDeleter.mjs'
  3. import UserGetter from './UserGetter.mjs'
  4. import { User } from '../../models/User.mjs'
  5. import NewsletterManager from '../Newsletter/NewsletterManager.mjs'
  6. import logger from '@overleaf/logger'
  7. import metrics from '@overleaf/metrics'
  8. import AuthenticationManager from '../Authentication/AuthenticationManager.mjs'
  9. import SessionManager from '../Authentication/SessionManager.mjs'
  10. import Features from '../../infrastructure/Features.mjs'
  11. import { z, parseReq } from '../../infrastructure/Validation.mjs'
  12. import UserAuditLogHandler from './UserAuditLogHandler.mjs'
  13. import UserSessionsManager from './UserSessionsManager.mjs'
  14. import UserUpdater from './UserUpdater.mjs'
  15. import Errors from '../Errors/Errors.js'
  16. import HttpErrorHandler from '../Errors/HttpErrorHandler.mjs'
  17. import OError from '@overleaf/o-error'
  18. import EmailHandler from '../Email/EmailHandler.mjs'
  19. import UrlHelper from '../Helpers/UrlHelper.mjs'
  20. import { promisify } from 'node:util'
  21. import { expressify } from '@overleaf/promise-utils'
  22. import { acceptsJson } from '../../infrastructure/RequestContentTypeDetection.mjs'
  23. import Modules from '../../infrastructure/Modules.mjs'
  24. import OneTimeTokenHandler from '../Security/OneTimeTokenHandler.mjs'
  25. async function _sendSecurityAlertClearedSessions(user) {
  26. const emailOptions = {
  27. to: user.email,
  28. actionDescribed: `active sessions were cleared on your account ${user.email}`,
  29. action: 'active sessions cleared',
  30. }
  31. try {
  32. await EmailHandler.promises.sendEmail('securityAlert', emailOptions)
  33. } catch (error) {
  34. // log error when sending security alert email but do not pass back
  35. logger.error(
  36. { error, userId: user._id },
  37. 'could not send security alert email when sessions cleared'
  38. )
  39. }
  40. }
  41. function _sendSecurityAlertPasswordChanged(user) {
  42. const emailOptions = {
  43. to: user.email,
  44. actionDescribed: `your password has been changed on your account ${user.email}`,
  45. action: 'password changed',
  46. }
  47. EmailHandler.promises
  48. .sendEmail('securityAlert', emailOptions)
  49. .catch(error => {
  50. // log error when sending security alert email but do not pass back
  51. logger.error(
  52. { error, userId: user._id },
  53. 'could not send security alert email when password changed'
  54. )
  55. })
  56. }
  57. async function _ensureAffiliation(userId, emailData) {
  58. if (emailData.samlProviderId) {
  59. await UserUpdater.promises.confirmEmail(userId, emailData.email)
  60. } else {
  61. await UserUpdater.promises.addAffiliationForNewUser(userId, emailData.email)
  62. }
  63. }
  64. async function changePassword(req, res, next) {
  65. metrics.inc('user.password-change')
  66. const userId = SessionManager.getLoggedInUserId(req.session)
  67. const { user } = await AuthenticationManager.promises.authenticate(
  68. { _id: userId },
  69. req.body.currentPassword,
  70. null,
  71. { enforceHIBPCheck: false }
  72. )
  73. if (!user) {
  74. return HttpErrorHandler.badRequest(
  75. req,
  76. res,
  77. req.i18n.translate('password_change_old_password_wrong')
  78. )
  79. }
  80. if (req.body.newPassword1 !== req.body.newPassword2) {
  81. return HttpErrorHandler.badRequest(
  82. req,
  83. res,
  84. req.i18n.translate('password_change_passwords_do_not_match')
  85. )
  86. }
  87. try {
  88. await AuthenticationManager.promises.setUserPassword(
  89. user,
  90. req.body.newPassword1
  91. )
  92. } catch (error) {
  93. if (error.name === 'InvalidPasswordError') {
  94. const message = AuthenticationManager.getMessageForInvalidPasswordError(
  95. error,
  96. req
  97. )
  98. return res.status(400).json({ message })
  99. } else if (error.name === 'PasswordMustBeDifferentError') {
  100. return HttpErrorHandler.badRequest(
  101. req,
  102. res,
  103. req.i18n.translate('password_change_password_must_be_different')
  104. )
  105. } else if (error.name === 'PasswordReusedError') {
  106. return res.status(400).json({
  107. message: {
  108. key: 'password-must-be-strong',
  109. },
  110. })
  111. } else {
  112. throw error
  113. }
  114. }
  115. await UserAuditLogHandler.promises.addEntry(
  116. user._id,
  117. 'update-password',
  118. user._id,
  119. req.ip
  120. )
  121. // no need to wait, errors are logged and not passed back
  122. _sendSecurityAlertPasswordChanged(user)
  123. await UserSessionsManager.promises.removeSessionsFromRedis(
  124. user,
  125. req.sessionID // remove all sessions except the current session
  126. )
  127. await OneTimeTokenHandler.promises.expireAllTokensForUser(
  128. userId.toString(),
  129. 'password'
  130. )
  131. return res.json({
  132. message: {
  133. type: 'success',
  134. email: user.email,
  135. text: req.i18n.translate('password_change_successful'),
  136. },
  137. })
  138. }
  139. async function clearSessions(req, res, next) {
  140. metrics.inc('user.clear-sessions')
  141. const userId = SessionManager.getLoggedInUserId(req.session)
  142. const user = await UserGetter.promises.getUser(userId, { email: 1 })
  143. const sessions = await UserSessionsManager.promises.getAllUserSessions(user, [
  144. req.sessionID,
  145. ])
  146. await UserAuditLogHandler.promises.addEntry(
  147. user._id,
  148. 'clear-sessions',
  149. user._id,
  150. req.ip,
  151. { sessions }
  152. )
  153. await UserSessionsManager.promises.removeSessionsFromRedis(
  154. user,
  155. req.sessionID // remove all sessions except the current session
  156. )
  157. await _sendSecurityAlertClearedSessions(user)
  158. res.sendStatus(201)
  159. }
  160. async function ensureAffiliation(user) {
  161. if (!Features.hasFeature('affiliations')) {
  162. return
  163. }
  164. const flaggedEmails = user.emails.filter(email => email.affiliationUnchecked)
  165. if (flaggedEmails.length === 0) {
  166. return
  167. }
  168. if (flaggedEmails.length > 1) {
  169. logger.error(
  170. { userId: user._id },
  171. `Unexpected number of flagged emails: ${flaggedEmails.length}`
  172. )
  173. }
  174. await _ensureAffiliation(user._id, flaggedEmails[0])
  175. }
  176. async function ensureAffiliationMiddleware(req, res, next) {
  177. let user
  178. if (!Features.hasFeature('affiliations') || !req.query.ensureAffiliation) {
  179. return next()
  180. }
  181. const userId = SessionManager.getLoggedInUserId(req.session)
  182. try {
  183. user = await UserGetter.promises.getUser(userId)
  184. } catch (error) {
  185. throw new Errors.UserNotFoundError({ info: { userId } })
  186. }
  187. // if the user does not have permission to add an affiliation, we skip this middleware
  188. try {
  189. req.assertPermission('add-affiliation')
  190. } catch (error) {
  191. if (error instanceof Errors.ForbiddenError) {
  192. return next()
  193. }
  194. }
  195. await ensureAffiliation(user)
  196. return next()
  197. }
  198. async function tryDeleteUser(req, res, next) {
  199. const userId = SessionManager.getLoggedInUserId(req.session)
  200. const { password } = req.body
  201. req.logger.addFields({ userId })
  202. logger.debug({ userId }, 'trying to delete user account')
  203. if (password == null || password === '') {
  204. logger.err({ userId }, 'no password supplied for attempt to delete account')
  205. return res.sendStatus(403)
  206. }
  207. let user
  208. try {
  209. user = (
  210. await AuthenticationManager.promises.authenticate(
  211. { _id: userId },
  212. password,
  213. null,
  214. { enforceHIBPCheck: false }
  215. )
  216. ).user
  217. } catch (err) {
  218. throw OError.tag(
  219. err,
  220. 'error authenticating during attempt to delete account',
  221. { userId }
  222. )
  223. }
  224. if (!user) {
  225. logger.err({ userId }, 'auth failed during attempt to delete account')
  226. return res.sendStatus(403)
  227. }
  228. try {
  229. await UserDeleter.promises.deleteUser(userId, {
  230. deleterUser: user,
  231. ipAddress: req.ip,
  232. })
  233. } catch (err) {
  234. const errorData = {
  235. message: 'error while deleting user account',
  236. info: { userId },
  237. }
  238. if (err instanceof Errors.SubscriptionAdminDeletionError) {
  239. // set info.public.error for JSON response so frontend can display
  240. // a specific message
  241. errorData.info.public = {
  242. error: 'SubscriptionAdminDeletionError',
  243. }
  244. const error = OError.tag(err, errorData.message, errorData.info)
  245. logger.warn({ error, req }, error.message)
  246. return HttpErrorHandler.unprocessableEntity(
  247. req,
  248. res,
  249. errorData.message,
  250. errorData.info.public
  251. )
  252. } else {
  253. throw OError.tag(err, errorData.message, errorData.info)
  254. }
  255. }
  256. await Modules.promises.hooks.fire('tryDeleteV1Account', user)
  257. const sessionId = req.sessionID
  258. if (typeof req.logout === 'function') {
  259. const logout = promisify(req.logout)
  260. await logout()
  261. }
  262. const destroySession = promisify(req.session.destroy.bind(req.session))
  263. await destroySession()
  264. UserSessionsManager.promises.untrackSession(user, sessionId).catch(err => {
  265. logger.warn({ err, userId: user._id }, 'failed to untrack session')
  266. })
  267. res.sendStatus(200)
  268. }
  269. async function subscribe(req, res, next) {
  270. const userId = SessionManager.getLoggedInUserId(req.session)
  271. req.logger.addFields({ userId })
  272. const user = await UserGetter.promises.getUser(userId, {
  273. _id: 1,
  274. email: 1,
  275. first_name: 1,
  276. last_name: 1,
  277. })
  278. await NewsletterManager.promises.subscribe(user)
  279. res.json({
  280. message: req.i18n.translate('thanks_settings_updated'),
  281. })
  282. }
  283. async function unsubscribe(req, res, next) {
  284. const userId = SessionManager.getLoggedInUserId(req.session)
  285. req.logger.addFields({ userId })
  286. const user = await UserGetter.promises.getUser(userId, {
  287. _id: 1,
  288. email: 1,
  289. first_name: 1,
  290. last_name: 1,
  291. })
  292. await NewsletterManager.promises.unsubscribe(user)
  293. await Modules.promises.hooks.fire('newsletterUnsubscribed', user)
  294. res.json({
  295. message: req.i18n.translate('thanks_settings_updated'),
  296. })
  297. }
  298. const updateUserSettingsSchema = z.object({
  299. body: z
  300. .object({
  301. first_name: z.string().max(255).nullish(),
  302. last_name: z.string().max(255).nullish(),
  303. })
  304. .passthrough(),
  305. // TODO: complete the schema and remove the passthrough
  306. })
  307. async function updateUserSettings(req, res, next) {
  308. const { body } = parseReq(req, updateUserSettingsSchema)
  309. const userId = SessionManager.getLoggedInUserId(req.session)
  310. req.logger.addFields({ userId })
  311. const user = await User.findById(userId).exec()
  312. if (user == null) {
  313. throw new OError('problem updating user settings', { userId })
  314. }
  315. if (body.first_name != null) {
  316. user.first_name = body.first_name.trim()
  317. }
  318. if (body.last_name != null) {
  319. user.last_name = body.last_name.trim()
  320. }
  321. if (body.role != null) {
  322. user.role = body.role.trim()
  323. }
  324. if (body.institution != null) {
  325. user.institution = body.institution.trim()
  326. }
  327. if (body.mode != null) {
  328. user.ace.mode = body.mode
  329. }
  330. if (body.editorTheme != null) {
  331. user.ace.theme = body.editorTheme
  332. }
  333. if (body.editorLightTheme != null) {
  334. user.ace.lightTheme = body.editorLightTheme
  335. }
  336. if (body.editorDarkTheme != null) {
  337. user.ace.darkTheme = body.editorDarkTheme
  338. }
  339. if (body.overallTheme != null) {
  340. user.ace.overallTheme = body.overallTheme
  341. }
  342. if (body.fontSize != null) {
  343. user.ace.fontSize = body.fontSize
  344. }
  345. if (body.autoComplete != null) {
  346. user.ace.autoComplete = body.autoComplete
  347. }
  348. if (body.autoPairDelimiters != null) {
  349. user.ace.autoPairDelimiters = body.autoPairDelimiters
  350. }
  351. if (body.spellCheckLanguage != null) {
  352. user.ace.spellCheckLanguage = body.spellCheckLanguage
  353. }
  354. if (body.pdfViewer != null) {
  355. user.ace.pdfViewer = body.pdfViewer
  356. }
  357. if (body.syntaxValidation != null) {
  358. user.ace.syntaxValidation = body.syntaxValidation
  359. }
  360. if (body.fontFamily != null) {
  361. user.ace.fontFamily = body.fontFamily
  362. }
  363. if (body.lineHeight != null) {
  364. user.ace.lineHeight = body.lineHeight
  365. }
  366. if (body.mathPreview != null) {
  367. user.ace.mathPreview = body.mathPreview
  368. }
  369. if (body.breadcrumbs != null) {
  370. user.ace.breadcrumbs = Boolean(body.breadcrumbs)
  371. }
  372. if (body.referencesSearchMode != null) {
  373. const mode = body.referencesSearchMode === 'simple' ? 'simple' : 'advanced'
  374. user.ace.referencesSearchMode = mode
  375. }
  376. if (body.enableNewEditor != null) {
  377. user.ace.enableNewEditorStageFour = Boolean(body.enableNewEditor)
  378. }
  379. if (body.darkModePdf != null) {
  380. user.ace.darkModePdf = Boolean(body.darkModePdf)
  381. }
  382. await user.save()
  383. const newEmail = body.email?.trim().toLowerCase()
  384. if (
  385. newEmail == null ||
  386. newEmail === user.email ||
  387. req.externalAuthenticationSystemUsed()
  388. ) {
  389. // end here, don't update email
  390. SessionManager.setInSessionUser(req.session, {
  391. first_name: user.first_name,
  392. last_name: user.last_name,
  393. })
  394. res.sendStatus(200)
  395. } else if (newEmail.indexOf('@') === -1) {
  396. // email invalid
  397. res.sendStatus(400)
  398. } else {
  399. // update the user email
  400. const auditLog = {
  401. initiatorId: userId,
  402. ipAddress: req.ip,
  403. }
  404. try {
  405. await UserUpdater.promises.changeEmailAddress(userId, newEmail, auditLog)
  406. } catch (err) {
  407. if (err instanceof Errors.EmailExistsError) {
  408. const translation = req.i18n.translate('email_already_registered')
  409. return HttpErrorHandler.conflict(req, res, translation)
  410. } else {
  411. return HttpErrorHandler.legacyInternal(
  412. req,
  413. res,
  414. req.i18n.translate('problem_changing_email_address'),
  415. OError.tag(err, 'problem_changing_email_address', {
  416. userId,
  417. newEmail,
  418. })
  419. )
  420. }
  421. }
  422. const user = await User.findById(userId).exec()
  423. SessionManager.setInSessionUser(req.session, {
  424. email: user.email,
  425. first_name: user.first_name,
  426. last_name: user.last_name,
  427. })
  428. try {
  429. await UserHandler.promises.populateTeamInvites(user)
  430. } catch (err) {
  431. logger.error({ err }, 'error populateTeamInvites')
  432. }
  433. res.sendStatus(200)
  434. }
  435. }
  436. async function doLogout(req) {
  437. metrics.inc('user.logout')
  438. const user = SessionManager.getSessionUser(req.session)
  439. logger.debug({ user }, 'logging out')
  440. const sessionId = req.sessionID
  441. if (user != null) {
  442. UserAuditLogHandler.addEntryInBackground(
  443. user._id,
  444. 'logout',
  445. user._id,
  446. req.ip,
  447. {}
  448. )
  449. }
  450. if (typeof req.logout === 'function') {
  451. // passport logout
  452. const logout = promisify(req.logout.bind(req))
  453. await logout()
  454. }
  455. const destroySession = promisify(req.session.destroy.bind(req.session))
  456. await destroySession()
  457. if (user != null) {
  458. UserSessionsManager.promises.untrackSession(user, sessionId).catch(err => {
  459. logger.warn({ err, userId: user._id }, 'failed to untrack session')
  460. })
  461. }
  462. }
  463. async function logout(req, res, next) {
  464. const requestedRedirect = req.body.redirect
  465. ? UrlHelper.getSafeRedirectPath(req.body.redirect)
  466. : undefined
  467. const redirectUrl = requestedRedirect || '/login'
  468. await doLogout(req)
  469. if (acceptsJson(req)) {
  470. res.status(200).json({ redir: redirectUrl })
  471. } else {
  472. res.redirect(redirectUrl)
  473. }
  474. }
  475. async function expireDeletedUser(req, res, next) {
  476. const userId = req.params.userId
  477. await UserDeleter.promises.expireDeletedUser(userId)
  478. res.sendStatus(204)
  479. }
  480. async function expireDeletedUsersAfterDuration(req, res, next) {
  481. await UserDeleter.promises.expireDeletedUsersAfterDuration()
  482. res.sendStatus(204)
  483. }
  484. export default {
  485. clearSessions: expressify(clearSessions),
  486. changePassword: expressify(changePassword),
  487. tryDeleteUser: expressify(tryDeleteUser),
  488. subscribe: expressify(subscribe),
  489. unsubscribe: expressify(unsubscribe),
  490. updateUserSettings: expressify(updateUserSettings),
  491. logout: expressify(logout),
  492. expireDeletedUser: expressify(expireDeletedUser),
  493. expireDeletedUsersAfterDuration: expressify(expireDeletedUsersAfterDuration),
  494. ensureAffiliationMiddleware: expressify(ensureAffiliationMiddleware),
  495. ensureAffiliation,
  496. }