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
|
|
|
|
},
|
|
|
|
apikey: {
|
|
|
|
type: String,
|
|
|
|
unique: true,
|
|
|
|
required: true
|
|
|
|
},
|
|
|
|
level: Number,
|
|
|
|
hash: String,
|
|
|
|
salt: String
|
|
|
|
});
|
|
|
|
|
|
|
|
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.genApiKey = function() {
|
|
|
|
this.apikey = crypto.randomBytes(16).toString('hex');
|
|
|
|
};
|
|
|
|
|
|
|
|
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,
|
|
|
|
level: this.level
|
|
|
|
};
|
|
|
|
|
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);
|