User.js
1.99 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const jwt = require('jsonwebtoken');
const moment = require("moment");
const userSchema = mongoose.Schema({
name: {
type:String,
maxlength:50
},
email: {
type:String,
trim:true,
unique: 1
},
password: {
type: String,
minglength: 5
},
lastname: {
type:String,
maxlength: 50
},
role : {
type:Number,
default: 0
},
image: String,
token : {
type: String,
},
tokenExp :{
type: Number
}
})
userSchema.pre('save', function( next ) {
var user = this;
if(user.isModified('password')){
// console.log('password changed')
bcrypt.genSalt(saltRounds, 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 {
next()
}
});
userSchema.methods.comparePassword = function(plainPassword,cb){
bcrypt.compare(plainPassword, this.password, function(err, isMatch){
if (err) return cb(err);
cb(null, isMatch)
})
}
userSchema.methods.generateToken = function(cb) {
var user = this;
var token = jwt.sign(user._id.toHexString(),'secret')
var oneHour = moment().add(1, 'hour').valueOf();
user.tokenExp = oneHour;
user.token = token;
user.save(function (err, user){
if(err) return cb(err)
cb(null, user);
})
}
userSchema.statics.findByToken = function (token, cb) {
var user = this;
jwt.verify(token,'secret',function(err, decode){
user.findOne({"_id":decode, "token":token}, function(err, user){
if(err) return cb(err);
cb(null, user);
})
})
}
const User = mongoose.model('User', userSchema);
module.exports = { User }