Retrieve information upon registration - mysql

How can i do this, When a user registers , I would like the endpoint to still go ahead and get back the information which is saved inside the database.For some reason, it does not work as expected
How do i go about this :
My code is looking thus :
app.post("/api/sign-up", async function (req, res) {
dbConn.query(
`select * from accounts where email = ${dbConn.escape(req.body.email)}`,
async function (err, result, fields) {
if (result.length === 0) {
var email = req.body.email;
var phone = req.body.phone;
var password = req.body.password;
var fullname = "NULL";
const hashPass = await bcrypt.hash(password, 12);
dbConn.query(
`insert into accounts(email, phone, password, fullname) values (?,?,?,?)`,
[email, phone, hashPass, fullname],
function (error, results, fields) {
if (error) throw error;
return res.send({
error: false,
data: results[0],
message: "User created Successfully",
});
}
);
} else {
return res.send({
error: true,
message: "User exists",
});
}
}
);
});
Checked thru the internet, i could not find the information needed.

I managed to fix it.
Code looks like this now , and it shows the data inside POST man
app.post("/api/sign-up", async function (req, res) {
dbConn.query(
`select * from accounts where email = ${dbConn.escape(req.body.email)}`,
async function (err, result, fields) {
if (result.length === 0) {
var email = req.body.email;
var phone = req.body.phone;
var password = req.body.password;
var fullname = "NULL";
const hashPass = await bcrypt.hash(password, 12);
dbConn.query(
`insert into accounts(email, phone, password, fullname) values (?,?,?,?)`,
[email, phone, hashPass, fullname],
function (error, results, fields) {
if (error) throw error;
return res.send({
error: false,
email:email,phone:phone,
message: "User created Successfully",
});
//return res.status(201).json({message: 'User created Successfully', "email":email,"phone":phone});
}
);
} else {
return res.send({
error: true,
message: "User exists",
});
}
}
);
});
Thanks to everyone who decided to take a Look :)

Related

bcrypt nodejs - null error when trying to login with comparing hashed password from the database

I created a basic register and login page connected to local mysql - that collects email, username and password (password gets hashed with bcrypt) and stores them in database.
Yet when i am trying to log in I get an error that says just : null + (console log saying password + else2 so i know which line got called)
This is login.js file
exports.login = (req, res) => {
console.log(req.body);
let email = req.body.email;
let password = req.body.password;
let username = req.body.username;
//if it finds username and email matching login credentials it will check for password
db.query('SELECT username, email, password FROM users WHERE username = ? AND email = ?', [username, email], function (error, results) {
if (error) {
res.send({
"code": 400,
"failed": "error ocurred"
});
}
//results[0].password means the password of the user that was found.
// it should compare plain password with the encrypted password in database
//and redirect to the /profile page if the password are a match.
if (results.length > 0) {
bcrypt.compare(password, results[0].password, function (error, answer) {
if (error) {
console.log(password +'if1')
console.log("comparing gone wrong", error);
return res.render('login', {
message3: 'Comparing error - please try again later'
});
}
if (answer) {
console.log(password + 'if 2')
res.redirect("/profile");
console.log("login successfull!");
}
else {
console.log(password + ' else2', error)
return res.render('login', {
message3: 'User or password or email is wrong'
});
}
});
} else {
console.log(password + 'else3')
return res.render('login', {
message3: 'User or password or email is wrong'
});
}
});
};
I will also put the register.js file if that will help with anything.
exports.register = (req, res) => {
console.log(req.body);
const { username, email, password, passwordConfirm } = req.body;
db.query('SELECT email FROM users WHERE email = ?', [email], async (error, result) => {
if(error) {
console.log(error);
}
if( result.length > 0 ) {
return res.render('register', {
message: 'That email is already in use'
})
} else if( password !== passwordConfirm) {
return res.render('register', {
message: 'That passwords do not match'
});
}
let hashedPassword = await bcrypt.hash(password, 8);
console.log(hashedPassword);
db.query('INSERT INTO users SET ?', {username: username, email: email, password: hashedPassword }, (error, result) => {
if(error) {
console.log(error);
} else {
console.log(result);
return res.render('register', {
message2: 'User Registered!'
});
}
})
});
}
Well, now I know why finding an answer online was so hard.
The code is right, the problem was in my database, I previously allowed for 50 Varchar password (but hashing it makes it longer, and it was getting cut), after I changed it to 128 chars it works perfectly with the new users that now register and login under the new broader restrictions.

check if username and email already exists with expressjs validator and mysql

