78 lines
2.5 KiB
JavaScript
78 lines
2.5 KiB
JavaScript
|
import mongoose from "mongoose";
|
||
|
import validator from "validator";
|
||
|
import bcrypt from "bcrypt";
|
||
|
import ModelNameRegister from "./ModelNameRegister.js";
|
||
|
|
||
|
const Types = mongoose.Schema.Types;
|
||
|
|
||
|
const userSchema = new mongoose.Schema({
|
||
|
email: {
|
||
|
value: {
|
||
|
type: String,
|
||
|
required: true,
|
||
|
minlength: 1,
|
||
|
trim: true,
|
||
|
unique: true,
|
||
|
validate: {
|
||
|
validator: validator.isEmail,
|
||
|
message: "String not email.",
|
||
|
}
|
||
|
},
|
||
|
public: { type: Boolean, required: true, default: false }
|
||
|
},
|
||
|
firstName: {
|
||
|
value: { type: String, required: true, trim: true },
|
||
|
public: { type: Boolean, required: true, default: false }
|
||
|
},
|
||
|
lastName: {
|
||
|
value: { type: String, required: true, trim: true },
|
||
|
public: { type: Boolean, required: true, default: false }
|
||
|
},
|
||
|
joinDate: { type: Date, default: Date.now, required: true },
|
||
|
phone: {
|
||
|
value: { type: Number, required: false, min: 0 },
|
||
|
public: { type: Boolean, required: true, default: false }
|
||
|
},
|
||
|
password: {
|
||
|
type: String,
|
||
|
required: true,
|
||
|
minlength: 8
|
||
|
// TODO: Custom validator for password requirements?
|
||
|
},
|
||
|
createdMatches: { type: [{ type: Types.ObjectId, ref: ModelNameRegister.Match }], required: true, default: [] },
|
||
|
participatingMatches: {
|
||
|
value: { type: [{ type: Types.ObjectId, ref: ModelNameRegister.Match }], required: true, default: [] },
|
||
|
public: { type: Boolean, required: true, default: false }
|
||
|
},
|
||
|
accessLevel: { type: Number, required: true, default: 0 }
|
||
|
});
|
||
|
|
||
|
userSchema.statics.credentialsExist = async function (email, password) {
|
||
|
let userModel = this;
|
||
|
let user = await userModel.findOne({ "email.value": email });
|
||
|
if (!user) {
|
||
|
return Promise.reject(new Error("Credentials do not exist."));
|
||
|
}
|
||
|
if (await bcrypt.compare(password, user.password)) {
|
||
|
return user;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
userSchema.pre("save", function (next) {
|
||
|
let user = this;
|
||
|
if (user.isModified("password")) { // Only perform hashing if the password has changed.
|
||
|
bcrypt.genSalt(10, (err, salt) => {
|
||
|
bcrypt.hash(user.password, salt, (err, hash) => {
|
||
|
if (err) {
|
||
|
throw err; // Probably not, but I'm gonna leave this here for now.
|
||
|
}
|
||
|
user.password = hash;
|
||
|
next();
|
||
|
});
|
||
|
});
|
||
|
} else {
|
||
|
next();
|
||
|
}
|
||
|
});
|
||
|
|
||
|
export default mongoose.model(ModelNameRegister.User, userSchema);
|