diff options
author | lowercasename <raphaelkabo@gmail.com> | 2019-07-25 16:16:04 +0100 |
---|---|---|
committer | lowercasename <raphaelkabo@gmail.com> | 2019-07-25 16:16:04 +0100 |
commit | 930542049e40a1a99c9a0c2c349519ccddf52140 (patch) | |
tree | ace22d1e09c409bc47743a44b8f8ca41bb8b2dd6 /models/User.js |
First commit
Diffstat (limited to 'models/User.js')
-rwxr-xr-x | models/User.js | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/models/User.js b/models/User.js new file mode 100755 index 0000000..9391c35 --- /dev/null +++ b/models/User.js @@ -0,0 +1,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);
\ No newline at end of file |