Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hashed password before saving in DB #269

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion server/controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,21 @@ const registerUser = async (req, res) => {
const loginUser = async (req, res) => {
const { email, password } = req.body;
try {
const user = await UserModel.findOne({ email: email, password: password });
const user = await UserModel.findOne({ email: email });
if (!user) {
return res.status(404).json({
status: 'notfound',
error: 'No user found'
});
}
//since the Passwored is hashed we need to validate the hashed paswword ...
const validatePassword = user.checkPassword(password) ;
if (!validatePassword) {
return res.status(401).json({
message: 'Invalid credentials',
status: 'error'
});
}

const token = jwt.sign({ email: email }, process.env.SECRET_JWT);
return res.status(200).json({
Expand Down
18 changes: 18 additions & 0 deletions server/models/user.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const mongoose = require('mongoose');
const { model, Schema } = mongoose;
const bcrypt = require('bcrypt'); //for hashing the password

const UserSchema = new Schema({
name: {
Expand Down Expand Up @@ -66,6 +67,23 @@ const UserSchema = new Schema({
}
}, { collection: 'users' });

//hashing the password before saving it to the database.

UserSchema.pre("save",async function(next){
//if the password field is not modified .
if(!this.isModified('password')) return next () ;

//this will run 1.For the first time 2.When the paswword is updated

this.password = await bcrypt.hash(this.password, 10);
next();
})
UserSchema.methods.checkPassword = async function(password){
return await bcrypt.compare(password, this.password); //this.password is the password from the database. this.password is the password from the request.
}



const UserModel = model('User', UserSchema);

module.exports = UserModel;
Loading