AuthenticationManager.coffee 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. Settings = require "settings-sharelatex"
  2. User = require("../../models/User").User
  3. {db, ObjectId} = require("../../infrastructure/mongojs")
  4. crypto = require 'crypto'
  5. bcrypt = require 'bcrypt'
  6. BCRYPT_ROUNDS = Settings?.security?.bcryptRounds or 12
  7. module.exports = AuthenticationManager =
  8. authenticate: (query, password, callback = (error, user) ->) ->
  9. # Using Mongoose for legacy reasons here. The returned User instance
  10. # gets serialized into the session and there may be subtle differences
  11. # between the user returned by Mongoose vs mongojs (such as default values)
  12. User.findOne query, (error, user) =>
  13. return callback(error) if error?
  14. if user?
  15. if user.hashedPassword?
  16. bcrypt.compare password, user.hashedPassword, (error, match) ->
  17. return callback(error) if error?
  18. if match
  19. AuthenticationManager.checkRounds user, user.hashedPassword, password, (err) ->
  20. return callback(err) if err?
  21. callback null, user
  22. else
  23. callback null, null
  24. else
  25. callback null, null
  26. else
  27. callback null, null
  28. setUserPassword: (user_id, password, callback = (error) ->) ->
  29. if Settings.passwordStrengthOptions?.length?.max? and Settings.passwordStrengthOptions?.length?.max < password.length
  30. return callback("password is too long")
  31. bcrypt.genSalt BCRYPT_ROUNDS, (error, salt) ->
  32. return callback(error) if error?
  33. bcrypt.hash password, salt, (error, hash) ->
  34. return callback(error) if error?
  35. db.users.update({
  36. _id: ObjectId(user_id.toString())
  37. }, {
  38. $set: hashedPassword: hash
  39. $unset: password: true
  40. }, callback)
  41. checkRounds: (user, hashedPassword, password, callback = (error) ->) ->
  42. # check current number of rounds and rehash if necessary
  43. currentRounds = bcrypt.getRounds hashedPassword
  44. if currentRounds < BCRYPT_ROUNDS
  45. AuthenticationManager.setUserPassword user._id, password, callback
  46. else
  47. callback()