const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcryptjs');
const UserSchema = new Schema({
username: {
type: String,
unique: true,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
admin: {
type: Boolean,
required: true,
default: false
},
registerAt: {
type: Date,
default: Date.now
}
});
UserSchema.pre('save', async function (next) {
if (!this.isModified('password')) {
return next();
}
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(this.password, salt);
this.password = hash;
next();
});
UserSchema.methods.comparePassword = async function (password) {
return await bcrypt.compare(password, this.password);
}
module.exports = mongoose.model('User', UserSchema);
let { username, password } = req.body;
let user = await User.findOne({ username });
if (!user) {
return next({
status: 400,
message: "User not found"
});
}
try {
let result = await User.comparePassword(password);
} catch ({ message }) {
return next({
status: 400,
message
});
}
let token = await jwt.sign({ _id: user._id }, config.secret);
res.json(user);