Skip to content

Commit bf826b9

Browse files
author
Mohammed Othman
authored
Merge pull request #18 from mohammedothman7/hash
Hashing for passwords
2 parents 01de30f + 6a4373f commit bf826b9

File tree

2 files changed

+35
-20
lines changed

2 files changed

+35
-20
lines changed

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
},
1010
"dependencies": {
1111
"axios": "^0.19.2",
12+
"bcrypt": "^5.0.0",
1213
"body-parser": "^1.19.0",
1314
"compression": "^1.7.4",
1415
"cookie-parser": "~1.4.4",

routes/users.js

+34-20
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
var express = require("express");
2+
const bcrypt = require('bcrypt')
23
var router = express.Router();
34
const { User } = require("../database/models");
45

@@ -21,14 +22,21 @@ router.get("/", async (req, res, next) => {
2122
/* GET a user with specific credentials. */
2223
router.get("/:username/:password", async (req, res, next) => {
2324
try {
25+
// Getting user from database by username
2426
const user = await User.findOne({
2527
where: {
2628
username: req.params.username,
27-
password: req.params.password,
2829
},
2930
});
30-
console.log(user);
31-
res.status(200).json(user);
31+
32+
// Verifying password matches hashed
33+
bcrypt.compare(req.params.password, user.password, function(err, response) {
34+
if(response){
35+
res.status(200).json(user);
36+
} else {
37+
res.status(401).json();
38+
}
39+
})
3240
} catch (err) {
3341
next(err);
3442
}
@@ -39,24 +47,30 @@ router.get("/:username/:password", async (req, res, next) => {
3947
router.post("/", async (req, res, next) => {
4048
// Take the form data from the request body
4149
const { firstName, lastName, email, username, password } = req.body;
42-
// Create a user object
43-
const userObj = {
44-
firstName: firstName,
45-
lastName: lastName,
46-
email: email,
47-
username: username,
48-
password: password,
49-
};
5050

51-
try {
52-
// Create a new user on the database
53-
const newUser = await User.create(userObj);
54-
// The database would return a user
55-
// send that user as a json to the client
56-
res.status(201).send(newUser);
57-
} catch (err) {
58-
next(err);
59-
}
51+
// Hashing password
52+
bcrypt.hash(password, 10, async function(err, hash) {
53+
if (err) next(err);
54+
55+
// Create a user object
56+
const userObj = {
57+
firstName: firstName,
58+
lastName: lastName,
59+
email: email,
60+
username: username,
61+
password: hash,
62+
};
63+
64+
try {
65+
// Create a new user on the database
66+
const newUser = await User.create(userObj);
67+
// The database would return a user
68+
// send that user as a json to the client
69+
res.status(201).send(newUser);
70+
} catch (err) {
71+
next(err);
72+
}
73+
});
6074
});
6175

6276
module.exports = router;

0 commit comments

Comments
 (0)