import mongoose from "mongoose"; import crypto from "crypto"; const userSchema = new mongoose.Schema( { username: { type: String, required: true, trim: true, }, fullName: { type: String, trim: true, default: "", }, email: { type: String, trim: true, lowercase: true, unique: true, sparse: true, }, phone: { type: String, trim: true, default: "", }, password: { type: String, required: true, }, role: { type: String, enum: ["super_admin", "owner", "admin", "cashier"], default: "cashier", }, status: { type: String, enum: ["active", "suspended"], default: "active", }, tenant: { type: mongoose.Schema.Types.ObjectId, ref: "Tenant", default: null, }, assignedBranch: { type: mongoose.Schema.Types.ObjectId, ref: "Branch", default: null, }, sessionToken: { type: String, default: null, }, sessionTokenExpiresAt: { type: Date, default: null, }, lastLoginAt: { type: Date, default: null, }, failedLoginAttempts: { type: Number, default: 0, }, lockedUntil: { type: Date, default: null, }, }, { timestamps: true } ); userSchema.index({ tenant: 1, role: 1 }); userSchema.index({ tenant: 1, username: 1 }, { unique: true }); userSchema.index({ tenant: 1, assignedBranch: 1, role: 1 }); userSchema.index({ sessionToken: 1 }, { sparse: true }); // protect() runs this query on EVERY request const PBKDF2_ITERATIONS = 100000; // OWASP minimum for PBKDF2-SHA512 userSchema.pre("save", async function () { if (!this.isModified("password")) return; const salt = crypto.randomBytes(16).toString("hex"); const hash = crypto.pbkdf2Sync(this.password, salt, PBKDF2_ITERATIONS, 64, "sha512").toString("hex"); this.password = `${salt}:${hash}`; }); userSchema.methods.matchPassword = function (enteredPassword) { try { const [salt, originalHash] = this.password.split(":"); const attemptHash = crypto.pbkdf2Sync(enteredPassword, salt, PBKDF2_ITERATIONS, 64, "sha512").toString("hex"); return originalHash === attemptHash; } catch (err) { return false; } }; export default mongoose.model("User", userSchema);