-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser-model.js
More file actions
59 lines (45 loc) · 1.46 KB
/
user-model.js
File metadata and controls
59 lines (45 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const UserSchema = new mongoose.Schema({
//REQUIRED:
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
//NOT REQUIRED:
estado : { type: Boolean, default: true },
score : { type: Number, default: 0}
});
//MIDLEWARE: Encripta el password antes de ser almacenado en la BBDD
UserSchema.pre('save', function(next) {
if(this.isNew || this.isModified('password')) {
const document=this;
bcrypt.hash(document.password, saltRounds,(err, hashedPassword)=>{
if(err){
next(err);
}else{
document.password=hashedPassword;
next();
}
});
}else{
next();
}
});
//funcion aternativa (Usando la librería PASSPORT):
UserSchema.methods.matchPassword = async function (password) {
return await bcrypt.compare(password, this.password);
};
//Exportación del modelo
module.exports = mongoose.model('User', UserSchema);
/* CÓDIGO DESCARTADO
// //FUNCIÓN: Desencripta el pasword y la compara con el IMPUT del usuario.
// UserSchema.methods.isCorrectPassword = function(password,callback){
// bcrypt.compare(password, this.password,function(err, same){
// if(err){
// callback(err);
// }else{
// callback(err,same);
// }
// });
// }
*/