Advertisement
Guest User

Untitled

a guest
Aug 11th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. var UsuarioSchema = new Schema({
  2. login: {
  3. type: String,
  4. required: true,
  5. unique: true
  6. },
  7. password: {
  8. type: String,
  9. required: true
  10. }
  11. });
  12.  
  13. UsuarioSchema.pre('save', function(next){
  14. var user = this;
  15. if(this.isModified('password') || this.isNew){
  16. bcrypt.genSalt(10, function(err, salt){
  17. if(err){
  18. return next(err);
  19. }
  20. bcrypt.hash(user.password, salt, function(err, hash){
  21. if(err){
  22. return next(err);
  23. }
  24. user.password = hash;
  25. next();
  26. });
  27. });
  28. }
  29. else{
  30. return next();
  31. }
  32. });
  33.  
  34. UsuarioSchema.method.verificaSenha = function (password, cb){
  35. bcrypt.compare(password, this.password, function(err, isMatch){
  36. if(err){
  37. return cb(err);
  38. }
  39. cb(null, isMatch);
  40. });
  41. }
  42.  
  43. module.exports = mongoose.model('Usuario', UsuarioSchema);
  44.  
  45. router.post('/api/admin', function(req, res){
  46. Usuario.findOne({
  47. login: req.query.login
  48. }, function(err, user){
  49. if(err){
  50. res.json({sucesso: false, mensagem: 'Autenticação falhou. Usuário nao encontrado'});
  51. }
  52. else{
  53. user.verificaSenha(req.query.password, function(err, misMatch){
  54. if(isMatch && !err){
  55. var token = jwt.encode(user, config.secret);
  56. res.json({sucesso: true, mensagem: 'JWT: ' + token});
  57. }
  58. else{
  59. res.send({sucesso: false, mensagem: 'Autenticação falhou. Senha inválida'});
  60. }
  61. });
  62. }
  63. });
  64. });
  65.  
  66. UsuarioSchema.method('verificaSenha', function(password, cb){
  67. bcrypt.compare(password, this.password, function(err, isMatch){
  68. console.log('SENHA', this.passwword + ' PASS: ' + password);
  69. if(err){
  70. return cb(err);
  71. }
  72. cb(null, isMatch);
  73. });
  74. });
  75.  
  76. UsuarioSchema.statics.verificaSenha = function (password, cb){
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement