Error: data and salt arguments required with mysql - mysql

import connection from '../database.js'
import bcrypt, { hash } from "bcrypt"
import express from 'express'
import jsonwebtoken from 'jsonwebtoken'
import secret from '../secret.js'
const authRouter = express.Router()
authRouter.post('/signup',async(req,res)=>
{
let {fullname,password,email,profile_pic}=req.body;
//the problem lies here
password=await bcrypt.hash(password,10)
connection.query("insert into users(fullname,email,password,profile_pic)values(?,?,?,?)",
[fullname,email,password,profile_pic],(err,result)=>{
if(err){
res.json({
error:err.message,
success:0
})
}
else if(result){
res.json({
email,
fullname,
profile_pic
})
}
})
})
authRouter.post('/login',(req,res)=>{
let{email,password}=req.body
connection.query("select *from users where email = ?",[email],async(err,result)=>{
if(err){
res.json({
err:err.message,
success:0
})
}
else{
if(result.length>0){
const ans = await bcrypt.compare(password, result[0].password)
if(ans){
delete result[0].password
const token = await jsonwebtoken.sign({...result[0]},secret,{expiresIn:'10h'})
res.json({
...result[0],token
})
}
else{
res.json({
error:"incorrect password",
success:0
})
}
}
else{
res.json({
error:"user not found",
success:0
})
}
}
})
})
export default authRouter

Related

How to call a function that return the result of mysql query to send it back in a Express.js result?

How to call a function that return the result of MySQL query to send it back in a Express.js result?
I try to export some of my sql query in individual function to clean up and remove duplicate code.
I try with async await function, but it did not work.
How clean this code?
Thanks
import { Request, Response } from 'express'
import { mysqlConnection } from '../config/mysql.config'
import { users } from '../models/users.models'
export class AuthController {
constructor() { }
// I want to avoid this embedded callbacks function
public signin(req: Request, res: Response) {
var user: users = req.body
var insUser = [
user.userEmail,
user.userFirstName,
user.userLastName,
user.userEmail,
//hash password
// user.userPassword
]
mysqlConnection.pool.getConnection((err, connection) => {
connection.query('SELECT * FROM tblusers where userEmail = ? OR userUserName = ?', [user.userEmail, user.userUsername], (err, row: users[]) => {
if (err) throw err;
if (row.length) {
return res.status(400).json({ errors: { msg: "user exist already", status: 'signin-error' } })
}
//addUserInDB
connection.query('INSERT INTO tblusers (userUserName, userFirstName, userLastName, userEmail, userPassword) VALUES (? ,?, ?, ?, ?)', insUser, (err, row) => {
if (err) throw err;
//get userFormDB
connection.query('SELECT userId, userUsername, userFirstName, userLastName, userEmail, userPassword, webrName FROM tblusers INNER JOIN tblweblroles ON tblusers.tblWeblroles_webrId = tblweblroles.webrId where userEmail = ?', [user.userEmail], (err, row: users[], fields) => {
if (err) throw err
connection.release();
var firstUser = row[0]
var user = {
userId: firstUser.userId,
userUsername: firstUser.userUsername,
userFirstName: firstUser.userFirstName,
userLastName: firstUser.userLastName,
userEmail: firstUser.userEmail,
userUpdateAt: firstUser.userUpdateAt,
userCreatedAt: firstUser.userCreatedAt,
webrName: firstUser.webrName
}
res.status(200).json(user);
})
})
})
})
}
//test
private getUsers() {
console.log('test')
mysqlConnection.pool.query('SELECT * FROM webapp.tblusers;', (err: any, row: any) => {
if (err) throw err
console.log('row: ' + row)
return row
})
}
public async login(req: Request, res: Response) {
console.log('test1')
try {
var users = await this.getUsers()
console.log('users:' + users)
res.json(users);
} catch (error) {
res.json(error);
}
};
}
export class AuthController {
constructor() {
}
public async login(req: Request, res: Response) {
var users: any = await AuthController.getUsers()
res.json(users)
};
public static getUsers(): Promise<any> {
console.log('test')
return new Promise(resolve => {
mysqlConnection.pool.query('SELECT * FROM webapp.tblusers;', (err: any, row: any) => {
if (err) throw err
resolve(row)
})
});
}
}

using bcrypt for login in nodejs

