AuthenticationController.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. const AuthenticationManager = require('./AuthenticationManager')
  2. const SessionManager = require('./SessionManager')
  3. const OError = require('@overleaf/o-error')
  4. const LoginRateLimiter = require('../Security/LoginRateLimiter')
  5. const UserUpdater = require('../User/UserUpdater')
  6. const Metrics = require('@overleaf/metrics')
  7. const logger = require('@overleaf/logger')
  8. const querystring = require('querystring')
  9. const Settings = require('@overleaf/settings')
  10. const basicAuth = require('basic-auth')
  11. const tsscmp = require('tsscmp')
  12. const UserHandler = require('../User/UserHandler')
  13. const UserSessionsManager = require('../User/UserSessionsManager')
  14. const Analytics = require('../Analytics/AnalyticsManager')
  15. const passport = require('passport')
  16. const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
  17. const UrlHelper = require('../Helpers/UrlHelper')
  18. const AsyncFormHelper = require('../Helpers/AsyncFormHelper')
  19. const _ = require('lodash')
  20. const UserAuditLogHandler = require('../User/UserAuditLogHandler')
  21. const AnalyticsRegistrationSourceHelper = require('../Analytics/AnalyticsRegistrationSourceHelper')
  22. const {
  23. acceptsJson,
  24. } = require('../../infrastructure/RequestContentTypeDetection')
  25. const {
  26. ParallelLoginError,
  27. PasswordReusedError,
  28. } = require('./AuthenticationErrors')
  29. const { hasAdminAccess } = require('../Helpers/AdminAuthorizationHelper')
  30. const Modules = require('../../infrastructure/Modules')
  31. const { expressify } = require('@overleaf/promise-utils')
  32. function send401WithChallenge(res) {
  33. res.setHeader('WWW-Authenticate', 'OverleafLogin')
  34. res.sendStatus(401)
  35. }
  36. function checkCredentials(userDetailsMap, user, password) {
  37. const expectedPassword = userDetailsMap.get(user)
  38. const userExists = userDetailsMap.has(user) && expectedPassword // user exists with a non-null password
  39. const isValid = userExists && tsscmp(expectedPassword, password)
  40. if (!isValid) {
  41. logger.err({ user }, 'invalid login details')
  42. }
  43. Metrics.inc('security.http-auth.check-credentials', 1, {
  44. path: userExists ? 'known-user' : 'unknown-user',
  45. status: isValid ? 'pass' : 'fail',
  46. })
  47. return isValid
  48. }
  49. function reduceStaffAccess(staffAccess) {
  50. const reducedStaffAccess = {}
  51. for (const field in staffAccess) {
  52. if (staffAccess[field]) {
  53. reducedStaffAccess[field] = true
  54. }
  55. }
  56. return reducedStaffAccess
  57. }
  58. function userHasStaffAccess(user) {
  59. return user.staffAccess && Object.values(user.staffAccess).includes(true)
  60. }
  61. const AuthenticationController = {
  62. serializeUser(user, callback) {
  63. if (!user._id || !user.email) {
  64. const err = new Error('serializeUser called with non-user object')
  65. logger.warn({ user }, err.message)
  66. return callback(err)
  67. }
  68. const lightUser = {
  69. _id: user._id,
  70. first_name: user.first_name,
  71. last_name: user.last_name,
  72. email: user.email,
  73. referal_id: user.referal_id,
  74. session_created: new Date().toISOString(),
  75. ip_address: user._login_req_ip,
  76. must_reconfirm: user.must_reconfirm,
  77. v1_id: user.overleaf != null ? user.overleaf.id : undefined,
  78. analyticsId: user.analyticsId || user._id,
  79. alphaProgram: user.alphaProgram || undefined, // only store if set
  80. betaProgram: user.betaProgram || undefined, // only store if set
  81. }
  82. if (user.isAdmin) {
  83. lightUser.isAdmin = true
  84. }
  85. if (userHasStaffAccess(user)) {
  86. lightUser.staffAccess = reduceStaffAccess(user.staffAccess)
  87. }
  88. callback(null, lightUser)
  89. },
  90. deserializeUser(user, cb) {
  91. cb(null, user)
  92. },
  93. passportLogin(req, res, next) {
  94. // This function is middleware which wraps the passport.authenticate middleware,
  95. // so we can send back our custom `{message: {text: "", type: ""}}` responses on failure,
  96. // and send a `{redir: ""}` response on success
  97. passport.authenticate(
  98. 'local',
  99. { keepSessionInfo: true },
  100. function (err, user, info) {
  101. if (err) {
  102. return next(err)
  103. }
  104. if (user) {
  105. // `user` is either a user object or false
  106. AuthenticationController.setAuditInfo(req, {
  107. method: 'Password login',
  108. })
  109. return AuthenticationController.finishLogin(user, req, res, next)
  110. } else {
  111. if (info.redir != null) {
  112. return res.json({ redir: info.redir })
  113. } else {
  114. res.status(info.status || 200)
  115. delete info.status
  116. const body = { message: info }
  117. const { errorReason } = info
  118. if (errorReason) {
  119. body.errorReason = errorReason
  120. delete info.errorReason
  121. }
  122. return res.json(body)
  123. }
  124. }
  125. }
  126. )(req, res, next)
  127. },
  128. finishLogin(user, req, res, next) {
  129. if (user === false) {
  130. return AsyncFormHelper.redirect(req, res, '/login')
  131. } // OAuth2 'state' mismatch
  132. if (user.suspended) {
  133. return AsyncFormHelper.redirect(req, res, '/account-suspended')
  134. }
  135. if (Settings.adminOnlyLogin && !hasAdminAccess(user)) {
  136. return res.status(403).json({
  137. message: { type: 'error', text: 'Admin only panel' },
  138. })
  139. }
  140. const auditInfo = AuthenticationController.getAuditInfo(req)
  141. const anonymousAnalyticsId = req.session.analyticsId
  142. const isNewUser = req.session.justRegistered || false
  143. Modules.hooks.fire(
  144. 'preFinishLogin',
  145. req,
  146. res,
  147. user,
  148. function (error, results) {
  149. if (error) {
  150. return next(error)
  151. }
  152. if (results.some(result => result && result.doNotFinish)) {
  153. return
  154. }
  155. if (user.must_reconfirm) {
  156. return AuthenticationController._redirectToReconfirmPage(
  157. req,
  158. res,
  159. user
  160. )
  161. }
  162. const redir =
  163. AuthenticationController.getRedirectFromSession(req) || '/project'
  164. _loginAsyncHandlers(req, user, anonymousAnalyticsId, isNewUser)
  165. const userId = user._id
  166. UserAuditLogHandler.addEntry(
  167. userId,
  168. 'login',
  169. userId,
  170. req.ip,
  171. auditInfo,
  172. err => {
  173. if (err) {
  174. return next(err)
  175. }
  176. _afterLoginSessionSetup(req, user, function (err) {
  177. if (err) {
  178. return next(err)
  179. }
  180. AuthenticationController._clearRedirectFromSession(req)
  181. AnalyticsRegistrationSourceHelper.clearSource(req.session)
  182. AnalyticsRegistrationSourceHelper.clearInbound(req.session)
  183. AsyncFormHelper.redirect(req, res, redir)
  184. })
  185. }
  186. )
  187. }
  188. )
  189. },
  190. doPassportLogin(req, username, password, done) {
  191. const email = username.toLowerCase()
  192. Modules.hooks.fire(
  193. 'preDoPassportLogin',
  194. req,
  195. email,
  196. function (err, infoList) {
  197. if (err) {
  198. return done(err)
  199. }
  200. const info = infoList.find(i => i != null)
  201. if (info != null) {
  202. return done(null, false, info)
  203. }
  204. LoginRateLimiter.processLoginRequest(email, function (err, isAllowed) {
  205. if (err) {
  206. return done(err)
  207. }
  208. if (!isAllowed) {
  209. logger.debug({ email }, 'too many login requests')
  210. return done(null, null, {
  211. text: req.i18n.translate('to_many_login_requests_2_mins'),
  212. type: 'error',
  213. key: 'to-many-login-requests-2-mins',
  214. status: 429,
  215. })
  216. }
  217. const { fromKnownDevice } = AuthenticationController.getAuditInfo(req)
  218. const auditLog = {
  219. ipAddress: req.ip,
  220. info: { method: 'Password login', fromKnownDevice },
  221. }
  222. AuthenticationManager.authenticate(
  223. { email },
  224. password,
  225. auditLog,
  226. {
  227. enforceHIBPCheck: !fromKnownDevice,
  228. },
  229. function (error, user, isPasswordReused) {
  230. if (error != null) {
  231. if (error instanceof ParallelLoginError) {
  232. return done(null, false, { status: 429 })
  233. } else if (error instanceof PasswordReusedError) {
  234. const text = `${req.i18n
  235. .translate(
  236. 'password_compromised_try_again_or_use_known_device_or_reset'
  237. )
  238. .replace('<0>', '')
  239. .replace('</0>', ' (https://haveibeenpwned.com/passwords)')
  240. .replace('<1>', '')
  241. .replace(
  242. '</1>',
  243. ` (${Settings.siteUrl}/user/password/reset)`
  244. )}.`
  245. return done(null, false, {
  246. status: 400,
  247. type: 'error',
  248. key: 'password-compromised',
  249. text,
  250. })
  251. }
  252. return done(error)
  253. }
  254. if (
  255. user &&
  256. AuthenticationController.captchaRequiredForLogin(req, user)
  257. ) {
  258. done(null, false, {
  259. text: req.i18n.translate('cannot_verify_user_not_robot'),
  260. type: 'error',
  261. errorReason: 'cannot_verify_user_not_robot',
  262. status: 400,
  263. })
  264. } else if (user) {
  265. if (
  266. isPasswordReused &&
  267. AuthenticationController.getRedirectFromSession(req) == null
  268. ) {
  269. AuthenticationController.setRedirectInSession(
  270. req,
  271. '/compromised-password'
  272. )
  273. }
  274. // async actions
  275. done(null, user)
  276. } else {
  277. AuthenticationController._recordFailedLogin()
  278. logger.debug({ email }, 'failed log in')
  279. done(null, false, {
  280. type: 'error',
  281. key: 'invalid-password-retry-or-reset',
  282. status: 401,
  283. })
  284. }
  285. }
  286. )
  287. })
  288. }
  289. )
  290. },
  291. captchaRequiredForLogin(req, user) {
  292. switch (AuthenticationController.getAuditInfo(req).captcha) {
  293. case 'trusted':
  294. case 'disabled':
  295. return false
  296. case 'solved':
  297. return false
  298. case 'skipped': {
  299. let required = false
  300. if (user.lastFailedLogin) {
  301. const requireCaptchaUntil =
  302. user.lastFailedLogin.getTime() +
  303. Settings.elevateAccountSecurityAfterFailedLogin
  304. required = requireCaptchaUntil >= Date.now()
  305. }
  306. Metrics.inc('force_captcha_on_login', 1, {
  307. status: required ? 'yes' : 'no',
  308. })
  309. return required
  310. }
  311. default:
  312. throw new Error('captcha middleware missing in handler chain')
  313. }
  314. },
  315. ipMatchCheck(req, user) {
  316. if (req.ip !== user.lastLoginIp) {
  317. NotificationsBuilder.ipMatcherAffiliation(user._id).create(
  318. req.ip,
  319. () => {}
  320. )
  321. }
  322. return UserUpdater.updateUser(
  323. user._id.toString(),
  324. {
  325. $set: { lastLoginIp: req.ip },
  326. },
  327. () => {}
  328. )
  329. },
  330. requireLogin() {
  331. const doRequest = function (req, res, next) {
  332. if (next == null) {
  333. next = function () {}
  334. }
  335. if (!SessionManager.isUserLoggedIn(req.session)) {
  336. if (acceptsJson(req)) return send401WithChallenge(res)
  337. return AuthenticationController._redirectToLoginOrRegisterPage(req, res)
  338. } else {
  339. req.user = SessionManager.getSessionUser(req.session)
  340. return next()
  341. }
  342. }
  343. return doRequest
  344. },
  345. /**
  346. * @param {string} scope
  347. * @return {import('express').Handler}
  348. */
  349. requireOauth(scope) {
  350. if (typeof scope !== 'string' || !scope) {
  351. throw new Error(
  352. "requireOauth() expects a non-empty string as 'scope' parameter"
  353. )
  354. }
  355. // require this here because module may not be included in some versions
  356. const Oauth2Server = require('../../../../modules/oauth2-server/app/src/Oauth2Server')
  357. const middleware = async (req, res, next) => {
  358. const request = new Oauth2Server.Request(req)
  359. const response = new Oauth2Server.Response(res)
  360. try {
  361. const token = await Oauth2Server.server.authenticate(
  362. request,
  363. response,
  364. { scope }
  365. )
  366. req.oauth = { access_token: token.accessToken }
  367. req.oauth_token = token
  368. req.oauth_user = token.user
  369. next()
  370. } catch (err) {
  371. if (
  372. err.code === 400 &&
  373. err.message === 'Invalid request: malformed authorization header'
  374. ) {
  375. err.code = 401
  376. }
  377. // send all other errors
  378. res
  379. .status(err.code)
  380. .json({ error: err.name, error_description: err.message })
  381. }
  382. }
  383. return expressify(middleware)
  384. },
  385. _globalLoginWhitelist: [],
  386. addEndpointToLoginWhitelist(endpoint) {
  387. return AuthenticationController._globalLoginWhitelist.push(endpoint)
  388. },
  389. requireGlobalLogin(req, res, next) {
  390. if (
  391. AuthenticationController._globalLoginWhitelist.includes(
  392. req._parsedUrl.pathname
  393. )
  394. ) {
  395. return next()
  396. }
  397. if (req.headers.authorization != null) {
  398. AuthenticationController.requirePrivateApiAuth()(req, res, next)
  399. } else if (SessionManager.isUserLoggedIn(req.session)) {
  400. next()
  401. } else {
  402. logger.debug(
  403. { url: req.url },
  404. 'user trying to access endpoint not in global whitelist'
  405. )
  406. if (acceptsJson(req)) return send401WithChallenge(res)
  407. AuthenticationController.setRedirectInSession(req)
  408. res.redirect('/login')
  409. }
  410. },
  411. validateAdmin(req, res, next) {
  412. const adminDomains = Settings.adminDomains
  413. if (
  414. !adminDomains ||
  415. !(Array.isArray(adminDomains) && adminDomains.length)
  416. ) {
  417. return next()
  418. }
  419. const user = SessionManager.getSessionUser(req.session)
  420. if (!hasAdminAccess(user)) {
  421. return next()
  422. }
  423. const email = user.email
  424. if (email == null) {
  425. return next(
  426. new OError('[ValidateAdmin] Admin user without email address', {
  427. userId: user._id,
  428. })
  429. )
  430. }
  431. if (!adminDomains.find(domain => email.endsWith(`@${domain}`))) {
  432. return next(
  433. new OError('[ValidateAdmin] Admin user with invalid email domain', {
  434. email,
  435. userId: user._id,
  436. })
  437. )
  438. }
  439. return next()
  440. },
  441. checkCredentials,
  442. requireBasicAuth: function (userDetails) {
  443. const userDetailsMap = new Map(Object.entries(userDetails))
  444. return function (req, res, next) {
  445. const credentials = basicAuth(req)
  446. if (
  447. !credentials ||
  448. !checkCredentials(userDetailsMap, credentials.name, credentials.pass)
  449. ) {
  450. send401WithChallenge(res)
  451. Metrics.inc('security.http-auth', 1, { status: 'reject' })
  452. } else {
  453. Metrics.inc('security.http-auth', 1, { status: 'accept' })
  454. next()
  455. }
  456. }
  457. },
  458. requirePrivateApiAuth() {
  459. return AuthenticationController.requireBasicAuth(Settings.httpAuthUsers)
  460. },
  461. setAuditInfo(req, info) {
  462. if (!req.__authAuditInfo) {
  463. req.__authAuditInfo = {}
  464. }
  465. Object.assign(req.__authAuditInfo, info)
  466. },
  467. getAuditInfo(req) {
  468. return req.__authAuditInfo || {}
  469. },
  470. setRedirectInSession(req, value) {
  471. if (value == null) {
  472. value =
  473. Object.keys(req.query).length > 0
  474. ? `${req.path}?${querystring.stringify(req.query)}`
  475. : `${req.path}`
  476. }
  477. if (
  478. req.session != null &&
  479. !/^\/(socket.io|js|stylesheets|img)\/.*$/.test(value) &&
  480. !/^.*\.(png|jpeg|svg)$/.test(value)
  481. ) {
  482. const safePath = UrlHelper.getSafeRedirectPath(value)
  483. return (req.session.postLoginRedirect = safePath)
  484. }
  485. },
  486. _redirectToLoginOrRegisterPage(req, res) {
  487. if (
  488. req.query.zipUrl != null ||
  489. req.session.sharedProjectData ||
  490. req.path === '/user/subscription/new'
  491. ) {
  492. AuthenticationController._redirectToRegisterPage(req, res)
  493. } else {
  494. AuthenticationController._redirectToLoginPage(req, res)
  495. }
  496. },
  497. _redirectToLoginPage(req, res) {
  498. logger.debug(
  499. { url: req.url },
  500. 'user not logged in so redirecting to login page'
  501. )
  502. AuthenticationController.setRedirectInSession(req)
  503. const url = `/login?${querystring.stringify(req.query)}`
  504. res.redirect(url)
  505. Metrics.inc('security.login-redirect')
  506. },
  507. _redirectToReconfirmPage(req, res, user) {
  508. logger.debug(
  509. { url: req.url },
  510. 'user needs to reconfirm so redirecting to reconfirm page'
  511. )
  512. req.session.reconfirm_email = user != null ? user.email : undefined
  513. const redir = '/user/reconfirm'
  514. AsyncFormHelper.redirect(req, res, redir)
  515. },
  516. _redirectToRegisterPage(req, res) {
  517. logger.debug(
  518. { url: req.url },
  519. 'user not logged in so redirecting to register page'
  520. )
  521. AuthenticationController.setRedirectInSession(req)
  522. const url = `/register?${querystring.stringify(req.query)}`
  523. res.redirect(url)
  524. Metrics.inc('security.login-redirect')
  525. },
  526. _recordSuccessfulLogin(userId, callback) {
  527. if (callback == null) {
  528. callback = function () {}
  529. }
  530. UserUpdater.updateUser(
  531. userId.toString(),
  532. {
  533. $set: { lastLoggedIn: new Date() },
  534. $inc: { loginCount: 1 },
  535. },
  536. function (error) {
  537. if (error != null) {
  538. callback(error)
  539. }
  540. Metrics.inc('user.login.success')
  541. callback()
  542. }
  543. )
  544. },
  545. _recordFailedLogin(callback) {
  546. Metrics.inc('user.login.failed')
  547. if (callback) callback()
  548. },
  549. getRedirectFromSession(req) {
  550. let safePath
  551. const value = _.get(req, ['session', 'postLoginRedirect'])
  552. if (value) {
  553. safePath = UrlHelper.getSafeRedirectPath(value)
  554. }
  555. return safePath || null
  556. },
  557. _clearRedirectFromSession(req) {
  558. if (req.session != null) {
  559. delete req.session.postLoginRedirect
  560. }
  561. },
  562. }
  563. function _afterLoginSessionSetup(req, user, callback) {
  564. req.login(user, { keepSessionInfo: true }, function (err) {
  565. if (err) {
  566. OError.tag(err, 'error from req.login', {
  567. user_id: user._id,
  568. })
  569. return callback(err)
  570. }
  571. delete req.session.__tmp
  572. delete req.session.csrfSecret
  573. req.session.save(function (err) {
  574. if (err) {
  575. OError.tag(err, 'error saving regenerated session after login', {
  576. user_id: user._id,
  577. })
  578. return callback(err)
  579. }
  580. UserSessionsManager.trackSession(user, req.sessionID, function () {})
  581. if (!req.deviceHistory) {
  582. // Captcha disabled or SSO-based login.
  583. return callback()
  584. }
  585. req.deviceHistory.add(user.email)
  586. req.deviceHistory
  587. .serialize(req.res)
  588. .catch(err => {
  589. logger.err({ err }, 'cannot serialize deviceHistory')
  590. })
  591. .finally(() => callback())
  592. })
  593. })
  594. }
  595. function _loginAsyncHandlers(req, user, anonymousAnalyticsId, isNewUser) {
  596. UserHandler.setupLoginData(user, err => {
  597. if (err != null) {
  598. logger.warn({ err }, 'error setting up login data')
  599. }
  600. })
  601. LoginRateLimiter.recordSuccessfulLogin(user.email, () => {})
  602. AuthenticationController._recordSuccessfulLogin(user._id, () => {})
  603. AuthenticationController.ipMatchCheck(req, user)
  604. Analytics.recordEventForUserInBackground(user._id, 'user-logged-in', {
  605. source: req.session.saml
  606. ? 'saml'
  607. : req.user_info?.auth_provider || 'email-password',
  608. })
  609. Analytics.identifyUser(user._id, anonymousAnalyticsId, isNewUser)
  610. logger.debug(
  611. { email: user.email, userId: user._id.toString() },
  612. 'successful log in'
  613. )
  614. req.session.justLoggedIn = true
  615. // capture the request ip for use when creating the session
  616. return (user._login_req_ip = req.ip)
  617. }
  618. module.exports = AuthenticationController