Having issues comparing user password and hashed password using bcrypt.I'll be glad if anyone helps.
Here is my login code snippet
app.post('/login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
const searchSql2 = 'SELECT * FROM users WHERE user_name = ?'
con.query(searchSql2,[username], async(err, results,fields) => {
if (err) throw err;
const hashedPassword = results[0].user_password
const isValid = bcrypt.compareSync(password, hashedPassword)
if (isValid) {
//password matched
req.session.loggedin = true;
req.session.username = username;
res.redirect('./home')
res.end();
} else {
res.send("Invalid username or password")
}
})
})
When user logins even with correct details he/she gets 'Invalid username or password!'.How do I go about this?
Related
My login.component.ts file
How to set cookies in the code to display the username.
login Submit(){
console.log(this.userLogin.value)
this.service.LoginData(this.userLogin.value).subscribe((res)=>{
console.log(res)
this.userLogin.reset()
this.successmsg = res.message
this.Username = this.cookieService.set('username', this.Username)
})
}
I am trying to display the username but it only see me undefined.
api service file
LoginData(data:any):Observable<any>{
return this.http.post(`http://localhost:3000/login`,data)
}
dashboard(){
return this.http.get('http://localhost:3000/dashboard')
}
NodeJS file using MySQL database
app.post('/login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
const query = `SELECT * FROM user WHERE username = '${username}' AND password = '${password}'`;
db.query(query, (error, result) => {
if (error) {
console.log('Error querying database:', error);
res.status(500).send('Error querying database');
} else if (result.length === 0) {
console.log('Invalid username or password');
res.status(401).send('Invalid username or password');
} else {
console.log('Login successful');
res.status(200).send({
message: 'Login successful',
username: username
});
}
});
res.cookie('username',`${username}`)
});
When the user try to login with wrong email or password my app throw error user not found if the email is not in dB a other error then password is wrong but after few second the server get crashed with the error
"SERVER CONNECTION LOST"
I was Thing the problem come in my error handling but after many try and search i'm now block
export const getUser = (req, res) => {
const token = req.cookies.accessToken;
if (!token) return res.status(401).json("Please logging first !");
jwt.verify(token, "secretkey", (err, data) =\> {
if (err) {
return res.status(403).json("Please login first !!");
}
const q = "SELECT * FROM `Users` WHERE ID= ?";
db.query(q, [req.params.userId], (err, data) => {
if (err) return res.status(500).json("Something when wrong !!");
const { user_PassCode, ...info } = data[0];
if(data) return res.json(info);
});
});
};
//...........LOGIN START HERE...............
export const logIn = (req, res) => {
const q = "SELECT * FROM Users WHERE user_Email = ? "
db.query(q, [req.body.user_Email], (err, data) => {
if (err) res.status(500).json(err)
if(data.length === 0) res.status(404).json('user not found!')
// chech if password match to userPasscode
const checkPassword = bcrypt.compareSync(
req.body.user_PassCode,
data[0].user_PassCode
)
if(!checkPassword) return res.status(400).json('wrong password or username try again!')
const token = jwt.sign({ id: data[0].ID }, "secretkey")
const {user_PassCode, ...others} = data[0]
// if not error
res.cookie("accessToken", token, {
httpOnly: true
}).status(200).json(others)
})
}
I am trying to make a login form. I send the data from frontend like seen here:
const username = loginform.username.value.trim();
const password = loginform.password.value.trim();
console.log(username, password)
Axios.post(apiUrlEndpont, {
username: username,
password: password,
}).then((res) => {
if(res.data.err){
console.log(res.data.err)
} else {
console.log(res)
}
})
I get the username and password successfully. But the SQL query won't work for some reason which I don't recognize.
export default async function handler(req, res) {
const dbConnection = await mysql.createConnection({
host: "localhost",
database: "testapp",
user: "root",
password: "",
socketPath: ""
})
if (req.method === 'POST') {
const username = req.body.username
const password = req.body.password
console.log(username, password)
dbConnection.query(`SELECT password FROM accounts WHERE username = '${username}'`)
.then((err, rows, fields) => {
console.log("asd")
if(rows.length!=0){
var password_hash=rows[0]['password'];
const verified = bcrypt.compareSync(password, password_hash);
if(verified){
res.send(rows[0])
res.end()
} else {
res.send({err: "Invalid password"})
res.end()
}
}else{
res.send({err: "Invalid username password"})
res.end()
}
})
}
}
rows will return undefined even though the username exists in the database.
I am a newbie with node and mysql so please be patient
can you change your code like this and try.
sequelize.query(`SELECT password FROM accounts WHERE username = '${username}'`)
.then(([rows]) => {
console.log(rows);
...
})
I am trying to show data on front end using controller in Angular js but unable to do so I am able to take data from database that is mysql but don't know how to show it on frontend
module.exports = function(app) {
app.post('/login', function(req, res) {
var email = req.body.email;
var password = req.body.password;
console.log(password);
if (email && password) {
connection.query('select * from user where email = ? and password = ?', [email, password], function(err, result) {
console.log(result);
if (err) res.send(err);
res.redirect('/dashboard');
});
}
});
}
I have successfully encrypted the password and stored in my DB during registration. But when I am login, I am comparing the password and trying to login, during the login period my sql query is falling to read the password and I am getting hash is not defined. Please let me know where I am going wrong.
router.post('/login', function(req,res) {
var password = req.body.password;
var user_name = req.body.user_name;
var response = {};
bcrypt.compare(password, hash, function(err, res) {
db.query('select user_id,email FROM user where password = ? AND user_name = ? OR email = ?',
[hash, req.body.user_name, req.body.user_name], function (error,rows) {
if (error) {
res.json(error)
} else {
response.msg = 'Login Success';
}
});
}
});
router.post('/login', function(req,res) {
var password = req.body.password;
var user_name = req.body.user_name;
var response = {};
var hash = db.query('SELECT hash FROM user WHERE user_name = ?', [req.body.user_name]);
bcrypt.compare(password, hash, function(err, res) {
db.query('select user_id,email FROM user where password = ? AND user_name = ? OR email = ?',
[hash, req.body.user_name, req.body.user_name], function (error,rows) {
if (error) {
res.json(error)
} else {
response.msg = 'Login Success';
}
});
}
});