MusicTopus/src/models/users.js
2024-02-01 08:47:33 +01:00

83 lines
2.0 KiB
JavaScript

/* eslint-disable func-names */
/* eslint-disable no-invalid-this */
/* eslint-disable no-param-reassign */
import mongoose from "mongoose";
import uniqueValidator from "mongoose-unique-validator";
import crypto from "crypto";
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
unique: true,
required: [true, "est requis"],
match: [/^[a-zA-Z0-9]+$/, "est invalide"],
index: true,
},
email: {
type: String,
lowercase: true,
unique: true,
required: [true, "est requis"],
match: [/\S+@\S+\.\S+/, "est invalide"],
index: true,
},
hash: String,
salt: String,
pagination: {
type: Number,
default: 16,
},
isPublicCollection: {
type: Boolean,
default: false,
},
mastodon: {
publish: Boolean,
token: String,
url: String,
message: String,
},
},
{
timestamps: true,
toJSON: {
transform(doc, ret) {
delete ret.hash;
delete ret.salt;
},
},
}
);
UserSchema.plugin(uniqueValidator, { message: "est déjà utilisé" });
UserSchema.methods.validPassword = function (password) {
const [salt, key] = this.hash.split(":");
return key === crypto.scryptSync(password, salt, 64).toString("hex");
};
UserSchema.pre("save", function (next) {
const user = this;
if (!user.isModified("salt")) {
return next();
}
const salt = crypto.randomBytes(16).toString("hex");
return crypto.scrypt(user.salt, salt, 64, (err, derivedKey) => {
if (err) {
next(err);
}
this.salt = salt;
this.hash = `${salt}:${derivedKey.toString("hex")}`;
next();
});
});
export default mongoose.model("Users", UserSchema);