From 08ee1c372fd6420814040e4ee4dd5033f860d949 Mon Sep 17 00:00:00 2001 From: Lucas Gabriel Lima <lgl15@inf.ufpr.br> Date: Thu, 15 Sep 2016 11:10:49 -0300 Subject: [PATCH] add user model and password encryptation --- src/libs/models/user.js | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/libs/models/user.js diff --git a/src/libs/models/user.js b/src/libs/models/user.js new file mode 100644 index 00000000..30cfe93a --- /dev/null +++ b/src/libs/models/user.js @@ -0,0 +1,46 @@ +var mongoose = require('mongoose'); +var Schema = mongoose.Schema; +var bcrypt = require('bcrypt'); + +var UserSchema = new Schema({ + email:{ + type: String, + required: true + }, + password: { + type: String, + required: true + } +}); + +UserSchema.pre('save', function(next){ + var user = this; + if(this.isModified('password') || this.isNew){ + bcrypt.genSalt(10, function (err, salt){ + if(err){ + return next(err); + } + bcrypt.hash(user.password, salt, function(err, hash){ + if(err){ + return next(err); + } + user.password = hash; + next(); + }); + }); + } + else{ + return next(); + } +}); + +UserSchema.methods.comparePassword = function(passw, cb){ + bcrypt.compare(passw, this.password, function(err, isMatch){ + if(err){ + return cb(err); + } + cb(null, isMatch) + }); +}; + +module.exports = mongoose.model('User', UserSchema); -- GitLab