Spaces:
Sleeping
Sleeping
File size: 1,887 Bytes
66821dd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | import mongoose from "mongoose";
import crypto from "crypto";
const userSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: 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,
},
sessionToken: {
type: String,
default: null,
},
lastLoginAt: {
type: Date,
default: null,
},
},
{ timestamps: true }
);
userSchema.index({ tenant: 1, role: 1 });
userSchema.pre("save", async function () {
if (!this.isModified("password")) return;
const salt = crypto.randomBytes(16).toString("hex");
const hash = crypto.pbkdf2Sync(this.password, salt, 1000, 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, 1000, 64, "sha512").toString("hex");
return originalHash === attemptHash;
} catch (err) {
return false;
}
};
export default mongoose.model("User", userSchema);
|