p5.js-web-editor/server/models/user.js

56 lines
1.6 KiB
JavaScript
Raw Normal View History

import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');
const userSchema = new Schema({
2016-06-24 00:29:55 +02:00
name: { type: String, default: '' },
2016-06-27 19:09:18 +02:00
username: { type: String, required: true, unique: true },
2016-06-24 00:29:55 +02:00
password: { type: String },
github: { type: String },
email: { type: String, unique: true },
tokens: Array,
preferences: {
fontSize: { type: Number, default: 18 },
indentationAmount: { type: Number, default: 2 },
isTabIndent: { type: Boolean, default: false },
autosave: { type: Boolean, default: true }
}
2016-06-27 19:09:18 +02:00
}, { timestamps: true });
/**
* Password hash middleware.
*/
2016-06-27 19:09:18 +02:00
userSchema.pre('save', function checkPassword(next) { // eslint-disable-line consistent-return
const user = this;
if (!user.isModified('password')) { return next(); }
2016-06-27 19:09:18 +02:00
bcrypt.genSalt(10, (err, salt) => { // eslint-disable-line consistent-return
if (err) { return next(err); }
2016-06-27 19:09:18 +02:00
bcrypt.hash(user.password, salt, null, (innerErr, hash) => {
if (innerErr) { return next(innerErr); }
user.password = hash;
2016-06-27 19:09:18 +02:00
return next();
});
});
});
userSchema.virtual('id').get(function(){
return this._id.toHexString();
});
userSchema.set('toJSON', {
virtuals: true
});
/**
* Helper method for validating user's password.
*/
2016-06-27 19:09:18 +02:00
userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) {
2016-06-25 00:18:22 +02:00
// userSchema.methods.comparePassword = (candidatePassword, cb) => {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
cb(err, isMatch);
});
};
2016-06-25 00:18:22 +02:00
export default mongoose.model('User', userSchema);