I don't understand it. I am not able to login. User is already in my database, and when I log in, it simply says:
POST http://localhost:3000/api/v1/users/login 402 (Payment Required)
When I register for the first time, and then login, login is successful. If I logout, and then try to log in with that same email and password, it's throwing me the above error. I'm not even using someone's API. It's my own created one. It's sending me a response of "incorrect password"
Here's the controller:
loginUser: (req, res, next) => {
const { email, password } = req.body
if (!email || !password) {
return res.status(400).json({ message: "Email and password are must" })
}
User.findOne({ email }, (err, user) => {
if (err) {
return next(err)
} else if (!validator.isEmail(email)) {
return res.status(400).json({ message: "Invalid email" })
} else if (!user) {
return res.status(402).json({ error: "User not found" })
} else if (!user.confirmPassword(password)) {
return res.status(402).json({ error: "incorrect password" })
}
})
}
User model
const mongoose = require("mongoose")
const bcrypt = require("bcrypt")
const Schema = mongoose.Schema
const userSchema = new Schema({
username: { type: String, required: true },
email: { type: String, reuired: true },
password: { type: String, required: true },
posts:[{ type: Schema.Types.ObjectId, ref: "Post" }]
}, { timestamps: true })
userSchema.pre("save", function (next) {
if (this.password) {
const salt = bcrypt.genSaltSync(10)
this.password = bcrypt.hashSync(this.password, salt)
}
next()
})
userSchema.methods.confirmPassword = function (password) {
return bcrypt.compareSync(password, this.password)
}
const User = mongoose.model("User", userSchema)
module.exports = User
registration controller
registerUser: (req, res) => {
const { username, email, password } = req.body
User.create(req.body, (err, createdUser) => {
if (err) {
return res.status(500).json({ error: "Server error occurred" })
} else if (!username || !email || !password) {
return res.status(400).json({ message: "Username, email and password are must" })
} else if (!validator.isEmail(email)) {
return res.status(400).json({ message: "Invaid email" })
} else if (password.length < 6) {
return res.status(400).json({ message: "Password should be of at least 6 characters" })
}
else {
return res.status(200).json({ user: createdUser })
}
})
}
Edit
loginUser: async (req, res, next) => {
const { email, password } = req.body
if (!email || !password) {
return res.status(400).json({ message: "Email and password are must" })
}
await User.findOne({ email }, (err, user) => {
if (err) {
return next(err)
} else if (!validator.isEmail(email)) {
return res.status(400).json({ message: "Invalid email" })
} else if (!user) {
return res.status(402).json({ error: "User not found" })
} else if (!user.confirmPassword(password)) {
return res.status(402).json({ error: "incorrect password" })
}
})
}
new post controller
newPost: (req, res) => {
const data = {
title: req.body.title,
content: req.body.content,
user: req.user.userId
}
Post.create(data, (err, newPost) => {
if (err) {
return res.status(500).json({ error: err })
} else if (!newPost) {
return res.status(400).json({ message: "No Post found" })
} else if (newPost) {
User.findById(req.user.userId, (err, user) => {
user.posts.push(newPost._id) //pushing posts documnet objectid to the post array of the user document
user
.save()
.then(() => {
return res.json(200).json({ user })
})
.catch(err => {
return res.status(500).json({ error: err })
})
})
}
})
}
You might want to refactor your code so that you do the bcrypt operations in controller not in the model. You are checking this.password after the user is updated (creating new posts) and since this is the user, the below code is being met each time you update the user object.
if (this.password) {
const salt = bcrypt.genSaltSync(10)
this.password = bcrypt.hashSync(this.password, salt)
}
So your hashing it every time you update the user (create a post). Instead, remove the above code from the userSchema.pre(...) and try doing the bcrypt hashing only when the user first registers.
registerUser: (req, res) => {
var { username, email, password } = req.body
if (password) {
const salt = bcrypt.genSaltSync(10)
password = bcrypt.hashSync(password, salt)
}
User.create(req.body, (err, createdUser) => {
if (err) {
return res.status(500).json({ error: "Server error occurred" })
} else if (!username || !email || !password) {
return res.status(400).json({ message: "Username, email and password are must" })
} else if (!validator.isEmail(email)) {
return res.status(400).json({ message: "Invaid email" })
} else if (password.length < 6) {
return res.status(400).json({ message: "Password should be of at least 6 characters" })
}
else {
return res.status(200).json({ user: createdUser })
}
})
}
This way the hashing occurs only once at the creation of the user and should remain consistent throughout other operations.
As for the Can't set headers after they are sent error, you might be sending a response twice, since the error appears to come from the posts controller. You are likely sending the user response and the post response. Maybe don't send the posts response since you will be sending it along in the user response.
More info on the error here.
Related
I've been struggling with Bcrypt on my MERN project I'm trying to create an authentication system I'm trying to run tests on Postman and I'm not sure why do I keep getting the error: "Illegal arguments: undefined, string at Object.bcrypt.hashSync"
this is my postman request:
this is the Controller Code:
const config = require("../config/auth.config");
const db = require("../models");
const User = db.user;
const Role = db.role;
var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");
exports.signup = (req, res) => {
const user = new User({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
});
user.save((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (req.body.roles) {
Role.find(
{
name: { $in: req.body.roles },
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = roles.map((role) => role._id);
user.save((err) => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({ message: "User was registered successfully!" });
});
}
);
} else {
Role.findOne({ name: "user" }, (err, role) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = [role._id];
user.save((err) => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({ message: "User was registered successfully!" });
});
});
}
});
};
exports.signin = (req, res) => {
User.findOne({
username: req.body.username,
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({ message: "Invalid Password!" });
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400, // 24 hours
});
var authorities = [];
for (let i = 0; i < user.roles.length; i++) {
authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
}
req.session.token = token;
res.status(200).send({
id: user._id,
username: user.username,
email: user.email,
roles: authorities,
});
});
};
exports.signout = async (req, res) => {
try {
req.session = null;
return res.status(200).send({ message: "You've been signed out!" });
} catch (err) {
this.next(err);
}
};
The error message:
Illegal arguments: undefined, string at Object.bcrypt.hashSync wants to say that you're passing undefined as an argument to the hashSync function. We need to fix this error.
Take a closer look at this line where the error occurs:
password: bcrypt.hashSync(req.body.password, 8),
req.body.password is undefined, you can verify it by console.log(req.body.password). What's wrong is that you are sending data as URL parameters. So req.body is an empty object and req.body.password is undefined.
In Postman, select the Body tab, choose JSON format, then type your data as a JSON object. Then, in your code, use express.json() middleware to parse requests in JSON format. You'll have the desired output.
You can see my example request in Postman below:
don't know whats going on wrong,when i am trying to post request through postman i am getting an error like "Invalid email or password". in sign in. please help
signup
below is my signup request where i am doing my signup validation.
const User = require('../model/user');
const bcrypt = require('bcryptjs');
exports.signup = (req, res) => {
const { name, email, password } = req.body;
if (!name || !email || !password) {
res.status(422).json({
error: "please add all field"
})
}
User.findOne({ email: email })
.then((SavedUser) => {
if (SavedUser) {
return res.status(400).json({
error: "User already exists that email"
})
}
const user = new User({
email,
password,
name
})
user.save()
.then(user => {
res.json({
message: "saved Successfully"
})
.catch(err => {
console.log(err);
})
})
.catch(err => {
console.log(err);
})
})
}
Signin
below is my signin form where i doing my signin operation
exports.signin = (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
res.status(422).json({
error: "please enter email and password"
})
}
User.findOne({ email: email })
.then(SavedUser => {
if (!SavedUser) {
return res.status(400).json({
error: "invalid email or password"
})
}
bcrypt.compare(password, SavedUser.password)
.then(doMatch => {
if (doMatch) {
res.json({
message: "Successfully Signed in"
})
}
else {
return res.status(422).json({
error: "Invalid email or password"
})
}
})
.catch(err => {
console.log(err);
})
})
}
It seems you're not hasing the password, when creating a new mongoose user-object. Obvioulsy, bcrypt.compare(password, SavedUser.password) will then fail. Try to do it like this (note I'm using async/await here instead of promises directly):
password = await bcrypt.hash(password, 10);
const user = new User({
email,
password,
name
});
you didn't bcrypt your password at the time of saving.
You can make a pre save function in your schema like this.
// Hash the plain text password before saving
User.pre("save", async function (next) {
const user = this;
try {
if (user.isModified("password")) {
user.password = await bcrypt.hash(user.password, 8);
}
next();
} catch (error) {
next(error);
}
});
This API is called when the user tries to register and enter the details. I am looking to see if I can add a condition that says email already exists.
I think I need something like:
const user = await User.find({ email })
if (user) {
res.status(400).json({ message: "User with this already exists" })
}
But I am creating a new user, so where should I place the above query. I'm kind of confused with the order of execution.
module.exports = {
registerUser: async(req, res, next) => {
try {
var {
username,
email,
password
} = req.body
if (password) {
const salt = bcrypt.genSaltSync(10)
password = bcrypt.hashSync(password, salt)
}
if (!username || !email || !password) {
return res
.status(400)
.json({
message: "Username, email and password are must"
})
}
if (!validator.isEmail(email)) {
return res.status(400).json({
message: "Invaid email"
})
}
if (password.length < 6) {
return res
.status(400)
.json({
message: "Password should be of at least 6 characters"
})
}
const user = await User.create({
username,
email,
password
})
if (!user) {
return res.status(404).json({
error: "No user found "
})
}
return res.status(200).json({
user
})
} catch (error) {
return next(error)
}
}
I think the best solution will be to place it before any logic, also I changed res.json in if block to throw because throw stops execution of code below but res.json continues and that can cause potential problems. Also, I change Module.find() to Module.findOne() because find() returns empty array if nothing was found and if([emptyArray]) returns true
module.exports = {
registerUser: async(req, res, next) => {
try {
var {
username,
email,
password
} = req.body
const user = await User.findOne({
email
})
if (user) {
throw 'User with this already exists'
}
if (password) {
const salt = bcrypt.genSaltSync(10)
password = bcrypt.hashSync(password, salt)
}
if (!username || !email || !password) {
return res
.status(400)
.json({
message: "Username, email and password are must"
})
}
if (!validator.isEmail(email)) {
return res.status(400).json({
message: "Invaid email"
})
}
if (password.length < 6) {
return res
.status(400)
.json({
message: "Password should be of at least 6 characters"
})
}
const user = await User.create({
username,
email,
password
})
if (!user) {
return res.status(404).json({
error: "No user found "
})
}
return res.status(200).json({
user
})
} catch (error) {
return next(error)
}
}
Place it inside the try block before the logic for registration because the find has the potentials of throwing and error if the email does not exist.
I am able to register and login to the application but I receive the following server error:
"Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" upon registration. I came across similar questions here but none of them resolved my problem.
authController.js:
const User = require("../models/User");
const jwt = require("jsonwebtoken");
const simplecrypt = require("simplecrypt");
const sc = simplecrypt();
process.env.SECRET_KEY = "secret";
exports.postLogin = (req, res, next) => {
const { username, password } = req.body;
let validationMessages = [];
if (!username || !password) {
validationMessages.push({ message: "Please fill in all fields" });
}
if (password.length < 6) {
validationMessages.push({
message: "Password should be at least 6 characters"
});
}
if (validationMessages.length > 0) {
res.sendStatus(403).json(validationMessages);
} else {
User.findOne({ where: { username: username } })
.then(user => {
if (!user) {
res.sendStatus(400).json({
message: "Invalid username or password"
});
} else if (password == sc.decrypt(user.password)) {
const token = jwt.sign(user.dataValues, process.env.SECRET_KEY, {
expiresIn: 1440 // expires in 24 hours
});
res.send(token);
}
})
.catch(err => {
res.send("Error: " + err);
});
}
};
exports.postRegister = (req, res, next) => {
const { username, password, password2 } = req.body;
let validationMessages = [];
//Check required fields
if (!username || !password || !password2) {
validationMessages.push({ message: "Please fill in all fields" });
}
if (password.length < 6 || password2.length < 6) {
validationMessages.push({
message: "Password should be at least 6 characters"
});
}
if (password !== password2) {
validationMessages.push({
message: "Passwords do not match"
});
}
if (validationMessages.length > 0) {
return res.sendStatus(400).json(validationMessages);
} else {
User.findOne({ where: { username: username } })
.then(user => {
if (user) {
return res.sendStatus(403).json("User already exists");
}
const hashedPassword = sc.encrypt(password);
User.create({ username: username, password: hashedPassword })
.then(user => {
return res.sendStatus(200).send(user);
})
.catch(err => {
throw new Error(err);
});
})
.catch(err => {
throw new Error(err);
});
}
};
exports.getProfile = (req, res, next) => {
const decoded = jwt.verify(
req.headers["authorization"],
process.env.SECRET_KEY
);
User.findOne({
where: {
id: decoded.id
}
})
.then(user => {
if (user) {
res.statusCode(200).json(user);
} else {
throw new Error("User does not exist");
}
})
.catch(err => {
throw new Error(err);
});
};
I am using Node.JS v12.14.0 and Express.JS v4.17.1.
I resolved it myself. My problem was using res.sendStatus which sets the given response HTTP status code and sends its string representation as the response body. res.json will set the content-type response header, but at time time the response will already have been sent to the client. So simply res.send() should replace res.sendStatus().
registerUser: (req, res, next) => {
const { username, email, password } = req.body
User.create(req.body, (err, createdUser) => {
if (err) {
return next(err)
} else if (!username || !email || !password) {
return res.status(400).json({ message: "Username, email and password are must" })
} else if (!validator.isEmail(email)) {
return res.status(400).json({ message: "Invaid email" })
} else if (password.length < 6) {
return res.status(400).json({ message: "Password should be of at least 6 characters" })
}
else {
return res.status(200).json({ user: createdUser })
}
})
},
loginUser: (req, res, next) => {
const { email, password } = req.body
User.findOne({ email }, (err, user) => {
if (err) {
return next(err)
} else if (!user || !password) {
return res.status(400).json({ message: "Email and password are must" })
} else if (!validator.isEmail(email)) {
return res.status(400).json({ message: "Invalid email" })
} else if (!user) {
return res.status(402).json({ error: "User not found" })
} else if (!user.confirmPassword(password)) {
return res.status(402).json({ error: "Incorrect password" })
}
// generate token here
const token = auth.signToken(email)
res.status(200).json({ user, token })
})
},
I want to check if the user is already there in the database, then the user will be able to log in. If not, then the message will be, "You are not registered".Right now, if I'm logging in with different email than the registered email, it's saying email and password are must.
All in all, I need to add proper validations in signup and login form.
handleSubmit = (event) => {
event.preventDefault();
const { email, password } = this.state;
const loginData = {
email: this.state.email,
password: this.state.password
}
if (!email || !password) {
return alert('Email and password are must.');
}
if (password.length < 6) {
return alert('Password must contain 6 characters.');
}
if (!validator.isEmail(email)) {
return alert('Invalid email.');
}
this.props.dispatch(loginUser(loginData))
this.props.history.push("/")
}
In the frontend, I'm redirecting the user to the home page after login. Now the problem is, the user is redirecting no matter what the credentials are. Should I have to add validations here in frontend too?
So your problem is, in the loginUser, before the condition reaches to !user, it will first enter into !user || !password. Thats why it keeps saying "Email and password are must."
Your logic would be like this:
If user does not provide any email or password, you should return "Email and password are must" immediately, you do not wany to check in database anymore since, they provide nothing its meanless to do db search.
If user do provide email and password, now you can do db check, if there is no match with the user's provided after searching through db, you just return "User not found" or as you said "You are not registered"
code:
loginUser: (req, res, next) => {
const { email, password } = req.body
if (!email || !password) {
// user does not provide email or password, return immediately without db search
return res.status(400).json({ message: "Email and password are must" })
}
User.findOne({ email }, (err, user) => {
if (err) {
return next(err)
} else if (!validator.isEmail(email)) {
return res.status(400).json({ message: "Invalid email" })
} else if (!user) {
// user provide email and password however email deos not match any in db
// this is equals to "You are not registered"
return res.status(402).json({ error: "User not found" })
} else if (!user.confirmPassword(password)) {
return res.status(402).json({ error: "Incorrect password" })
}
// generate token here
const token = auth.signToken(email)
res.status(200).json({ user, token })
})
},
Hope this is what you want.
(!user || !password) means "if user is not found or password is not in the request body". If you want to specifically check if a user is not found you should have a if(!user) and act on that... Which you already do - lower down in the else if statement. But the first condition (if(!user || !password)) is a superset of the second (if(!user )), so you will never get to the second one. You should move this condition to be the first in the sequence.
Generally, I would rework your entire if statement to possibly nest some conditions inside others, e.g.
// user found:
if(user) {
if(!user.confirmPassword(password)) {
// user found but password is wrong
}
} else {
// user not found
}