| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- import mongoose from "mongoose";
- const { Schema, models, model } = mongoose;
- export const USER_ROLES = Object.freeze({
- BRANCH: "branch",
- ADMIN: "admin",
- SUPERADMIN: "superadmin",
- DEV: "dev",
- });
- const userSchema = new Schema(
- {
- username: {
- type: String,
- required: true,
- unique: true,
- index: true,
- trim: true,
- lowercase: true,
- minlength: 3,
- maxlength: 100,
- },
- email: {
- type: String,
- required: true,
- unique: true,
- index: true,
- trim: true,
- lowercase: true,
- maxlength: 200,
- },
- passwordHash: {
- type: String,
- required: true,
- },
- role: {
- type: String,
- required: true,
- enum: Object.values(USER_ROLES),
- },
- branchId: {
- type: String,
- default: null,
- validate: {
- validator: function (value) {
- if (this.role === USER_ROLES.BRANCH) {
- return typeof value === "string" && value.trim().length > 0;
- }
- return true;
- },
- message: "branchId is required for branch users",
- },
- },
- mustChangePassword: {
- type: Boolean,
- default: false,
- },
- passwordResetToken: {
- type: String,
- default: null,
- },
- passwordResetExpiresAt: {
- type: Date,
- default: null,
- },
- },
- {
- timestamps: true,
- toJSON: {
- transform(doc, ret) {
- delete ret.passwordHash;
- delete ret.passwordResetToken;
- return ret;
- },
- },
- toObject: {
- transform(doc, ret) {
- delete ret.passwordHash;
- delete ret.passwordResetToken;
- return ret;
- },
- },
- },
- );
- // Avoid model overwrite issues in Next.js dev / hot reload
- const User = models.User || model("User", userSchema);
- export default User;
|