How to catch error using Postgres, PG, Express? - javascript

const pool = require('../db')
const asyncHandler = require('express-async-handler')
const { generateToken } = require('../middleware/userAuth')
// #desc Register New User
// #route POST /api/users/register
// #public Public
const registerUser = asyncHandler(async(req, res) => {
const { email, name, password } = req.body
const newUser = {
name,
email,
password
}
const existingUser = ''
if (existingUser) {
res.status(400)
throw new Error('User Already Exists')
} else {
try {
const result = await pool.query(
'INSERT INTO users (name, email, password) VALUES ($1, $2, $3) RETURNING *',
[name, email, password],
(err, res) => {
if (err) {
console.log(err)
}
}
)
res.status(201)
res.json(result.rows)
} catch (error) {
console.log(error)
res.status(400)
throw new Error('Unable to create user')
}
}
})
I'm trying to figure out how to console.log the errors that come from the postgresql database errors when I make a query.
So far, the try/catch is only catching main errors in express. The console.log(error) will say "Type Error, cannot return rows of undefined" which means "result" variable is undefined because the query failed, and "Unable to create user" from the new Error thrown. (I purposefully made it fail)
The "err" callback doesn't seem to console.log anything.
I'd like to be able to see what specifically in postgresql was the problem, such as in this case the columns do not exist.
Any ideas?

Related

How do i Validate old password while updating user password?

What's the proper way to validate old user password while updating new password?
So far i have tried and always get error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
What i did:
I tried using bcrypt to compare the old password from req.body with user existing password and then hash with bcrypt before saving. Comparing the password using bcrypt gave the error above. Not comparing the old password at all and just saving new password works properly.
My code:
exports.updatePassword = async (req, res) => {
try {
const { oldPassword, password } = req.body;
let updatedPassword = {
password: password,
};
const user = await User.findOneAndUpdate(
{ _id: req.params.userId },
{ $set: updatedPassword },
{ new: true, useFindAndModify: false }
);
// validate old password
bcrypt.compare(oldPassword, user.password, function (err, match) {
if (!match || err)
return res.status(400).send('Please enter correct old password');
});
//hash password and save user
bcrypt.genSalt(12, function (err, salt) {
bcrypt.hash(user.password, salt, (err, hash) => {
user.password = hash;
user.save();
return res.json({user});
});
});
} catch (err) {
console.log(err);
return res.status(400).send('Something went wrong. Try again');
}
};
The issue is that the updatePassword function is ending before you actually process everything. To avoid nested function calls and returns, use the async methods provided by bcrypt (also check their recomendation on using async vs sync).
Regarding the code itself, you are updating the user's password before checking if the password is valid. You should get the user from the db, check if the current password matches, and only then insert the new hashed password into the db.
exports.updatePassword = async (req, res) => {
const { oldPassword, password } = req.body;
try {
// get user
const user = await User.findById(req.params.userId);
if (!user) {
return res.status(400).send('User not found');
}
// validate old password
const isValidPassword = await bcrypt.compare(oldPassword, user.password);
if (!isValidPassword) {
return res.status(400).send('Please enter correct old password');
}
// hash new password
const hashedPassword = await bcrypt.hash(password, 12);
// update user's password
user.password = hashedPassword;
const updatedUser = await user.save();
return res.json({ user: updatedUser });
} catch (err) {
console.log(err);
return res.status(500).send('Something went wrong. Try again');
}
};

Make a login and registration system using Azure functions and Azure SQL server

