Skip to content

Instantly share code, notes, and snippets.

@mkhizeryounas
Last active August 18, 2018 22:09
Show Gist options
  • Save mkhizeryounas/01523e3d46ce100b28d258c594f0db65 to your computer and use it in GitHub Desktop.
Save mkhizeryounas/01523e3d46ce100b28d258c594f0db65 to your computer and use it in GitHub Desktop.
const bcrypt = require("bcryptjs");
module.exports = {
attributes: {
name: { type: "String", required: true },
email: { type: "String", unique: true, required: true },
password: { type: "String", required: true },
phone: { type: "String", required: true }
},
beforeCreate: (user, next) => {
bcrypt.genSalt(10, (error, salt) => {
if (error) {
return next(error);
}
bcrypt.hash(user.password, salt, (error, hash) => {
if (error) {
return next(error);
}
user.password = hash;
next();
});
});
},
beforeUpdate: (user, next) => {
bcrypt.genSalt(10, (error, salt) => {
if (error) {
return next(error);
}
bcrypt.hash(user.password, salt, (error, hash) => {
if (error) {
return next(error);
}
user.password = hash;
next();
});
});
},
customToJSON() {
delete this.password;
return this;
},
async checkIfPasswordIsValid(password, user) {
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, async (error, isMatch) => {
if (error) {
reject("Error occoured while checking password");
}
if (isMatch) {
resolve(true);
} else {
reject("Invalid password entered");
}
});
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment