Unable to encrypt password when updating bcrypt? - javascript

I want to update a customer's information that consists of first name, last name, email and password. I want to encrypt the password when its being updated. I wrote my route like this:
customerRouter.put(
'/:id', isAuth,
expressAsyncHandler( async (req, res) => {
const {id} = req.params;
const customer = await Customers.findOne({where: {id: id}});
const {firstname,lastname,password,email} = req.body;
if (!customer) {
res.status(401).send({
message: "Customer Not Found",
});
}else{
bcrypt.hash(password,10).then((hash)=>{
customer.firstName = firstname || customer.firstName
customer.lastName = lastname || customer.lastName
customer.email = email || customer.email
customer.password = hash || customer.password
})
const updatedCustomer = await customer.save();
res.send({
id: updatedCustomer.id,
firstname: updatedCustomer.firstName,
lastname: updatedCustomer.lastName,
email: updatedCustomer.email,
isAdmin: updatedCustomer.isAdmin,
token: generateToken(updatedCustomer)
});
};
})
);
The password wont change in the backend, I had a previous method that didn't encrypt and only changed the password, but this one doesn't encrypt the password or change it. Any help/guidance is much appreciated.

Related

How to perform user-input validation using if statements

I'm trying to perform user validation using if statements but on testing using post man, I keep on getting only the first return statement 'Email is required ' even after adding a valid email address and also an invalid email address. I have attached the user model, user controller logic and a picture of postman's response
user schema model
const mongoose = require('mongoose');
const { Schema } = mongoose
const userSchema = new Schema({
firstName: {
type: String,
required: true,
min: 3,
max: 20
},
lastName: {
type: String,
required: true,
min: 3,
max: 20
},
email: {
type: String,
required: true,
unique: true,
},
phoneNumber: {
type: String,
required: true,
},
password: {
type: String,
required: true,
min: 5
},
confirmPassword: {
type: String,
required: true,
min: 5
}
});
const User = mongoose.model('User', userSchema);
module.exports = User;
user.controller.js
module.exports.users = async(req, res) => {
try {
const email = await user.findOne({ email: req.body.email });
const firstName = await user.find({ firstName: req.body.firstName });
const lastName = await user.find({ lastName: req.body.lastName });
const password = await user.find({ password: req.body.password });
const confirmPassword = await user.find({ confirmPassword: req.body.confirmPassword });
const phoneNumber = await user.find({ phoneNumber: req.body.phoneNumber });
if (!email) return res.send('Email is required')
const filterEmail = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filterEmail.test(email.value)) return
res.send('Please provide a valid email address');
if (email) return res.send('Email already exists');
if (!firstName) return res.send('First Name is required');
if (firstName.length < 3 || firstName.length > 20) return
res.send('First name must be at least 3 characters and less than 20 characters');;
if (!lastName) return res.send('Last Name is required');
if (lastName.length < 3 || lastName.length > 20) return
res.send('Last name must be at least 3 characters and less than 20 characters')
if (!password) return res.send('PassWord is required');
const filterPassword = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{5,15}$/;
if (!filterPassword.test(password.value)) return
res.send('Password must include at least one lowercase letter, one uppercase letter, one digit, and one special character');
if (!confirmPassword) return res.send(' Please confirm password');
if (password.value !== confirmPassword.value) return res.send('Passwords do not match');
if (!phoneNumber) return res.send('Phone Number is required');
phone(phoneNumber.value);
let User = new user(_.pick(req.body, ['firstName', 'lastName', 'email', 'phoneNumber', 'password']));
bcrypt.genSalt(10, async(err, salt) => {
if (err) throw err;
return user.password = await bcrypt.hash(user.password, salt);
});
await User.save();
} catch (err) {
res.status(500).send('Something went wrong');
console.warn(err);
}
}
Your controller is not good. You need to get the email, lastName and firstName from req.body.
const {email, lastName} = req.body
And then do the validation, which by the way will already happen in mongoose.
const email = await user.findOne({ email: req.body.email });
In this line you are looking in your DB for a user with email = req.body.email. But since there is no such a user it return your if statement
if (!email) return res.send('Email is required')
to get your user you only need to compare with one value if you set it to be unique in your schema, for instead user email.
const user = await user.findOne({ email });
In this case email was already destructed and if there is no user, you can create one.
you can use await user.create() and pass your values and hash the password with pre("save") in your schema.
UserSchema.pre("save", async function () {
if (!this.isModified("password")) return;
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
});
You can also validate user email in the schema
email: {
type: String,
required: [true, "Please provide email"],
match: [
/^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
"Please provide a valid email",
],
unique: true,
},
You can simply install the validator package npm i validator then call it in in the user model const { isEmail } = require('validator'); and finally type this in your schema instead of hardcoding the verification code in the function.
email: { type: String, required: true, validate: [isEmail], unique: true },
Instead of writing custom logic for validation Please add a validation layer after performing security checks
you can use Express validator, to perform all your validations in a smoother way, It will eliminate unnecessary logic and code lines and add structured code to validate all types inputs, nested objects, DB call for existing data handling. It will handle the response and response message on its own without hitting the controller
just hit
npm install --save express-validator
and you are ready to validate requests very easily and effectively
Beside other answers i thought one thing which is missing but yet it is very strong validation method in Node.JS is JOI package, you can define your validation schema and get rid of all other pain full if and else, example is following
const Joi = require('joi');
const schema = Joi.object().keys({
firstName: Joi.string().alphanum().min(3).max(20).required(),
lastName: Joi.string().alphanum().min(3).max(20).required(),
email: Joi.email().required(),
phoneNumber: Joi.string().length(10).pattern(/^[0-9]+$/).required(),
password: Joi.string().min(5).required(),
confirmPassword: Joi.any().valid(Joi.ref('password')).required()
});
const dataToValidate = {
firstName: 'chris',
lastName: 'John',
email: 'test#test.com'
}
const result = Joi.validate(dataToValidate, schema);
// result.error == null means valid
Without node script you can always test your JOI schema and your data object on this webpage