I want to make a Dating application using node.js and javascript with Azure functions and an Azure sql server. I can create a user so it appears in my database, but how do I make a login system that "checks" if the users email and password is in the database and is correct.
This is what I have so far:
**Login.js:**
var form = document.getElementById("form")
form.addEventListener('submit', function(e) {
e.preventDefault()
var email = document.getElementById("email").value
var password = document.getElementById("password").value
fetch("http://localhost:7071/api/login", {
method: 'POST',
body: JSON.stringify({
email: email,
password: password,
}),
headers: {
"Content-Type": "application/json; charset-UTF-8"
}
})
.then((response) => {
return response.text()
})
.then((data) => {
console.log(data)
}).catch((err) =>{ // catcher fejl, hvis noget går galt
console.log("wuups: " + err)
})
})
**DB.js connect:**
function login (payload) {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM [user] where email = #email AND password = #password'
const request = new Request(sql,(err,rowcount) =>{
if (err){
reject(err)
console.log(err)
} else if( rowcount == 0){
reject({messsage:"user does not exit"})
}
});
request.addParameter('email', TYPES.VarChar, payload.email)
request.addParameter('password', TYPES.VarChar, payload.password)
request.on('row',(colums) => {
resolve(colums)
})
connection.execSql(request)
return "you are now logged in"
});
}
module.exports.login = login;
You're on the right track. Consider an updated version of db.sql:
function login(payload, connection) {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM [user] where email = #email AND password = #password'
const request = new Request(sql, (err, rowCount) => {
if (err) {
reject(err)
console.error(err)
}
else {
if (rowCount == 1) {
resolve(payload.email)
}
else {
reject('Invalid credentials')
}
}
});
request.addParameter('email', TYPES.VarChar, payload.email)
request.addParameter('password', TYPES.VarChar, payload.password)
connection.execSql(request)
});
}
Since we can infer a successful login from the amount of returned rows, we don't need access to the actual rows in the row callback.
However: as pointed out by Robert in the comments, storing passwords in plain text is a security concern (since access to the database immediately unveils user passwords).
Better approach
The better approach is to store hashed passwords instead. Imagine this simple user table schema in MSSQL:
CREATE TABLE [User] (
[Email] [varchar](max) NOT NULL UNIQUE,
[PasswordHash] [varchar(max)] NOT NULL
)
The login procedure will remain almost the same. Instead of comparing passwords we now compare hashed passwords. Without going into too much detail, you would usually use a library for this purpose (to handle salts, mitigate timing attacks, etc.). I chose bcryptjs for the example below:
var bcrypt = require('bcryptjs');
function login(email, password, connection) {
return new Promise((resolve, error) => {
const sql = 'SELECT * FROM [user] where email = #email' // Note that the password comparison no longer lives here
const request = new Request(sql, (err, rowCount) => {
if (err) {
reject(err)
}
})
request.addParameter('email', TYPES.VarChar, email)
let userRow = null
// This time we need the 'row' callback to retrieve the password hash
request.on('row', row => {
userRow = {
email = row[0].value,
passwordHash = row[1].value
}
})
// .. and the 'done' callback to know, when the query has finished
request.on('done', rowCount => {
if (rowCount == 0) {
reject('User not found')
}
else {
bcrypt.compare(password, userRow.passwordHash) // Password comparison
.then(passwordsMatch => {
if (passwordsMatch) {
resolve(email)
}
else {
reject('Invalid credentials')
}
})
}
})
connection.execSql(request)
})
}
And here's an example of how to create new users with this approach using the same library:
var bcrypt = require('bcryptjs');
const PASSWORD_SALT_ROUNDS = 10 // Learn more at ex. https://stackoverflow.com/questions/46693430/what-are-salt-rounds-and-how-are-salts-stored-in-bcrypt
function createNewUser(email, password, connection) {
return bcrypt.hash(password, PASSWORD_SALT_ROUNDS).then(passwordHash => {
const sql = 'INSERT INTO [user] (Email, PasswordHash) VALUES (#email, #passwordHash)'
const request = new Request(sql, err => {
if (err) {
error(err)
}
else {
resolve()
}
})
request.addParameter('Email', TYPES.VarChar, email)
request.addParameter('PasswordHash', TYPES.VarChar, passwordHash)
connection.execSql(request)
})
}
Consider this a pragmatic proposal to get started. Please note, that the code is illustrative, since I haven't actually executed it, and it is made under certain assumptions.

How Can I update each password in my database with hashed bcrypt version?

