| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- import mongoose from "mongoose";
- const { Schema, models, model } = mongoose;
- export const USER_ROLES = Object.freeze({
- BRANCH: "branch",
- ADMIN: "admin",
- 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;
|