AuthenticationController.js 16 KB

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