api/resources/user/userModel.js

89 lines
2.4 KiB
JavaScript

import dotenv from "dotenv";
dotenv.config();
import mongoose from "mongoose";
import validator from "validator";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import crypto from "crypto";
const userSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, "Please Enter Your Name"],
maxLength: [30, "Name cannot exceed 30 characters"],
minLength: [4, "Name should have more than 4 characters"],
},
email: {
type: String,
required: [true, "Please Enter Your Email"],
unique: true,
validate: [validator.isEmail, "Please Enter a valid Email"],
},
phone: { // Change to 'mobileno' to match frontend field
type: String,
required: [true, "Please Enter Your phone no."],
validate: {
validator: function (v) {
return /^\d{10}$/.test(v);
},
message: "Please enter a valid 10-digit phone number",
},
},
password: {
type: String,
required: [true, "Please Enter Your Password"],
minLength: [6, "Password should be greater than 6 characters"],
select: false,
},
avatar: {
public_id: {
type: String,
default: "",
},
url: {
type: String,
default: "",
},
},
role: {
type: String,
default: "principal-Distributor",
},
accessTo: {},
resetPasswordToken: String,
resetPasswordExpire: Date,
},
{ timestamps: true }
);
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) {
next();
}
this.password = await bcrypt.hash(this.password, 10);
});
// JWT TOKEN
userSchema.methods.getJWTToken = function () {
return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_TIME,
});
};
// Compare Password
userSchema.methods.comparePassword = async function (password) {
return await bcrypt.compare(password, this.password);
};
// Generating Reset Token
userSchema.methods.getResetPasswordToken = function () {
const resetToken = crypto.randomBytes(20).toString("hex");
this.resetPasswordToken = crypto.createHash("sha256").update(resetToken).digest("hex");
this.resetPasswordExpire = Date.now() + 15 * 60 * 1000; // 15 minutes
return resetToken;
};
const User = mongoose.model("User", userSchema);
export default User;