AuthenticationController.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. const AuthenticationManager = require('./AuthenticationManager')
  2. const OError = require('@overleaf/o-error')
  3. const LoginRateLimiter = require('../Security/LoginRateLimiter')
  4. const UserUpdater = require('../User/UserUpdater')
  5. const Metrics = require('@overleaf/metrics')
  6. const logger = require('logger-sharelatex')
  7. const querystring = require('querystring')
  8. const Settings = require('settings-sharelatex')
  9. const basicAuth = require('basic-auth-connect')
  10. const crypto = require('crypto')
  11. const UserHandler = require('../User/UserHandler')
  12. const UserSessionsManager = require('../User/UserSessionsManager')
  13. const SessionStoreManager = require('../../infrastructure/SessionStoreManager')
  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 AnalyticsRegistrationSourceMiddleware = require('../Analytics/AnalyticsRegistrationSourceMiddleware')
  22. const {
  23. acceptsJson,
  24. } = require('../../infrastructure/RequestContentTypeDetection')
  25. function send401WithChallenge(res) {
  26. res.setHeader('WWW-Authenticate', 'OverleafLogin')
  27. res.sendStatus(401)
  28. }
  29. const AuthenticationController = {
  30. serializeUser(user, callback) {
  31. if (!user._id || !user.email) {
  32. const err = new Error('serializeUser called with non-user object')
  33. logger.warn({ user }, err.message)
  34. return callback(err)
  35. }
  36. const lightUser = {
  37. _id: user._id,
  38. first_name: user.first_name,
  39. last_name: user.last_name,
  40. isAdmin: user.isAdmin,
  41. staffAccess: user.staffAccess,
  42. email: user.email,
  43. referal_id: user.referal_id,
  44. session_created: new Date().toISOString(),
  45. ip_address: user._login_req_ip,
  46. must_reconfirm: user.must_reconfirm,
  47. v1_id: user.overleaf != null ? user.overleaf.id : undefined,
  48. }
  49. callback(null, lightUser)
  50. },
  51. deserializeUser(user, cb) {
  52. cb(null, user)
  53. },
  54. passportLogin(req, res, next) {
  55. // This function is middleware which wraps the passport.authenticate middleware,
  56. // so we can send back our custom `{message: {text: "", type: ""}}` responses on failure,
  57. // and send a `{redir: ""}` response on success
  58. passport.authenticate('local', function (err, user, info) {
  59. if (err) {
  60. return next(err)
  61. }
  62. if (user) {
  63. // `user` is either a user object or false
  64. return AuthenticationController.finishLogin(user, req, res, next)
  65. } else {
  66. if (info.redir != null) {
  67. return res.json({ redir: info.redir })
  68. } else {
  69. return res.json({ message: info })
  70. }
  71. }
  72. })(req, res, next)
  73. },
  74. finishLogin(user, req, res, next) {
  75. if (user === false) {
  76. return res.redirect('/login')
  77. } // OAuth2 'state' mismatch
  78. const Modules = require('../../infrastructure/Modules')
  79. Modules.hooks.fire(
  80. 'preFinishLogin',
  81. req,
  82. res,
  83. user,
  84. function (error, results) {
  85. if (error) {
  86. return next(error)
  87. }
  88. if (results.some(result => result && result.doNotFinish)) {
  89. return
  90. }
  91. if (user.must_reconfirm) {
  92. return AuthenticationController._redirectToReconfirmPage(
  93. req,
  94. res,
  95. user
  96. )
  97. }
  98. const redir =
  99. AuthenticationController._getRedirectFromSession(req) || '/project'
  100. _loginAsyncHandlers(req, user)
  101. const userId = user._id
  102. UserAuditLogHandler.addEntry(userId, 'login', userId, req.ip, err => {
  103. if (err) {
  104. return next(err)
  105. }
  106. _afterLoginSessionSetup(req, user, function (err) {
  107. if (err) {
  108. return next(err)
  109. }
  110. AuthenticationController._clearRedirectFromSession(req)
  111. AnalyticsRegistrationSourceMiddleware.doClearSource(req.session)
  112. AsyncFormHelper.redirect(req, res, redir)
  113. })
  114. })
  115. }
  116. )
  117. },
  118. doPassportLogin(req, username, password, done) {
  119. const email = username.toLowerCase()
  120. const Modules = require('../../infrastructure/Modules')
  121. Modules.hooks.fire(
  122. 'preDoPassportLogin',
  123. req,
  124. email,
  125. function (err, infoList) {
  126. if (err) {
  127. return done(err)
  128. }
  129. const info = infoList.find(i => i != null)
  130. if (info != null) {
  131. return done(null, false, info)
  132. }
  133. LoginRateLimiter.processLoginRequest(email, function (err, isAllowed) {
  134. if (err) {
  135. return done(err)
  136. }
  137. if (!isAllowed) {
  138. logger.log({ email }, 'too many login requests')
  139. return done(null, null, {
  140. text: req.i18n.translate('to_many_login_requests_2_mins'),
  141. type: 'error',
  142. })
  143. }
  144. AuthenticationManager.authenticate(
  145. { email },
  146. password,
  147. function (error, user) {
  148. if (error != null) {
  149. return done(error)
  150. }
  151. if (user != null) {
  152. // async actions
  153. done(null, user)
  154. } else {
  155. AuthenticationController._recordFailedLogin()
  156. logger.log({ email }, 'failed log in')
  157. done(null, false, {
  158. text: req.i18n.translate('email_or_password_wrong_try_again'),
  159. type: 'error',
  160. })
  161. }
  162. }
  163. )
  164. })
  165. }
  166. )
  167. },
  168. ipMatchCheck(req, user) {
  169. if (req.ip !== user.lastLoginIp) {
  170. NotificationsBuilder.ipMatcherAffiliation(user._id).create(req.ip)
  171. }
  172. return UserUpdater.updateUser(user._id.toString(), {
  173. $set: { lastLoginIp: req.ip },
  174. })
  175. },
  176. setInSessionUser(req, props) {
  177. const sessionUser = AuthenticationController.getSessionUser(req)
  178. if (!sessionUser) {
  179. return
  180. }
  181. for (const key in props) {
  182. const value = props[key]
  183. sessionUser[key] = value
  184. }
  185. return null
  186. },
  187. isUserLoggedIn(req) {
  188. const userId = AuthenticationController.getLoggedInUserId(req)
  189. return ![null, undefined, false].includes(userId)
  190. },
  191. // TODO: perhaps should produce an error if the current user is not present
  192. getLoggedInUserId(req) {
  193. const user = AuthenticationController.getSessionUser(req)
  194. if (user) {
  195. return user._id
  196. } else {
  197. return null
  198. }
  199. },
  200. getLoggedInUserV1Id(req) {
  201. const user = AuthenticationController.getSessionUser(req)
  202. if ((user != null ? user.v1_id : undefined) != null) {
  203. return user.v1_id
  204. } else {
  205. return null
  206. }
  207. },
  208. getSessionUser(req) {
  209. const sessionUser = _.get(req, ['session', 'user'])
  210. const sessionPassportUser = _.get(req, ['session', 'passport', 'user'])
  211. return sessionUser || sessionPassportUser || null
  212. },
  213. requireLogin() {
  214. const doRequest = function (req, res, next) {
  215. if (next == null) {
  216. next = function () {}
  217. }
  218. if (!AuthenticationController.isUserLoggedIn(req)) {
  219. if (acceptsJson(req)) return send401WithChallenge(res)
  220. return AuthenticationController._redirectToLoginOrRegisterPage(req, res)
  221. } else {
  222. req.user = AuthenticationController.getSessionUser(req)
  223. return next()
  224. }
  225. }
  226. return doRequest
  227. },
  228. requireOauth() {
  229. // require this here because module may not be included in some versions
  230. const Oauth2Server = require('../../../../modules/oauth2-server/app/src/Oauth2Server')
  231. return function (req, res, next) {
  232. if (next == null) {
  233. next = function () {}
  234. }
  235. const request = new Oauth2Server.Request(req)
  236. const response = new Oauth2Server.Response(res)
  237. return Oauth2Server.server.authenticate(
  238. request,
  239. response,
  240. {},
  241. function (err, token) {
  242. if (err) {
  243. // use a 401 status code for malformed header for git-bridge
  244. if (
  245. err.code === 400 &&
  246. err.message === 'Invalid request: malformed authorization header'
  247. ) {
  248. err.code = 401
  249. }
  250. // send all other errors
  251. return res
  252. .status(err.code)
  253. .json({ error: err.name, error_description: err.message })
  254. }
  255. req.oauth = { access_token: token.accessToken }
  256. req.oauth_token = token
  257. req.oauth_user = token.user
  258. return next()
  259. }
  260. )
  261. }
  262. },
  263. validateUserSession: function () {
  264. // Middleware to check that the user's session is still good on key actions,
  265. // such as opening a a project. Could be used to check that session has not
  266. // exceeded a maximum lifetime (req.session.session_created), or for session
  267. // hijacking checks (e.g. change of ip address, req.session.ip_address). For
  268. // now, just check that the session has been loaded from the session store
  269. // correctly.
  270. return function (req, res, next) {
  271. // check that the session store is returning valid results
  272. if (req.session && !SessionStoreManager.hasValidationToken(req)) {
  273. // force user to update session
  274. req.session.regenerate(() => {
  275. // need to destroy the existing session and generate a new one
  276. // otherwise they will already be logged in when they are redirected
  277. // to the login page
  278. if (acceptsJson(req)) return send401WithChallenge(res)
  279. AuthenticationController._redirectToLoginOrRegisterPage(req, res)
  280. })
  281. } else {
  282. next()
  283. }
  284. }
  285. },
  286. _globalLoginWhitelist: [],
  287. addEndpointToLoginWhitelist(endpoint) {
  288. return AuthenticationController._globalLoginWhitelist.push(endpoint)
  289. },
  290. requireGlobalLogin(req, res, next) {
  291. if (
  292. AuthenticationController._globalLoginWhitelist.includes(
  293. req._parsedUrl.pathname
  294. )
  295. ) {
  296. return next()
  297. }
  298. if (req.headers.authorization != null) {
  299. AuthenticationController.requirePrivateApiAuth()(req, res, next)
  300. } else if (AuthenticationController.isUserLoggedIn(req)) {
  301. next()
  302. } else {
  303. logger.log(
  304. { url: req.url },
  305. 'user trying to access endpoint not in global whitelist'
  306. )
  307. if (acceptsJson(req)) return send401WithChallenge(res)
  308. AuthenticationController.setRedirectInSession(req)
  309. res.redirect('/login')
  310. }
  311. },
  312. validateAdmin(req, res, next) {
  313. const adminDomains = Settings.adminDomains
  314. if (
  315. !adminDomains ||
  316. !(Array.isArray(adminDomains) && adminDomains.length)
  317. ) {
  318. return next()
  319. }
  320. const user = AuthenticationController.getSessionUser(req)
  321. if (!(user && user.isAdmin)) {
  322. return next()
  323. }
  324. const email = user.email
  325. if (email == null) {
  326. return next(
  327. new OError('[ValidateAdmin] Admin user without email address', {
  328. userId: user._id,
  329. })
  330. )
  331. }
  332. if (!adminDomains.find(domain => email.endsWith(`@${domain}`))) {
  333. return next(
  334. new OError('[ValidateAdmin] Admin user with invalid email domain', {
  335. email: email,
  336. userId: user._id,
  337. })
  338. )
  339. }
  340. return next()
  341. },
  342. requireBasicAuth: function (userDetails) {
  343. return basicAuth(function (user, pass) {
  344. const expectedPassword = userDetails[user]
  345. const isValid =
  346. expectedPassword &&
  347. expectedPassword.length === pass.length &&
  348. crypto.timingSafeEqual(Buffer.from(expectedPassword), Buffer.from(pass))
  349. if (!isValid) {
  350. logger.err({ user, pass }, 'invalid login details')
  351. }
  352. return isValid
  353. })
  354. },
  355. requirePrivateApiAuth() {
  356. return AuthenticationController.requireBasicAuth(Settings.httpAuthUsers)
  357. },
  358. setRedirectInSession(req, value) {
  359. if (value == null) {
  360. value =
  361. Object.keys(req.query).length > 0
  362. ? `${req.path}?${querystring.stringify(req.query)}`
  363. : `${req.path}`
  364. }
  365. if (
  366. req.session != null &&
  367. !/^\/(socket.io|js|stylesheets|img)\/.*$/.test(value) &&
  368. !/^.*\.(png|jpeg|svg)$/.test(value)
  369. ) {
  370. const safePath = UrlHelper.getSafeRedirectPath(value)
  371. return (req.session.postLoginRedirect = safePath)
  372. }
  373. },
  374. _redirectToLoginOrRegisterPage(req, res) {
  375. if (
  376. req.query.zipUrl != null ||
  377. req.query.project_name != null ||
  378. req.path === '/user/subscription/new'
  379. ) {
  380. AuthenticationController._redirectToRegisterPage(req, res)
  381. } else {
  382. AuthenticationController._redirectToLoginPage(req, res)
  383. }
  384. },
  385. _redirectToLoginPage(req, res) {
  386. logger.log(
  387. { url: req.url },
  388. 'user not logged in so redirecting to login page'
  389. )
  390. AuthenticationController.setRedirectInSession(req)
  391. const url = `/login?${querystring.stringify(req.query)}`
  392. res.redirect(url)
  393. Metrics.inc('security.login-redirect')
  394. },
  395. _redirectToReconfirmPage(req, res, user) {
  396. logger.log(
  397. { url: req.url },
  398. 'user needs to reconfirm so redirecting to reconfirm page'
  399. )
  400. req.session.reconfirm_email = user != null ? user.email : undefined
  401. const redir = '/user/reconfirm'
  402. AsyncFormHelper.redirect(req, res, redir)
  403. },
  404. _redirectToRegisterPage(req, res) {
  405. logger.log(
  406. { url: req.url },
  407. 'user not logged in so redirecting to register page'
  408. )
  409. AuthenticationController.setRedirectInSession(req)
  410. const url = `/register?${querystring.stringify(req.query)}`
  411. res.redirect(url)
  412. Metrics.inc('security.login-redirect')
  413. },
  414. _recordSuccessfulLogin(userId, callback) {
  415. if (callback == null) {
  416. callback = function () {}
  417. }
  418. UserUpdater.updateUser(
  419. userId.toString(),
  420. {
  421. $set: { lastLoggedIn: new Date() },
  422. $inc: { loginCount: 1 },
  423. },
  424. function (error) {
  425. if (error != null) {
  426. callback(error)
  427. }
  428. Metrics.inc('user.login.success')
  429. callback()
  430. }
  431. )
  432. },
  433. _recordFailedLogin(callback) {
  434. Metrics.inc('user.login.failed')
  435. if (callback) callback()
  436. },
  437. _getRedirectFromSession(req) {
  438. let safePath
  439. const value = _.get(req, ['session', 'postLoginRedirect'])
  440. if (value) {
  441. safePath = UrlHelper.getSafeRedirectPath(value)
  442. }
  443. return safePath || null
  444. },
  445. _clearRedirectFromSession(req) {
  446. if (req.session != null) {
  447. delete req.session.postLoginRedirect
  448. }
  449. },
  450. }
  451. function _afterLoginSessionSetup(req, user, callback) {
  452. if (callback == null) {
  453. callback = function () {}
  454. }
  455. req.login(user, function (err) {
  456. if (err) {
  457. OError.tag(err, 'error from req.login', {
  458. user_id: user._id,
  459. })
  460. return callback(err)
  461. }
  462. // Regenerate the session to get a new sessionID (cookie value) to
  463. // protect against session fixation attacks
  464. const oldSession = req.session
  465. req.session.destroy(function (err) {
  466. if (err) {
  467. OError.tag(err, 'error when trying to destroy old session', {
  468. user_id: user._id,
  469. })
  470. return callback(err)
  471. }
  472. req.sessionStore.generate(req)
  473. // Note: the validation token is not writable, so it does not get
  474. // transferred to the new session below.
  475. for (const key in oldSession) {
  476. const value = oldSession[key]
  477. if (key !== '__tmp' && key !== 'csrfSecret') {
  478. req.session[key] = value
  479. }
  480. }
  481. req.session.save(function (err) {
  482. if (err) {
  483. OError.tag(err, 'error saving regenerated session after login', {
  484. user_id: user._id,
  485. })
  486. return callback(err)
  487. }
  488. UserSessionsManager.trackSession(user, req.sessionID, function () {})
  489. callback(null)
  490. })
  491. })
  492. })
  493. }
  494. function _loginAsyncHandlers(req, user) {
  495. UserHandler.setupLoginData(user, err => {
  496. if (err != null) {
  497. logger.warn({ err }, 'error setting up login data')
  498. }
  499. })
  500. LoginRateLimiter.recordSuccessfulLogin(user.email)
  501. AuthenticationController._recordSuccessfulLogin(user._id)
  502. AuthenticationController.ipMatchCheck(req, user)
  503. Analytics.recordEvent(user._id, 'user-logged-in')
  504. Analytics.identifyUser(user._id, req.sessionID)
  505. logger.log(
  506. { email: user.email, user_id: user._id.toString() },
  507. 'successful log in'
  508. )
  509. req.session.justLoggedIn = true
  510. // capture the request ip for use when creating the session
  511. return (user._login_req_ip = req.ip)
  512. }
  513. module.exports = AuthenticationController