AuthenticationController.js 15 KB

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