AuthenticationController.js 16 KB

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