Reviewed-on: https://git.darkou.fr/dbroqua/MusicTopus/pulls/91 Co-authored-by: dbroqua <contact@darkou.fr> Co-committed-by: dbroqua <contact@darkou.fr>
78 lines
1.9 KiB
JavaScript
78 lines
1.9 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,
|
|
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);
|