AuthenticationController.js 16 KB

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