Files
Checkmate/server/db/models/User.js
T

92 lines
1.6 KiB
JavaScript
Raw Normal View History

2025-04-20 11:29:53 -07:00
import mongoose from "mongoose";
2025-04-25 12:46:35 -07:00
import bcrypt from "bcryptjs";
2025-04-20 11:29:53 -07:00
import logger from "../../utils/logger.js";
const UserSchema = mongoose.Schema(
{
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
avatarImage: {
type: String,
},
profileImage: {
data: Buffer,
contentType: String,
},
isActive: {
type: Boolean,
default: true,
},
isVerified: {
type: Boolean,
default: false,
},
role: {
type: [String],
default: "user",
enum: ["user", "admin", "superadmin", "demo"],
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
},
checkTTL: {
type: Number,
},
},
{
timestamps: true,
}
);
2025-04-25 12:46:35 -07:00
UserSchema.pre("save", function (next) {
2025-04-20 11:29:53 -07:00
if (!this.isModified("password")) {
2025-04-25 12:46:35 -07:00
return next();
2025-04-20 11:29:53 -07:00
}
2025-04-25 12:46:35 -07:00
const salt = bcrypt.genSaltSync(10);
this.password = bcrypt.hashSync(this.password, salt);
2025-04-20 11:29:53 -07:00
next();
});
2025-04-25 12:46:35 -07:00
UserSchema.pre("findOneAndUpdate", function (next) {
2025-04-20 11:29:53 -07:00
const update = this.getUpdate();
if ("password" in update) {
2025-04-25 12:46:35 -07:00
const salt = bcrypt.genSaltSync(10);
update.password = bcrypt.hashSync(update.password, salt);
2025-04-20 11:29:53 -07:00
}
next();
});
UserSchema.methods.comparePassword = async function (submittedPassword) {
const res = await bcrypt.compare(submittedPassword, this.password);
return res;
};
const User = mongoose.model("User", UserSchema);
User.init().then(() => {
logger.info({
message: "User model initialized",
service: "UserModel",
method: "init",
});
});
2025-04-25 12:46:35 -07:00
export default User;