Guest User

Untitled

a guest
Aug 12th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. Why am I getting two different encrypted hashes from node.bcrypt even though password and salt are the same?
  2. vows.describe('User').addBatch
  3. 'User':
  4. topic: ->
  5. user = new User
  6. name: 'test.user'
  7.  
  8. '#authenticate':
  9. topic: (user) ->
  10. promise = new events.EventEmitter
  11. password = User.generatePassword()
  12. user.set 'password', password
  13. user.save (err) ->
  14. User.authenticate user.name, password, (err, user) ->
  15. if (err) promise.emit 'error', err
  16. else promise.emit 'success', user
  17. promise
  18.  
  19. 'should return a user': (err, user) ->
  20. assert.isNotNull user
  21.  
  22. bcrypt = require 'bcrypt'
  23. mongoose = require 'mongoose'
  24.  
  25. User = new mongoose.Schema
  26. name: { type: String, unique: true }
  27. password_salt: String
  28. password_hash: String
  29.  
  30. User.virtual('password')
  31. .set (pass) ->
  32. salt = bcrypt.gen_salt_sync(10)
  33. @set 'password_salt', salt
  34. @set 'password_hash', bcrypt.encrypt_sync pass, salt
  35.  
  36. User.static
  37. generatePassword: ->
  38. # just generates 8 characters of alphanumerics
  39.  
  40. authenticate: (name, password, next) ->
  41. @findOne { name: name }, (err, user) ->
  42. if user
  43. bcrypt.compare password, user.password_hash, (err, res) ->
  44. if res is true then next(err, user) else next(err, null)
  45. else
  46. next(err, user)
  47.  
  48. # spec/models/user_spec.coffee
  49.  
  50. # Rest of the test snippet above...
  51. user.save (err) ->
  52. console.log "1 Pass: #{password}n
  53. 1 Salt: #{user.password_salt}n
  54. 1 Hash: #{user.password_hash}"
  55. # Rest of the test snippet above...
  56.  
  57. # models/user.coffee
  58.  
  59. # Rest of user model snippet above...
  60. bcrypt.compare password, user.password_hash, (err, res) ->
  61. console.log "2 Pass: #{password}n
  62. 2 Salt: #{user.password_salt}n
  63. 2 Hash: #{user.password_hash}nn
  64.  
  65. 2 Encrypt Again: #{bcrypt.encrypt_sync password, user.password_salt}"
  66. # Rest of user model snippet above...
  67.  
  68. # console.log output
  69.  
  70. 1 Pass: Q8ZE0Yj1
  71. 1 Salt: $2a$10$o0sRXPchaW2R841MWRCT3u
  72. 1 Hash: $2a$10$o0sRXPchaW2R841MWRCT3uj80ecPs1QX4kTfC/hzG.2kMa8RaCsZu
  73.  
  74. 2 Pass: Q8ZE0Yj1
  75. 2 Salt: $2a$10$o0sRXPchaW2R841MWRCT3u
  76. 2 Hash: $2a$10$o0sRXPchaW2R841MWRCT3uj80ecPs1QX4kTfC/hzG.2kMa8RaCsZu
  77. 2 Encrypt Again: $2a$10$o0sRXPchaW2R841MWRCT3ukGkrfpJuzZFKJcdX0WiNHONuJTy
Add Comment
Please, Sign In to add comment