const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const userSchema = new mongoose.Schema({ fullName: { type: String, required: true, trim: true }, email: { type: String, required: true, unique: true, trim: true, lowercase: true }, username: { type: String, required: true, unique: true, trim: true }, password: { type: String, required: true }, role: { type: String, enum: ['admin', 'moderator', 'editor', 'user'], default: 'user' }, agreedToRules: { type: Boolean, required: true } }, { timestamps: true }); // Hash password before saving userSchema.pre('save', async function () { if (!this.isModified('password')) { return; } try { const salt = await bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); } catch (error) { throw error; } }); // Compare password method userSchema.methods.comparePassword = async function (candidatePassword) { return await bcrypt.compare(candidatePassword, this.password); }; module.exports = mongoose.model('User', userSchema);