AuthenticationController.js 18 KB

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