I'm having a hard time with integrating bcrypt to try to make my login system safe.
I basically get the username, password the user inputs and try to compare it from the hashed password in my db. here's what I have.
const inputUsername = req.body.inputUsername;
const inputPassword = req.body.inputPassword;
var userLogin = "select * from login where USERNAME = ?"
ibmdb.open(ibmdbconnMaster, function(err, conn) {
if (err) return console.log(err);
conn.query(userLogin, [inputUsername], function(err, rows) {
if (err) {
console.log(err)
}
if (rows.length > 0) {
var pass = ""
for (var i = 0; i < rows.length; i++) {
pass = rows[i]['PASSWORD'];
console.log(pass)
bcrypt.compare(inputPassword, hash, function(err, result) {
if (pass == result) {
console.log("this works")
userAuth = true;
res.redirect('/index')
}
})
}
console.log("does not work")
} else {
userAuth = "false";
res.render('login.ejs')
alert('Incorrect username or password. Please try again')
}
conn.close(function() {
console.log('closed the function /login');
});
})
})
what happens right now is I get the error ReferenceError: hash is not defined
not sure how to fix this. thanks in advance
Where have you defined hash? I don't see it in your code.
Here's an example of auth routes that I've used with bcrypt/node/express:
const Users = require("../users/users-model.js");
router.post("/register", (req, res) => {
// Pull the user's credentials from the body of the request.
const user = req.body;
// Hash the user's password, and set the hashed password as the
// user's password in the request.
const hash = bcrypt.hashSync(user.password, 10);
user.password = hash;
Users.add(user)
.then((newUser) => {
const token = generateToken(newUser);
res
.status(201)
.json({ created_user: newUser, token: token, user_id: newUser.id });
})
.catch((err) => {
res.status(500).json({
message: "There was an error adding a user to the database",
err,
});
});
});
router.post("/login", (req, res) => {
const { username, password } = req.body;
Users.findBy({ username })
.first()
.then((user) => {
if (user && bcrypt.compareSync(password, user.password)) {
const token = generateToken(user);
res
.status(200)
.json({
username: user.username,
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
token: token,
user_id: user.id,
});
} else {
res.status(401).json({ message: "Invalid Credentials" });
}
})
.catch((err) => {
res.status(500).json(err);
});
});
function generateToken(user) {
const payload = {
userid: user.id,
username: user.username,
};
const options = {
expiresIn: "1h",
};
const token = jwt.sign(payload, secrets.jwtSecret, options);
return token;
}
module.exports = router;

unable to return response after login in node js api

TypeError: res.send is not a function.
I am getting this error when I try to return response after user login successfully.
can anybody help me out from this error.
here is my code:-
exports.login = function(req, res, next) {
let q = "SELECT * from users WHERE email = ?";
let query = sql.query(q,req.body.email, (error, res) => {
if (res.length > 0) {
bcrypt.compare(req.body.password, res[0].password, function(err, result){
if(err) {
console.log('password dost not match');
console.log("error: ", err);
result(null, err);
}
if(result) {
console.log('pasword match');
const jwtToken = jwt.sign({
email: res[0].email,
id: res[0].id
},
'secret',
{
expiresIn: '2h'
});
//tk = jwtToken;
return res.status(200).json({
error:0,
message:'user login successfully',
token:jwtToken
});
}
});
} else {
console.log('error commit');
console.log("error: ", error);
result(null, error);
}
});
};
just change the res from the call back of sq.query to dataResult, because once you send the res.send... then for sure in your case res was the dataResult of the sql.
exports.login = function(req, res, next) {
let q = "SELECT * from users WHERE email = ?";
let query = sql.query(q,req.body.email, (error, dataResult) => {
if(error){
console.log('error commit');
console.log("error: ", error);
res.status(400).send({error});
}
if (dataResult && dataResult.length > 0) {
bcrypt.compare(req.body.password, dataResult[0].password,
function(err, result){
if(err) {
console.log('password dost not match');
console.log("error: ", err);
res.status(400).send({err});
}
if(result) {
console.log('pasword match');
const jwtToken = jwt.sign({
email: dataResult[0].email,
id: dataResult[0].id
},
'secret',
{
expiresIn: '2h'
});
//tk = jwtToken;
return res.status(200).json({
error:0,
message:'user login successfully',
token:jwtToken
});
}
}else{
res.status(400).send({error:'error occured no email
found'});
}
});
});
};

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);
}
}
})
})

Can't get data form nodejs by angular

