2017-10-09 22:01:02 -04:00
|
|
|
var fs = require('fs');
|
|
|
|
var path = require('path');
|
|
|
|
var mongoose = require('mongoose');
|
|
|
|
var crypto = require('crypto');
|
|
|
|
var jwt = require('jsonwebtoken');
|
|
|
|
var jwtsign = require('jwt-sign');
|
|
|
|
|
|
|
|
var UserSchema = mongoose.Schema({
|
|
|
|
username: {
|
|
|
|
type: String,
|
|
|
|
unique: true,
|
|
|
|
required: true
|
|
|
|
},
|
2017-10-14 15:13:50 -04:00
|
|
|
uploadCount: {
|
|
|
|
type: Number,
|
|
|
|
default: 0
|
|
|
|
},
|
|
|
|
uploadSize: {
|
|
|
|
type: Number,
|
|
|
|
default: 0
|
|
|
|
},
|
2017-10-11 20:26:07 -04:00
|
|
|
scope: [String],
|
2017-10-09 22:01:02 -04:00
|
|
|
hash: String,
|
2017-10-11 12:55:46 -04:00
|
|
|
salt: String,
|
|
|
|
date: Date
|
2017-10-09 22:01:02 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
UserSchema.methods.setPassword = function(password) {
|
|
|
|
this.salt = crypto.randomBytes(16).toString('hex');
|
2017-10-11 10:15:19 -04:00
|
|
|
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha256').toString('hex');
|
2017-10-09 22:01:02 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
UserSchema.methods.validatePassword = function(password) {
|
2017-10-11 10:15:19 -04:00
|
|
|
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha256').toString('hex');
|
2017-10-09 22:01:02 -04:00
|
|
|
return this.hash === hash;
|
|
|
|
};
|
|
|
|
|
2017-10-11 10:15:19 -04:00
|
|
|
UserSchema.methods.genJwt = function() {
|
|
|
|
var expiry = new Date();
|
2017-10-09 22:01:02 -04:00
|
|
|
expiry.setDate(expiry.getDate() + 7);
|
|
|
|
|
|
|
|
var payload = {
|
|
|
|
_id: this._id,
|
|
|
|
username: this.username,
|
2017-10-11 20:26:07 -04:00
|
|
|
scope: this.scope,
|
|
|
|
exp: parseInt(expiry.getTime() / 1000)
|
2017-10-09 22:01:02 -04:00
|
|
|
};
|
|
|
|
|
2017-10-11 10:15:19 -04:00
|
|
|
var key = fs.readFileSync(path.join(__dirname, '../../jwt.pem'), 'utf8');
|
2017-10-09 22:01:02 -04:00
|
|
|
|
|
|
|
return jwt.sign(payload, key);
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = mongoose.model('User', UserSchema);
|