I want to check if email already exist in mysql database using express-validator package to do this. The example about checking email is not for mysql database.
The code is submitting form values successfully but the checks are being skipped. This is a middleware but the middleware is not been implemented before inserting into the database.
The solution I currently implemented is from stackoverflow. But still not working for me
router.post("/register",[
body('username').not().isEmpty().isLength({ min: 4 }).trim().escape(),
//check if email is aleady existing in the database
body('email').not().isEmpty().isEmail().normalizeEmail().custom(async (email, {req})=>{
const getEmails = "SELECT * FROM users WHERE email=" + req.body.email;
return await con.query(getEmails, [email], (error, rows, fields)=>{
if(error){
console.log("the email is not ok",error)
}else{
if (rows.length != 0) {
res.redirect('/guests/register');
return Promise.reject("user already exists.");
}else{
return true;
}
}
})
}),//end check if email already exit
body('phone').not().isEmpty().isLength({ min: 6 }),
body('password').not().isEmpty().isLength({ min: 6 }),
//check if password match
body('passwordConfirmation').not().isEmpty().isLength({ min: 6 }).custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation does not match password');
}
return true;
}),
//check if password match
], async function(req, res, next) {
try{
var usernames = req.body.username;
var emails = req.body.email;
var phones = req.body.phone;
const hashedPassword = await bcrypt.hash(req.body.password, 10);
let sql = "INSERT INTO `users` (username, email, phone, password) VALUES ('" + usernames + "', '" + emails + "', '" + phones + "', '" + hashedPassword + "')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted, ID: " + result.insertId);
res.redirect('/guests/login');
})
}catch{
//console.log("something is wrong", error)
res.redirect('/guests/register');
}
});
This code works for me:
const express = require('express');
const router = express.Router();
const { check,validationResult } = require('express-validator');
const bcrypt = require('bcrypt');
const bcryptRounds = 10;
router.post('/register', [
check('username')
.exists()
.trim()
.matches(/^[a-zA-Z\ö\ç\ş\ı\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü ]{3,16}$/)
.withMessage('Invalid username!'),
check('mentionName')
.exists()
.trim()
.matches(/^(?=.*[a-z])[a-z0-9_]{3,15}$/)
.custom(async mentionName => {
const value = await isMentionNameInUse(mentionName);
if (value) {
throw new Error('Mention name is already exists!!!');
}
})
.withMessage('Invalid mention name!!!'),
check('email')
.exists()
.isLength({ min: 6, max: 100 })
.isEmail()
.normalizeEmail()
.trim()
.custom(async email => {
const value = await isEmailInUse(email);
if (value) {
throw new Error('Email is already exists!!!');
}
})
.withMessage('Invalid email address!!!'),
check('password')
.exists()
.isLength({ min: 6, max: 16 })
.escape()
.trim()
.withMessage('Invalid password!!!'),
check('rePassword').exists().custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('The passwords is not same!!!');
}
return true;
})
],
function (req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
} else {
console.log("----->START USER REGISTRATION");
const username = req.body.username;
const mentionName = '#'+req.body.mentionName;
const email = req.body.email;
const pass = req.body.password;
bcrypt.hash(pass, bcryptRounds, function(err, hash) {
console.log("HASH PASS : "+hash);
//INSERT USER
});
}
});
function isMentionNameInUse(mentionName){
var conn = require('../../modules/mysql_db');
return new Promise((resolve, reject) => {
conn.query('SELECT COUNT(*) AS total FROM users_table WHERE m_name = ?', [mentionName], function (error, results, fields) {
if(!error){
console.log("MENTION COUNT : "+results[0].total);
return resolve(results[0].total > 0);
} else {
return reject(new Error('Database error!!'));
}
}
);
});
}
function isEmailInUse(email){
var conn = require('../../modules/mysql_db');
return new Promise((resolve, reject) => {
conn.query('SELECT COUNT(*) AS total FROM users_table WHERE email = ?', [email], function (error, results, fields) {
if(!error){
console.log("EMAIL COUNT : "+results[0].total);
return resolve(results[0].total > 0);
} else {
return reject(new Error('Database error!!'));
}
}
);
});
}

Not a valid BCrypt hash. error is occuring

