Create USER with bcrypt and authenticate
This is my user.js file, where i handle two requestes.
First the POST /signup, where the user enters an email, and a password so that i can store it in mongodb.
var express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
var bcrypt = require("bcrypt");
var jwt = require("jsonwebtoken");
var User = require("../models/user");
router.post("/signup", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "User created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
});
}
});
});
Second the POST /login, where the user enters an email, and the password and with bcrypt i compare if the password matches the one in the db.
router.post("/login", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length < 1) {
return res.status(401).json({
message: "Auth failed"
});
}
bcrypt.compare(req.body.password, user[0].password, (err, result) => {
if (err) {
return res.status(401).json({
message: "Auth failed"
});
}
if (result) {
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id
},
process.env.JWT_KEY,
{
expiresIn: "1h"
}
);
return res.status(200).json({
message: "Auth successful",
token: token
});
}
res.status(401).json({
message: "Auth failed"
});
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
The problem is the following: Whenever i try to create a user /signup using postman the request stays in "loading" and the server shuts down.
POSTMAN body: {
'emial': 'teste@gmail.com',
'password': '12345'
}
Error in the server:
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [node-rest-shop-shard-00-01-pbcph.azure.mongodb.net:27017] on first connect [MongoNetworkError: connection 4 to node-rest-shop-shard-00-01-pbcph.azure.mongodb.net:27017 timed out]
(node:1496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1496) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
node.js mongodb bcrypt
add a comment |
This is my user.js file, where i handle two requestes.
First the POST /signup, where the user enters an email, and a password so that i can store it in mongodb.
var express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
var bcrypt = require("bcrypt");
var jwt = require("jsonwebtoken");
var User = require("../models/user");
router.post("/signup", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "User created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
});
}
});
});
Second the POST /login, where the user enters an email, and the password and with bcrypt i compare if the password matches the one in the db.
router.post("/login", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length < 1) {
return res.status(401).json({
message: "Auth failed"
});
}
bcrypt.compare(req.body.password, user[0].password, (err, result) => {
if (err) {
return res.status(401).json({
message: "Auth failed"
});
}
if (result) {
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id
},
process.env.JWT_KEY,
{
expiresIn: "1h"
}
);
return res.status(200).json({
message: "Auth successful",
token: token
});
}
res.status(401).json({
message: "Auth failed"
});
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
The problem is the following: Whenever i try to create a user /signup using postman the request stays in "loading" and the server shuts down.
POSTMAN body: {
'emial': 'teste@gmail.com',
'password': '12345'
}
Error in the server:
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [node-rest-shop-shard-00-01-pbcph.azure.mongodb.net:27017] on first connect [MongoNetworkError: connection 4 to node-rest-shop-shard-00-01-pbcph.azure.mongodb.net:27017 timed out]
(node:1496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1496) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
node.js mongodb bcrypt
add a comment |
This is my user.js file, where i handle two requestes.
First the POST /signup, where the user enters an email, and a password so that i can store it in mongodb.
var express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
var bcrypt = require("bcrypt");
var jwt = require("jsonwebtoken");
var User = require("../models/user");
router.post("/signup", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "User created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
});
}
});
});
Second the POST /login, where the user enters an email, and the password and with bcrypt i compare if the password matches the one in the db.
router.post("/login", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length < 1) {
return res.status(401).json({
message: "Auth failed"
});
}
bcrypt.compare(req.body.password, user[0].password, (err, result) => {
if (err) {
return res.status(401).json({
message: "Auth failed"
});
}
if (result) {
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id
},
process.env.JWT_KEY,
{
expiresIn: "1h"
}
);
return res.status(200).json({
message: "Auth successful",
token: token
});
}
res.status(401).json({
message: "Auth failed"
});
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
The problem is the following: Whenever i try to create a user /signup using postman the request stays in "loading" and the server shuts down.
POSTMAN body: {
'emial': 'teste@gmail.com',
'password': '12345'
}
Error in the server:
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [node-rest-shop-shard-00-01-pbcph.azure.mongodb.net:27017] on first connect [MongoNetworkError: connection 4 to node-rest-shop-shard-00-01-pbcph.azure.mongodb.net:27017 timed out]
(node:1496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1496) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
node.js mongodb bcrypt
This is my user.js file, where i handle two requestes.
First the POST /signup, where the user enters an email, and a password so that i can store it in mongodb.
var express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
var bcrypt = require("bcrypt");
var jwt = require("jsonwebtoken");
var User = require("../models/user");
router.post("/signup", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "User created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
});
}
});
});
Second the POST /login, where the user enters an email, and the password and with bcrypt i compare if the password matches the one in the db.
router.post("/login", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length < 1) {
return res.status(401).json({
message: "Auth failed"
});
}
bcrypt.compare(req.body.password, user[0].password, (err, result) => {
if (err) {
return res.status(401).json({
message: "Auth failed"
});
}
if (result) {
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id
},
process.env.JWT_KEY,
{
expiresIn: "1h"
}
);
return res.status(200).json({
message: "Auth successful",
token: token
});
}
res.status(401).json({
message: "Auth failed"
});
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
The problem is the following: Whenever i try to create a user /signup using postman the request stays in "loading" and the server shuts down.
POSTMAN body: {
'emial': 'teste@gmail.com',
'password': '12345'
}
Error in the server:
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [node-rest-shop-shard-00-01-pbcph.azure.mongodb.net:27017] on first connect [MongoNetworkError: connection 4 to node-rest-shop-shard-00-01-pbcph.azure.mongodb.net:27017 timed out]
(node:1496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1496) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
node.js mongodb bcrypt
node.js mongodb bcrypt
asked Nov 26 '18 at 11:01
user10695385
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
The User.find promise is being rejected because Node fails to connect to your MongoDB instance. This rejected promise tries to execute the first error handler that it comes across. In your case, it fails to find any catch() to handle this error. You can avoid this by adding a catch() to the promise chain at the end.
You should also look into why your Node instance cannot make a successful connection to your MongoDB instance.
router.post("/signup", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "User created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
});
}
}).catch(err => { //Handle the error here.
console.log(err);
res.status(500).json({
error: err
});
});
});
You should do the same for your login call.
Sry for the late response, now when i try to /login i receive the following error: Error: secretOrPrivateKey must have a value
– user10695385
Nov 26 '18 at 19:39
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53479724%2fcreate-user-with-bcrypt-and-authenticate%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The User.find promise is being rejected because Node fails to connect to your MongoDB instance. This rejected promise tries to execute the first error handler that it comes across. In your case, it fails to find any catch() to handle this error. You can avoid this by adding a catch() to the promise chain at the end.
You should also look into why your Node instance cannot make a successful connection to your MongoDB instance.
router.post("/signup", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "User created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
});
}
}).catch(err => { //Handle the error here.
console.log(err);
res.status(500).json({
error: err
});
});
});
You should do the same for your login call.
Sry for the late response, now when i try to /login i receive the following error: Error: secretOrPrivateKey must have a value
– user10695385
Nov 26 '18 at 19:39
add a comment |
The User.find promise is being rejected because Node fails to connect to your MongoDB instance. This rejected promise tries to execute the first error handler that it comes across. In your case, it fails to find any catch() to handle this error. You can avoid this by adding a catch() to the promise chain at the end.
You should also look into why your Node instance cannot make a successful connection to your MongoDB instance.
router.post("/signup", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "User created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
});
}
}).catch(err => { //Handle the error here.
console.log(err);
res.status(500).json({
error: err
});
});
});
You should do the same for your login call.
Sry for the late response, now when i try to /login i receive the following error: Error: secretOrPrivateKey must have a value
– user10695385
Nov 26 '18 at 19:39
add a comment |
The User.find promise is being rejected because Node fails to connect to your MongoDB instance. This rejected promise tries to execute the first error handler that it comes across. In your case, it fails to find any catch() to handle this error. You can avoid this by adding a catch() to the promise chain at the end.
You should also look into why your Node instance cannot make a successful connection to your MongoDB instance.
router.post("/signup", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "User created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
});
}
}).catch(err => { //Handle the error here.
console.log(err);
res.status(500).json({
error: err
});
});
});
You should do the same for your login call.
The User.find promise is being rejected because Node fails to connect to your MongoDB instance. This rejected promise tries to execute the first error handler that it comes across. In your case, it fails to find any catch() to handle this error. You can avoid this by adding a catch() to the promise chain at the end.
You should also look into why your Node instance cannot make a successful connection to your MongoDB instance.
router.post("/signup", (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
password: hash
});
user
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "User created"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
});
}
}).catch(err => { //Handle the error here.
console.log(err);
res.status(500).json({
error: err
});
});
});
You should do the same for your login call.
answered Nov 26 '18 at 11:46
Siddharth NayarSiddharth Nayar
28915
28915
Sry for the late response, now when i try to /login i receive the following error: Error: secretOrPrivateKey must have a value
– user10695385
Nov 26 '18 at 19:39
add a comment |
Sry for the late response, now when i try to /login i receive the following error: Error: secretOrPrivateKey must have a value
– user10695385
Nov 26 '18 at 19:39
Sry for the late response, now when i try to /login i receive the following error: Error: secretOrPrivateKey must have a value
– user10695385
Nov 26 '18 at 19:39
Sry for the late response, now when i try to /login i receive the following error: Error: secretOrPrivateKey must have a value
– user10695385
Nov 26 '18 at 19:39
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53479724%2fcreate-user-with-bcrypt-and-authenticate%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown