AuthenticationController.js 16 KB

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