AuthenticationController.coffee 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. AuthenticationManager = require ("./AuthenticationManager")
  2. LoginRateLimiter = require("../Security/LoginRateLimiter")
  3. UserGetter = require "../User/UserGetter"
  4. UserUpdater = require "../User/UserUpdater"
  5. Metrics = require('../../infrastructure/Metrics')
  6. logger = require("logger-sharelatex")
  7. querystring = require('querystring')
  8. Url = require("url")
  9. Settings = require "settings-sharelatex"
  10. module.exports = AuthenticationController =
  11. login: (req, res, next = (error) ->) ->
  12. email = req.body?.email?.toLowerCase()
  13. password = req.body?.password
  14. redir = Url.parse(req.body?.redir or "/project").path
  15. LoginRateLimiter.processLoginRequest email, (err, isAllowed)->
  16. if !isAllowed
  17. logger.log email:email, "too many login requests"
  18. res.statusCode = 429
  19. return res.send
  20. message:
  21. text: req.i18n.translate("to_many_login_requests_2_mins"),
  22. type: 'error'
  23. AuthenticationManager.authenticate email: email, password, (error, user) ->
  24. return next(error) if error?
  25. if user?
  26. LoginRateLimiter.recordSuccessfulLogin email
  27. AuthenticationController._recordSuccessfulLogin user._id
  28. AuthenticationController.establishUserSession req, user, (error) ->
  29. return next(error) if error?
  30. req.session.justLoggedIn = true
  31. logger.log email: email, user_id: user._id.toString(), "successful log in"
  32. res.send redir: redir
  33. else
  34. AuthenticationController._recordFailedLogin()
  35. logger.log email: email, "failed log in"
  36. res.send message:
  37. text: req.i18n.translate("email_or_password_wrong_try_again"),
  38. type: 'error'
  39. getAuthToken: (req, res, next = (error) ->) ->
  40. AuthenticationController.getLoggedInUserId req, (error, user_id) ->
  41. return next(error) if error?
  42. AuthenticationManager.getAuthToken user_id, (error, auth_token) ->
  43. return next(error) if error?
  44. res.send(auth_token)
  45. getLoggedInUserId: (req, callback = (error, user_id) ->) ->
  46. if req?.session?.user?._id?
  47. callback null, req.session.user._id.toString()
  48. else
  49. callback null, null
  50. getLoggedInUser: (req, options = {allow_auth_token: false}, callback = (error, user) ->) ->
  51. if typeof(options) == "function"
  52. callback = options
  53. options = {allow_auth_token: false}
  54. if req.session?.user?._id?
  55. query = req.session.user._id
  56. else if req.query?.auth_token? and options.allow_auth_token
  57. query = { auth_token: req.query.auth_token }
  58. else
  59. return callback null, null
  60. UserGetter.getUser query, callback
  61. requireLogin: (options = {allow_auth_token: false, load_from_db: false}) ->
  62. doRequest = (req, res, next = (error) ->) ->
  63. load_from_db = options.load_from_db
  64. if req.query?.auth_token? and options.allow_auth_token
  65. load_from_db = true
  66. if load_from_db
  67. AuthenticationController.getLoggedInUser req, { allow_auth_token: options.allow_auth_token }, (error, user) ->
  68. return next(error) if error?
  69. return AuthenticationController._redirectToLoginOrRegisterPage(req, res) if !user?
  70. req.user = user
  71. return next()
  72. else
  73. if !req.session.user?
  74. AuthenticationController._redirectToLoginOrRegisterPage(req, res)
  75. else
  76. req.user = req.session.user
  77. return next()
  78. return doRequest
  79. _globalLoginWhitelist: []
  80. addEndpointToLoginWhitelist: (endpoint) ->
  81. AuthenticationController._globalLoginWhitelist.push endpoint
  82. requireGlobalLogin: (req, res, next) ->
  83. if req.url in AuthenticationController._globalLoginWhitelist
  84. return next()
  85. if req.headers['authorization']?
  86. return AuthenticationController.httpAuth(req, res, next)
  87. else if req.session.user?
  88. return next()
  89. else
  90. return res.redirect "/login"
  91. httpAuth: require('express').basicAuth (user, pass)->
  92. isValid = Settings.httpAuthUsers[user] == pass
  93. if !isValid
  94. logger.err user:user, pass:pass, "invalid login details"
  95. return isValid
  96. _redirectToLoginOrRegisterPage: (req, res)->
  97. if req.query.zipUrl? or req.query.project_name?
  98. return AuthenticationController._redirectToRegisterPage(req, res)
  99. else
  100. AuthenticationController._redirectToLoginPage(req, res)
  101. _redirectToLoginPage: (req, res) ->
  102. logger.log url: req.url, "user not logged in so redirecting to login page"
  103. req.query.redir = req.path
  104. url = "/login?#{querystring.stringify(req.query)}"
  105. res.redirect url
  106. Metrics.inc "security.login-redirect"
  107. _redirectToRegisterPage: (req, res) ->
  108. logger.log url: req.url, "user not logged in so redirecting to register page"
  109. req.query.redir = req.path
  110. url = "/register?#{querystring.stringify(req.query)}"
  111. res.redirect url
  112. Metrics.inc "security.login-redirect"
  113. _recordSuccessfulLogin: (user_id, callback = (error) ->) ->
  114. UserUpdater.updateUser user_id.toString(), {
  115. $set: { "lastLoggedIn": new Date() },
  116. $inc: { "loginCount": 1 }
  117. }, (error) ->
  118. callback(error) if error?
  119. Metrics.inc "user.login.success"
  120. callback()
  121. _recordFailedLogin: (callback = (error) ->) ->
  122. Metrics.inc "user.login.failed"
  123. callback()
  124. establishUserSession: (req, user, callback = (error) ->) ->
  125. lightUser =
  126. _id: user._id
  127. first_name: user.first_name
  128. last_name: user.last_name
  129. isAdmin: user.isAdmin
  130. email: user.email
  131. referal_id: user.referal_id
  132. # Regenerate the session to get a new sessionID (cookie value) to
  133. # protect against session fixation attacks
  134. oldSession = req.session
  135. req.sessionStore.generate(req)
  136. for key, value of oldSession
  137. req.session[key] = value
  138. req.session.user = lightUser
  139. callback()