AuthenticationController.js 16 KB

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