AuthenticationController.js 16 KB

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