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
|
const mongoose = require('mongoose');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const { Schema } = mongoose;
const UserSchema = new Schema({
email: String,
hash: String,
salt: String,
});
UserSchema.methods.setPassword = function(password) {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
};
UserSchema.methods.validatePassword = function(password) {
const hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
return this.hash === hash;
};
UserSchema.methods.generateJWT = function() {
const today = new Date();
const expirationDate = new Date(today);
expirationDate.setDate(today.getDate() + 60);
return jwt.sign({
email: this.email,
id: this._id,
exp: parseInt(expirationDate.getTime() / 1000, 10),
}, 'secret');
}
UserSchema.methods.toAuthJSON = function() {
return {
_id: this._id,
email: this.email,
token: this.generateJWT(),
};
};
mongoose.model('User', UserSchema);
|