From 52e5b834d485a0b2bc2c07c5e652372e442bd35f Mon Sep 17 00:00:00 2001 From: phgkfux43 <3469266505@qq.com> Date: Sat, 26 Apr 2025 22:39:02 +0800 Subject: [PATCH] ADD file via upload --- User.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 User.js diff --git a/User.js b/User.js new file mode 100644 index 0000000..981e48c --- /dev/null +++ b/User.js @@ -0,0 +1,44 @@ +const mongoose = require('mongoose'); +const bcrypt = require('bcryptjs'); + +const userSchema = new mongoose.Schema({ + username: { + type: String, + required: true, + unique: true, + trim: true + }, + password: { + type: String, + required: true + }, + role: { + type: String, + enum: ['student', 'teacher', 'admin'], + default: 'student' + }, + createdAt: { + type: Date, + default: Date.now + } +}); + +// 密码加密中间件 +userSchema.pre('save', async function (next) { + if (!this.isModified('password')) return next(); + + try { + const salt = await bcrypt.genSalt(10); + this.password = await bcrypt.hash(this.password, salt); + next(); + } catch (err) { + next(err); + } +}); + +// 密码验证方法 +userSchema.methods.comparePassword = async function (candidatePassword) { + return await bcrypt.compare(candidatePassword, this.password); +}; + +module.exports = mongoose.model('User', userSchema); \ No newline at end of file