Trying to create a document whenever a user signs up

I am trying to create a document in firestore in the path "users" and the name user.uid every time a new user signs up. In this document I want to store some attributes such as firstname, lastname, email and uid. The issue i have is that the auth works perfectly, but no document is created.
var email = signupEmail.value;
var password = signupPassword.value;
var firstname = signupFirstname.value;
var lastname = signupLastname.value;
var password_repeat = signupRepeatPw.value;
const auth = getAuth();
const db = getFirestore();
if (firstname != "" && lastname != "") {
if (password == password_repeat) {
createUserWithEmailAndPassword(auth, email, password)
.then(async (userCredential) => {
const user = userCredential.user;
await setDoc(doc(db, "users", user.uid), {
firstName: firstname,
lastName: lastname,
accountLevel: 0,
UID: user.uid,
email: email,
})
.then(() => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
})
.catch((error) => {
const errorCode = error.code;
var errorMessage = error.message;
Any help will be very appreciated as I have been stuck on this for quite some time!
Best regards,
Isak
If anyone else is struggling with this issue, I fixed my mistake.
The problem was that I redirected the user to their profile page when the auth state changed, from another script tag running simaltaniously. This led to the code redirecting the user before the promise was complete and therefore it does not update the db.
Best regards,
Isak

My bcrypt.js hash returns undefined while all other inputs are fine

This code below returns the input password as undefined, but all other inputs are fine. I don't know what to do, if anyone can help please do.
I am using bcrypt.js with knex for psql.
app.post("/register", (req, res) => {
const { email, name, password } = req.body;
let salt = bcrypt.genSaltSync(10);
let hash = bcrypt.hashSync(password, salt);
knex
.transaction((trx) => {
trx
.insert({
hash: bcrypt.hashSync(password, salt),
email: email,
})
.into("login")
.returning("email")
.then((loginEmail) => {
return trx("users")
.returning("*")
.insert({
email: loginEmail[0].email,
name: name,
joined: new Date(),
})
.then((user) => {
res.json(user[0]);
});
})
.then(trx.commit)
.catch(trx.rollback);
})
.catch((err) => res.status(400).json("E-mail is already in use"));
});
*P.S. Using postman gives no errors. The error that comes in on the back-end terminal is Error: Illegal arguments: undefined, string meaning hash is undefined
I fixed it, was apparently a variable naming issue :) such a goof.
password was actually being received as "hash" from the front-end, changed it to hash & changed hash to hashedPassword.
const { email, name, hash } = req.body;
let salt = bcrypt.genSaltSync(10);
let hashedPassword = bcrypt.hashSync(hash, salt);
knex
.transaction((trx) => {
trx
.insert({
hash: hashedPassword,
email: email,
})

Why find() using models won't work in signup route?

It's a simple signup route to store credentials in a mongoDB database but I miss something because the 2 else if won't work properly. I suspect it is my find().
The first else if returns me in Postman "error": "E11000 duplicate key error collection: vinted.users index: email_1 dup key: { email: \"jean#dpont.com\" }" and the second give me "email already exists".
Thanks in advance for your help
const express = require("express");
const router = express.Router();
const SHA256 = require("crypto-js/sha256");
const encBase64 = require("crypto-js/enc-base64");
const uid2 = require("uid2");
const User = require("../models/User");
router.post("/user/signup", async (req, res) => {
try {
const email = req.fields.email;
const username = req.fields.username;
const phone = req.fields.phone;
const password = req.fields.password;
const token = uid2(64);
const salt = uid2(16);
const hash = SHA256(password + salt).toString(encBase64);
const emailSearch = await User.find({ email: email });
if (!emailSearch || username !== null) {
const newUser = new User({
email: email,
account: {
username: username,
phone: phone,
},
password: password,
token: token,
hash: hash,
salt: salt,
});
await newUser.save();
res.status(200).json({
_id: newUser._id,
token: newUser.token,
account: newUser.account,
});
}
//problem under
else if (emailSearch) {
res.status(404).json({ message: "email already exists" });
} else if (username === null) {
res.status(404).json({ message: "please type a username" });
}
} catch (error) {
res.status(404).json({
error: error.message,
});
}
});
It looks like the issue is that if the username in the request body is not null, it's going to attempt to create a new User with that username regardless of whether a User exists with the same email - if (!emailSearch || username !== null).
It's generally best-practice to do as much input validation as you can before you start looking for records or creating new ones, as you will be able to avoid more Mongo errors and database actions if you can stop invalid actions before they're attempted. So in this case, check that the username is valid before looking for existing Users.
To solve this problem, I would move that last else-if to before you check whether a User exists with the same email. That way, once you determine whether the username is valid, then the only thing that you need to consider is existing Users before creating a new one. Something like this:
if (username === null) {
res.status(400).send({ message: "Error: Please provide a 'username'." });
}
const existingUserWithEmail = await User.find({ email: email });
if (!existingUserWithEmail) {
// Create the new User
} else {
res.status(400).send({ message: "Error: An account already exists with this email." });
}

React Native & Firebase : user info not being stored in database

I'm trying to create a new user and store their information in firebase database. I successfully create the user but the user information isn't getting stored in firebase.
The function that is running is handleAuthWithFirebase
The console.log("Storing user") is showing up in the console so I'm not sure why firebase.database().ref().set isn't running.
Here is my code
export function handleAuthWithFirebase (newUser) {
return function (dispatch, getState) {
dispatch(authenticating());
console.log(newUser);
console.log('Signing up user');
var email = newUser.email;
var password = newUser.password;
firebase.auth().createUserWithEmailAndPassword(email, password).catch(error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
}).then(() => {
const user = firebase.auth().currentUser;
// Set user in Firebase
console.log("Storing user")
firebase.database().ref('/users/' + user.uid).set({
name: newUser.displayName,
username: newUser.username,
email: newUser.email
})
}).then(() => {
const user = firebase.auth().currentUser;
dispatch(isAuthed(user.uid))
})
}
}
The problem is that you're missing a child object, so you have to specify it after ref. It would be more helpful if you can post the tree of your database as well, but before try this and figure out yout child.
firebase.database().ref('myRef').child('myChild').set({
name: newUser.displayName,
username: newUser.username,
email: newUser.email
})
Here's what I got working, for those coming across this post.
firebaseApp.auth()
.createUserAndRetrieveDataWithEmailAndPassword(this.state.email, this.state.password)
.then(response => {
firebaseApp.database().ref('users').child(response.user.uid).set({
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
email: this.state.email
});
response.user.sendEmailVerification().then(response => {
AlertIOS.alert('Message', 'Sending email verification to '+this.state.email)
});
this.setState({authenticating: false})
}, error => {
AlertIOS.alert('Error', error.message);
this.setState({authenticating: false})
})

Categories