So as you can see. I am trying to take the previous password in the column and update it with the hashed version. For some reason the save on the document isn't firing right away. So I tried using async await and even creating a custom async await foreach to await the callback and the save. However, Mongoose seems to be waiting for all of the saves to come in before applying the save.
This is the error that I get.
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: 505)
(node:2440)
const User = require("./models/User");
const bcrypt = require("bcryptjs");
const db = require("./config/keys").mongoURI;
async function hashIt(user) {
console.log(user);
bcrypt.genSalt(10, (err, salt) => {
if (err) console.log(err);
bcrypt.hash(user.Password, salt, async (err, hash) => {
if (err) throw err;
user.Password = hash;
const id = await user.save();
console.log(id);
})
});
}
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
async function mySeed() {
try {
User.find({}, async (err, users) => {
if (err) console.log(err);
asyncForEach(users, async (user) => {
await hashIt(user);
})
});
} catch (e) {
console.log(e);
}
}
async function fullThing(){
mongoose.connect(db, { useNewUrlParser: true })
.then(async () => {
await mySeed();
console.log("finished successfully");
})
}
fullThing();```
I appreciate the response. The solution turned out to be that w=majority for some reason needed to be removed from the db connection. After removing that. Everything began working fine. Wrapping the connect with the catch did help to find the error.
I have a similar routine running on my current back front end system, and below is how I have adapted your code to mine; mine is working, therefore I hope yours will work as well. I believe the problem is that is you are not catching potential errors, that happened to me a lot in the beginning, and sometimes it still happens when I am tired.
bcrypt.genSalt(10, (err, salt) => {
if (err) console.log(err);
bcrypt.hash(user.Password, salt, (err, hash) => {
if (err) throw err;
user.Password = hash;
const id = user
.save()
.then(() => {
console.log("okay");
})
.catch(err => console.log(err));
});
});
In case it does not work, please, let me know what comes out as error.
Appendix
I have tested my solution below:
const bcrypt = require("bcryptjs");
require("./connection");
//creating user schema
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
UserSchema = new Schema({ name: String, password: String });
var User = mongoose.model("User", UserSchema);
const user = new User({ name: "Jorge Pires", password: "Corona Virus" });
console.log(` Before hashing ${user.password}`);
//---------------------------------------------------------------
//Uncomment here to save the user before hashing, it will change anyway, therefore no need!
// user.save();
// User.create({ name: "Jorge Pires", password: "Corona Virus" });
//--------------------------------------------------------------
bcrypt.genSalt(10, (err, salt) => {
//generates the salta
if (err) console.log(err);
bcrypt.hash(user.password, salt, (err, hash) => {
//creates the hash
if (err) throw err;
user.password = hash; //saves the hash
const id = user
.save()
.then(() => {
console.log(` after hashing ${user.password}`);
console.log(` Here goes the user id ${user.id}`);
})
.catch(err => console.log(err));
});
});
Output sample:
Before hashing Corona Virus
we are connected mongoose-tutorial
after hashing $2a$10$84MqPsiiMGA/KTHKFbytVOD5/su6rXiE7baA2TmsLzPMe.Y45aL9i
Here goes the user id 5e710a0bd4385c05b0cd827f

Using async in app startup script not returning any results

I am trying to run the following script in my Node app to check if any users exist and if not, create first admin user. Yet the script simply do nothing, return nothing even while using Try/Catch so can someone please tell me what I am missing / doing wrong here? or how I can possibly catch the error (if any)? Thanks
import pmongo from 'promised-mongo';
import crypto from 'crypto';
const salt = 'DuCDuUR8yvttLU7Cc4';
const MONGODB_URI = 'mongodb://localhost:27017/mydb';
const db = pmongo(MONGODB_URI, {
authMechanism: 'ScramSHA1'
}, ['users']);
async function firstRunCheckAndCreateSuperAdmin(cb) {
const username = 'admin2#test2.com';
try {
const user = await db.users.findOne({ role: 'admin'});
console.log(user);
if(!user) return cb('No user found');
} catch(e) {
cb('Unexpected error occurred');
}
if(!user) {
console.log('No admin detected.');
const adminPassword = crypto.pbkdf2Sync ( 'password', salt, 10000, 512, 'sha512' ).toString ( 'hex' );
await db.users.update({username: username}, {$set: {username: username, password: adminPassword, role: 'admin'}}, {upsert: true});
}
db.close();
process.exit();
}
firstRunCheckAndCreateSuperAdmin(function(err, resultA){
if(err) console.log(err);
});
You are not returning any callback when there is no admin user in the following code snippet
if (!user) {
console.log('No admin detected.');
const adminPassword = crypto.pbkdf2Sync ( 'password', salt, 10000, 512, 'sha512' ).toString ( 'hex' );
await db.users.update({username: username}, {$set: {username: username, password: adminPassword, role: 'admin'}}, {upsert: true});
// call cb(user) here
}
Please see comment.
import pmongo from 'promised-mongo';
import crypto from 'crypto';
const salt = 'DuCDuUR8yvttLU7Cc4';
const MONGODB_URI = 'mongodb://localhost:27017/mydb';
const db = pmongo(MONGODB_URI, {
authMechanism: 'ScramSHA1'
}, ['users']);
async function firstRunCheckAndCreateSuperAdmin(cb) {
const username = 'admin2#test2.com';
try {
const user = await db.users.findOne({
role: 'admin'
});
console.log(user);
//(1) If user is undefined, then launch cb with an error message;
if (!user) return cb('No user found');
} catch (e) {
//(2) If something is wrong, then launch cb with an error message;
cb('Unexpected error occurred');
}
//This part of the code will only be reached if user is defined.
//This is a dead code as if user is undefined, it would have exited at (1)
if (!user) {
console.log('No admin detected.');
const adminPassword = crypto.pbkdf2Sync('password', salt, 10000, 512, 'sha512').toString('hex');
await db.users.update({
username: username
}, {
$set: {
username: username,
password: adminPassword,
role: 'admin'
}
}, {
upsert: true
});
}
//So if user exists, it will close db and exit without calling cb.
db.close();
process.exit();
}
firstRunCheckAndCreateSuperAdmin(function(err, resultA) {
if (err) console.log(err);
});
Note:
If you are using async/await, then you don't need to use callback.
If you are using callback, then you don't need to have a return statement.
If the intention of the function is suppose to have a return value, make sure all code path returns a value.
I have tried to rewrite your code to make it smaller and to remove all node-style callback types of async code from it. I replaced update with insertOne since you only have one user to insert (not multiple to update). Also I have added 500 ms timeout when calling firstRunCheckAndCreateSuperAdmin in case it "hangs". It should log something at the end :)
import pmongo from 'promised-mongo'
import crypto from 'crypto'
import {
promisify
} from 'util'
const pbkdf2 = promisify(crypto.pbkdf2)
const salt = 'DuCDuUR8yvttLU7Cc4'
const MONGODB_URI = 'mongodb://localhost:27017/mydb'
const db = pmongo(MONGODB_URI, {
authMechanism: 'ScramSHA1'
}, ['users']);
const username = 'admin2#test2.com'
async function firstRunCheckAndCreateSuperAdmin() {
let user = await db.users.findOne({
role: 'admin'
});
if (!user) { // no user lets create one
user = await db.users.insertOne({
username: username,
password: (await pbkdf2('password', salt, 10000, 512, 'sha512')).toString('HEX'),
role: 'admin'
});
}
return user
}
const timeout = delay => message => new Promise((_, reject) => setTimeout(reject, delay, new Error(message)))
Promise
.race([firstRunCheckAndCreateSuperAdmin(), timeout(500)('Rejected due to timeout')])
.then(user => console.log(`Got user ${JSON.stringify(user)}`))
.catch(error => console.error(error))

Node return errors correctly (e.g. validation errors)

I'm refactoring our code into promises.
Two blocks with sample code:
user.service.js
export function updateUserProfileByUsername(req, res) {
userController.getUserByUsername(req.params.username)
.then((userProfile) => {
return userController.saveUserProfileByUser(userProfile,
req.body.email,
req.body.username,
req.body.firstname,
req.body.lastname)
})
.then((updated_user) => {
res.status(200).json(updated_user.profile);
})
.catch((err) => {
res.status(404).send('something went wrong');
});
}
export function getUserProfileByUsername(req, res) {
userController.getUserProfileByUsername(req.params.username)
.then((userProfile) => {
res.status(200).json(userProfile);
})
.catch((err) => {
res.status(404).send('something went wrong');
})
}
user.controller.js
export function getUserProfileByUsername(username) {
return User.findOne({
'username': username
}).exec()
.then((user) => {
if (user)
return user.profile;
else
throw new Error("user not found!");
});
}
export function getUserByUsername(username) {
return User.findOne({
'username': username
}).exec()
.then((user) => {
if (user)
return user;
else
throw new Error("user not found!");
});
}
export function saveUserProfileByUser(user, email, username, firstname, lastname) {
user.email = email;
user.username = username;
user.firstname = firstname;
user.lastname = lastname;
return user.save(); // returns a promise
}
Our routes enter in user/index.js, go into service.js and the controller handles our database work and errors.
What I am trying to achieve is to send fitting errors to the client.
Like: 'the user does not exist' or 'username is too long' when updating a wrong user, etc.
if I try to send the error to the client, i'll just get a empty json as result ({}). If I log the error, i get the full stack trace, including validation errors.
.catch((err) => {
console.log(err) // shows me full stacktrace of the error
res.status(404).send(err); //sends {} to the client
})
How can I implement this with promises? Should i add extra middleware sending correct error messages?
I would really appreciate some hints in the right direction for this one.
Thanks in advance!
Because err is an object I assume express is converting to JSON for you. However, when you stringify an error you get '{}';
If you want to return the stacktrace try .send(err.stack).
Alternatively if you only want the message and not the entire stack you can use err.message.
.catch((err) => {
console.log(err)
res.status(404).send(err.stack);
})

Categories

Resources