forked from dbroqua/MusicTopus
Updated env + Added SignIn/SignUp
This commit is contained in:
parent
2218d2663b
commit
33c87b434c
25 changed files with 625 additions and 41 deletions
58
src/models/users.js
Normal file
58
src/models/users.js
Normal file
|
@ -0,0 +1,58 @@
|
|||
/* eslint-disable func-names */
|
||||
/* eslint-disable no-invalid-this */
|
||||
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,
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
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);
|
Loading…
Add table
Add a link
Reference in a new issue