· 7 years ago · Jul 05, 2018, 05:34 PM
1const mongoose = require('mongoose');
2const crypto = require('crypto');
3const jwt = require('jsonwebtoken');
4
5const UserSchema = new mongoose.Schema({
6 email : {
7 type: String,
8 required: true,
9 unique: true
10 },
11 passwordHash : {
12 type: String,
13 required: true
14 },
15 salt: {
16 type: String,
17 required: true
18 }
19});
20
21UserSchema.method("setPassword", function(password){
22 this.salt = crypto.randomBytes(16).toString('hex');
23 this.passwordHash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
24});
25
26UserSchema.method("validatePassword", function(password){
27 let hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
28 return (hash === this.passwordHash);
29});
30
31UserSchema.method("generateJWT", function() {
32 return jwt.sign({
33 id: this._id,
34 email: this.email
35 }, 'SecretKey');
36});
37
38const User = mongoose.model('User', UserSchema);
39module.exports = User;