framez-server/Server/Schemas/Account.js

50 lines
1.5 KiB
JavaScript

const Config = require('../Config/Config')
const TokenGen = require('../Utils/TokenGenerator');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const Schema = mongoose.Schema;
const SALT_WORK_FACTOR = Config.salt_work_factor;
const Account = new Schema({
username: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true },
auth_token: {type: String, require: false, index: { unique: true }},
frames: {type: [Schema.ObjectId], default: []}
});
Account.pre('save', function(next) {
var user = this;
// only geerate auth_token if it was modified (or is new)
if(!user.auth_token){
user.auth_token = TokenGen.generate()
}
// only hash the password if it has been modified (or is new)
if (user.isModified('password')){
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
} else {
next()
}
});
Account.methods.comparePassword = (password, hash,cb) => {
bcrypt.compare(password, hash, (err, isMatch) => {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('Account', Account);