Hi I can't get data from nodejs by angular 6.
I added a service to connect between them but it is not working.
I succeed to get data by nodejs server, but I can't receive it on angular components.
I know that I missed something to connect between them but I can't resolve it.
HostingstartComponent.ts
import { Component, OnInit } from '#angular/core';
import { NgAnalyzedFile } from '#angular/compiler';
import {RouterModule ,Routes } from '#angular/router';
import {HttpModule, Http} from '#angular/http'
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { SecComponent } from '../sec/sec.component';
import { ThirdComponent } from '../third/third.component';
import {aService} from '../services/a.service';
#Component({
selector: 'app-hostingstart',
templateUrl: './hostingstart.component.html',
styleUrls: ['./hostingstart.component.css']
})
export class HostingstartComponent implements OnInit {
aService: any;
data: any;
appRoutes : Routes=[
{path: 'hostingstar',component : HostingstartComponent},
{path: '',component : HostingstartComponent},
{path: 'sec',component : SecComponent, data : {some_data : 'some value'}},
{path: 'third',component : ThirdComponent, data : {some_data : 'some value'}}
];
headImg : any="assets/images/pan.JPG";
constructor(private http: Http , private service: aService) {
this.headImg ="assets/images/pan.JPG";
// this.aService.getData().then( (result) => {this.data = result; });
}
ngOnInit() {
// alert(this.aService.getData());
// this.aService.getData().then( (result) => {this.data = result; });
// alert(this.data);
}
myFunc() {
//this.router.navigate(['/third', 'north']);
// alert( document.getElementById("search-input").value);
}
getData() {
this.aService.getData().subscribe((dataFromServer) => {
this.data=dataFromServer;
// Now you can use the data
// alert(dataFromServer)
console.log(dataFromServer);
});
}
}
aService.ts
import 'rxjs/add/operator/toPromise';
import { Http, Response, Headers } from '#angular/http';
import { Injectable } from '#angular/core';
#Injectable()
export class aService {
constructor(private http: Http) {
}
async getData() {
const options = {
headers: new Headers({
'Content-Type': 'application/json;charset=utf-8',
'Access-Control-Allow-Origin': '*'
})
};
// const url = './assets/heroes.data.json';
const url = 'http://localhost:3000/';
return this.http.get(url, options)
.toPromise()
.then(response => {
if (response != null) {
const result = response.json();
return Promise.resolve(result);
}
return [];
})
.catch(err => {
console.warn('error in getCats', err);
return Promise.reject(null);
});
}
}
Node js : index.js
console.log('Running File: index.js')
//-- Create Express Server:
var express = require('express');
var app = express();
var util = require('util');
var mysql = require('mysql');
var a;
var con = mysql.createConnection({
host : 'localhost',
user: 'node',
password : 'arafat1990!##$',
database: "iTour"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM feedback", function (err, result, fields) {
if (err) throw err;
// console.log(result);
a=result;
});
});
//-- Map Base URL to res (Response)
app.get('/', function(req, res){
var fname = req.query.fname;
var lname = req.query.lname;
var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
res.send(a);
});
app.get('/hostingstar', function(req, res){
var fname = req.query.fname;
var lname = req.query.lname;
var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
res.send(a);
});
//-- Listen on Port 3000:
app.listen(3000);
app.js
const express = require('express');
const app = express();
//const firebase = require('firebase-admin');
app.get('/hostingstart', (req, res) => res.send('Server Is Active!'))
app.get('/hostingstart', (req, res) => {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user: 'node',
password : 'arafat1990!##$',
database: "iTour"
});
connection.connect();
connection.query('SELECT * FROM feedback;', function (error, results, fields) {
if (error) {
console.warn(error);
res.send('');
return;
}
console.log("Result: " + results);
res.send(results);
});
connection.end();
})
app.get('/hostingstart', (req, res) => {
var ref = firebase.app().database().ref();
ref.once("value").then(function (snap) {
console.log("snap.val()", snap.val());
res.send(snap.val());
});
});
app.use(function(req, res, next){
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
// Check if preflight request
if (req.method === 'OPTIONS') {
res.status(200);
res.end();
}
else {
next();
}
});
app.listen(3000, () => console.log('Server is listening on port 3000!'))
In your getService method you are calling the service itself not the property from the constructor.
Your:
this.aService.getData()
Should be:
this.service.getData()
Additionally call myFunc() in ngOnInit
ngOnInit() {
this.myFunc()
}