AuthenticationController.js 19 KB

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