AuthenticationController.js 15 KB

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