user.js 1.5 KB

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