Skip to content

Commit f34f53d

Browse files
Implemented hashing and dehashing while signup and sign in with bcrypt js..
1 parent efc6251 commit f34f53d

File tree

4 files changed

+39
-3
lines changed

4 files changed

+39
-3
lines changed

models/user.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const {connector} = require('./databaseUtil');
2-
2+
const {hashPassword,comparePasswords} = require("../util");
33
const userSchema = {
44
name: {type: String, required: true},
55
emailId: {type: String, unique: true, required: true},
@@ -19,6 +19,11 @@ async function createUser(name, password, emailId, uid, userType){
1919
uid: uid,
2020
userType: userType
2121
});
22+
23+
//hash the password
24+
const hashedPassword = await hashPassword(user.password);
25+
user.password = hashedPassword;
26+
2227
let newUser = {};
2328
await user.save().then((savedUser) => {
2429
newUser = savedUser ;
@@ -30,7 +35,7 @@ async function createUser(name, password, emailId, uid, userType){
3035
async function validateUser(uid, pass){
3136
let user = await User.findOne({uid: uid}).catch(err=>console.log(err))
3237
if(user){
33-
if(user.password==pass)
38+
if(comparePasswords(pass,user.password))
3439
return user
3540
return null;
3641
}

package-lock.json

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
"serverstartWin": "SET DEBUG=api:* && npm run devstart"
1010
},
1111
"dependencies": {
12+
"bcryptjs": "^2.4.3",
1213
"cookie-parser": "~1.4.4",
1314
"cors": "^2.8.5",
1415
"debug": "~2.6.9",

util.js

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,33 @@
11
const jwt = require("jsonwebtoken");
2-
2+
const bcrypt = require("bcryptjs");
33
exports.genrateToken = (data)=>{
44
return jwt.sign(data, process.env.TOKEN_SECRET);
55
}
66

7+
exports.hashPassword = async(password) =>{
8+
try {
9+
const salt = await bcrypt.genSalt(10);
10+
const hashedPassword = await bcrypt.hash(password,salt);
11+
return hashedPassword;
12+
} catch (error) {
13+
return error.message;
14+
}
15+
}
16+
17+
exports.comparePasswords = async(userPassword,storedPassword) =>{
18+
try {
19+
bcrypt.compare(userPassword,storedPassword,(err,success)=>{
20+
if(err) throw Error();
21+
if(success){
22+
return true;
23+
}
24+
else return false;
25+
})
26+
} catch (error) {
27+
return error.message;
28+
}
29+
}
30+
731
/**
832
*
933
* @param {*} data any data that you want as return from the function after mentioned time

0 commit comments

Comments
 (0)