Commit 11ac71eb authored by Balasuriya D.A.M.'s avatar Balasuriya D.A.M.

Password Encryption with Bcrypt

parent 3b725380
...@@ -49,7 +49,7 @@ const authUser = asyncHandler(async (req, res) => { ...@@ -49,7 +49,7 @@ const authUser = asyncHandler(async (req, res) => {
const user = await User.findOne({ email }); const user = await User.findOne({ email });
//If user is already exist check it with DB data such as password //If user is already exist check it with DB data such as password
if (user) { if (user && (await user.matchPassword(password))) {
res.json({ res.json({
_id: user._id, _id: user._id,
name: user.name, name: user.name,
...@@ -63,4 +63,4 @@ const authUser = asyncHandler(async (req, res) => { ...@@ -63,4 +63,4 @@ const authUser = asyncHandler(async (req, res) => {
} }
}); });
module.exports = { registerUser }; module.exports = { registerUser, authUser };
\ No newline at end of file \ No newline at end of file
const mongoose = require("mongoose"); const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const userSchema = mongoose.Schema({ const userSchema = mongoose.Schema({
name: { type: String, required: true }, name: { type: String, required: true },
...@@ -14,6 +15,22 @@ const userSchema = mongoose.Schema({ ...@@ -14,6 +15,22 @@ const userSchema = mongoose.Schema({
{timestamps:true} {timestamps:true}
); );
userSchema.methods.matchPassword = async function (enteredPassword) {
//Verify Password
return await bcrypt.compare(enteredPassword, this.password);
};
//I add the .pre becouse before goint to database saving
userSchema.pre("save", async function (next) {
if (!this.isModified) {
next();
}
const salt = await bcrypt.genSalt(10); // generate strongest new salt
this.password = await bcrypt.hash(this.password, salt); //add Hash and bcrypt
});
const User = mongoose.model("User", userSchema); const User = mongoose.model("User", userSchema);
module.exports = User; module.exports = User;
\ No newline at end of file
const express = require("express"); const express = require("express");
const { registerUser } = require("../controllers/userControllers"); const { registerUser,authUser } = require("../controllers/userControllers");
const router = express.Router(); const router = express.Router();
router.route("/").post(registerUser); router.route("/").post(registerUser);
router.post("/login", authUser); router.post("/login",authUser );
module.exports = router; module.exports = router;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment