Explorar el Código

RHL-003-feat(user): implement user model with roles and password management

Code_Uwe hace 1 semana
padre
commit
00027bb0fc
Se han modificado 1 ficheros con 89 adiciones y 0 borrados
  1. 89 0
      models/user.js

+ 89 - 0
models/user.js

@@ -0,0 +1,89 @@
+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;