user.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import mongoose from "mongoose";
  2. const { Schema, models, model } = mongoose;
  3. export const USER_ROLES = Object.freeze({
  4. BRANCH: "branch",
  5. ADMIN: "admin",
  6. SUPERADMIN: "superadmin",
  7. DEV: "dev",
  8. });
  9. const userSchema = new Schema(
  10. {
  11. username: {
  12. type: String,
  13. required: true,
  14. unique: true,
  15. index: true,
  16. trim: true,
  17. lowercase: true,
  18. minlength: 3,
  19. maxlength: 100,
  20. },
  21. email: {
  22. type: String,
  23. required: true,
  24. unique: true,
  25. index: true,
  26. trim: true,
  27. lowercase: true,
  28. maxlength: 200,
  29. },
  30. passwordHash: {
  31. type: String,
  32. required: true,
  33. },
  34. role: {
  35. type: String,
  36. required: true,
  37. enum: Object.values(USER_ROLES),
  38. },
  39. branchId: {
  40. type: String,
  41. default: null,
  42. validate: {
  43. validator: function (value) {
  44. if (this.role === USER_ROLES.BRANCH) {
  45. return typeof value === "string" && value.trim().length > 0;
  46. }
  47. return true;
  48. },
  49. message: "branchId is required for branch users",
  50. },
  51. },
  52. mustChangePassword: {
  53. type: Boolean,
  54. default: false,
  55. },
  56. passwordResetToken: {
  57. type: String,
  58. default: null,
  59. },
  60. passwordResetExpiresAt: {
  61. type: Date,
  62. default: null,
  63. },
  64. },
  65. {
  66. timestamps: true,
  67. toJSON: {
  68. transform(doc, ret) {
  69. delete ret.passwordHash;
  70. delete ret.passwordResetToken;
  71. return ret;
  72. },
  73. },
  74. toObject: {
  75. transform(doc, ret) {
  76. delete ret.passwordHash;
  77. delete ret.passwordResetToken;
  78. return ret;
  79. },
  80. },
  81. },
  82. );
  83. // Avoid model overwrite issues in Next.js dev / hot reload
  84. const User = models.User || model("User", userSchema);
  85. export default User;