I have a problem in comparing method of bcrypt. This mthod is not able to compare password properly. Please sort out me from this problem.There is problem with comparing method its not working.I have a problem in comparing method of bcrypt. This mthod is not able to compare password properly. Please sort out me from this problem.There is problem with comparing method its not working.
app.post('/upload', (req, res) => {
// hash and save a password
const pass = bcrypt.hashSync(req.body.password);
const username = req.body.username;
console.log(bcrypt.compareSync(req.body.password, pass));
const sql = "INSERT INTO data ( password, username ) values (?,?)";
db.query(sql, [pass, username], (err, rows, fields) => {
if(!err){
res.send({
key: rows
});
}
else {
console.log(err);
}
});
})
app.post('/show', (req, res) => {
const username = req.body.username;
const password = req.body.password;
db.query("SELECT * FROM data WHERE username = ?",[username], function(err, results){
if (err) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"err ocurred"
})
}else{
if(results.length >0){
// console.log(bcrypt.compareSync(password, results[0].password));
if(bcrypt.compareSync(password, results[0].password)){
res.send({
"code":200,
"success":"login sucessfull"
});
}
else{
res.send({
"code":204,
"success":"Email and password does not match"
});
}
}else{
res.send({
"code":204,
"success":"Email does not exits"
});
console.log(results.length);
}
}
})
})

Node.js - Express & mysql TypeError: res.json is not a function although insert is successful

Although I have a successful insert I get an error (TypeError: res.json is not a function) when I want to return a json message upon. This is my setup:
const express = require('express');
module.exports = {
signup: async (req, res, next) => {
const { email, username, password } = req.value.body;
const connection = require('../config/dbconnection');
connection.query("SELECT * FROM tbl_users WHERE email = ?",[email], function(err, rows) {
if (rows.length) {
return res.json({ err: 'Email already exist'});
} else {
var newUserMysql = {
email: email,
username: username,
password: password
};
var insertQuery = "INSERT INTO tbl_users ( email, username, password ) values (?,?,?)";
connection.query(insertQuery,[newUserMysql.email, newUserMysql.username, newUserMysql.password],function(err, res, rows) {
if(err){
console.log('Insert error');
//res.json({ err: 'Insert error'});
} else {
console.log('Insert successful');
return res.json({ 'success': 'Insert successful'});
//return done(null, newUserMysql);
}
});
}
});
}
How can I return a json on successfull insert?
Your function's res parameter is hidden by the res return value from the connection.query call.
Rename the res parameter of this call to result (for example) and you should be fine:
connection.query(insertQuery,[newUserMysql.email, newUserMysql.username, newUserMysql.password],function(err, result, rows) {
if(err){
console.log('Insert error');
//res.json({ err: 'Insert error'});
} else {
console.log('Insert successful');
return res.json({ 'success': 'Insert successful'});
//return done(null, newUserMysql);
}
});
When you have nested scopes with conflicting variable names, the variable the closest (scope-wise) from where you reference this conflicting name will be used.
You're redefining res in your connection.query(insertQuery, [.....], function(err, res, rows) { ...}) function.
That res overrules the res from your express router within the scope of that function

Node.js - MySQL API, multi GET functions

I'm new in making API. I use Node.js and MySQL.
The fact is I have two GET function to get all users and one to get user by ID.
Both function are working when they are alone implemented. If both of them are implemented the function to get all user try to enter in the function to get user by ID so the API crash.
So here is my model users.js
var connection = require("../connection");
function Users()
{
//GET ALL USERS
this.get = function(res)
{
console.log('Request without id');
connection.acquire(function(err, con)
{
con.query('SELECT * FROM users', function(err, result)
{
con.release();
if (err)
res.send({status: 1, message: 'Failed to get users'})
else
res.send(result);
});
});
}
//GET USER BY ID
this.get = function(id, res)
{
console.log('Request with ID');
connection.acquire(function(err, con)
{
if (id != null)
{
con.query('SELECT * FROM users WHERE id = ?', id, function(err, result)
{
con.release();
if (err)
res.send({status: 1, message: 'Failed to find user: ' + id});
else if (result == "")
res.send({status: 1, message: 'Failed to find user: ' + id});
else
res.send(result);
});
}
});
}
And here is the routes.js
var users = require('./models/users');
module.exports = {
configure: function(app) {
app.get('/users/', function(req, res) {
users.get(res);
});
app.get('/users/:id/', function(req, res) {
users.get(req.params.id, res);
});
Do you have any idea why ?
Thanks for help :)
You can't have two functions with the same name in the same scope.
You have to rename your functions
/**
* Get all users
*/
this.get = function(res) {...}
/**
* Get user by id
*/
this.getById = function(id, res) {...}
Or you can have one function and check if an id is provided
this.get = function(id, res) {
if ( Number.isInteger(id) ) {
// return the user
} else {
res = id;
// return all users
}
}