❓ Help Nodejs, E×ρréšš, MySQL

Bearmy

Established
error sa signin maling username nalabas ang invalid password or usename sa postman pero pagmali ang password nakakapag login kaya dapat nalabas din ang invalid password or usename sa postman. PLS FIX THIS PROBLEM.
exports.signin = async (req, res) => {
console.log("Signin request received:", req.body);
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log("Validation errors:", errors.array());
return res.status(400).json({ errors: errors.array() });
}//this uses E×ρréšš-validator to check for validation errors like missing fields or invalid data
try {
const { username, password } = req.body;
const [admins] = await db.query(
"SELECT * FROM admin WHERE username = ?",
[username.trim()]
);
console.log("Admin Query Result:", admins);
if (!admins||admins.length === 0) {
console.log("Invalid Username or Password!");
return res.status(401).json({ message: "Invalid Username or Password!" });
}

const admin = admins[0];
if (admin.status === "Disabled") {
console.log("Account is disabled:", admin.username);
return res.status(403).json({ message: "Your account has been disabled. Please contact admin." });
}
console.log("Comparing passwords for:", admin.username);
console.log("Stored Hashed Password:", admin.password);
console.log("Entered Password:", password);
const isPasswordValid = bcrypt.compareSync(password, admin.password);
console.log("Password Match Result:", isPasswordValid);
if (!isPasswordValid) {
console.log("Incorrect password for user:", admin.username);
return res.status(401).json({ message: "Invalid Username or Password!" });
}
console.log("Generating access token...");
const accessToken = jwt.sign({ id: admin.id }, config.secret, {
algorithm: "HS256",
expiresIn: config.jwtExpiration,
});
console.log("Checking existing refresh token for user:", admin.id);
const [existingTokens] = await db.query(
"SELECT * FROM refresh_tokens WHERE adminId = ?",
[admin.id]
);
let refreshToken;
if (existingTokens.length > 0) {
const existingToken = existingTokens[0];
if (!refreshTokenModel.verifyExpiration(existingToken)) {
console.log("Reusing existing refresh token.");
refreshToken = existingToken.token;
} else {
console.log("Existing refresh token expired, creating a new one.");
await refreshTokenModel.deleteExpiredTokens(existingToken.id);
refreshToken = await refreshTokenModel.createToken(admin.id);
}
} else {
console.log("No existing refresh token, creating a new one.");
refreshToken = await refreshTokenModel.createToken(admin.id);
}
console.log("Fetching roles for:", admin.username);
const [roles] = await db.query(
`SELECT r.name FROM roles r INNER JOIN
admin_roles ur ON r.id = ur.roleId
WHERE ur.adminId = ?`,
[admin.id]
);
console.log("Roles Found:", roles);
const authorities = roles.length
? roles.map(role => ROLE_${role.name.toUpperCase()}) :
["NO_ROLE_ASSIGNED"];
console.log("Signin successfully for:", admin.username);
res.status(200).json({
id: admin.id,
username: admin.username,
role: authorities,
status: admin.status,
accessToken,
refreshToken,
});//this is a success message will be sent in Postman
} catch (err) {
console.error("Signin Error:", err);
res.status(500).json({ message: "Internal server error" });
}
};
 
It appears that the issue you are facing is related to how the error messages are handled in your signin function when an invalid username or password is provided. To ensure that Postman displays the appropriate error message when an invalid password is entered, you should make some adjustments to your code.

Here are the steps you can take to address this problem:

1. Modify the error handling logic after checking if the user with the provided username exists in the database. You need to check for the case when the user exists but the password is incorrect.

JavaScript:
if (!admins || admins.length === 0) {
  console.log("Invalid Username or Password!");
  return res.status(401).json({ message: "Invalid Username or Password!" });
}

const admin = admins[0];    
if (admin.status === "Disabled") {
  console.log("Account is disabled:", admin.username);
  return res.status(403).json({ message: "Your account has been disabled. Please contact admin." });
}

console.log("Comparing passwords for:", admin.username);
console.log("Stored Hashed Password:", admin.password);
console.log("Entered Password:", password);
const isPasswordValid = bcrypt.compareSync(password, admin.password);
console.log("Password Match Result:", isPasswordValid);
if (!isPasswordValid) {
  console.log("Incorrect password for user:", admin.username);
  return res.status(401).json({ message: "Invalid Username or Password!" });
}

2. By adding the above code snippet, you are explicitly checking if the password provided by the user matches the hashed password stored in the database. If the passwords do not match, the function will return a 401 status code with the message "Invalid Username or Password!".

By making these adjustments, you can ensure that Postman displays the correct error message when an invalid password is entered during the sign-in process.
 
It appears that the issue you are facing is related to how the error messages are handled in your signin function when an invalid username or password is provided. To ensure that Postman displays the appropriate error message when an invalid password is entered, you should make some adjustments to your code.

Here are the steps you can take to address this problem:

1. Modify the error handling logic after checking if the user with the provided username exists in the database. You need to check for the case when the user exists but the password is incorrect.

JavaScript:
if (!admins || admins.length === 0) {
  console.log("Invalid Username or Password!");
  return res.status(401).json({ message: "Invalid Username or Password!" });
}

const admin = admins[0];   
if (admin.status === "Disabled") {
  console.log("Account is disabled:", admin.username);
  return res.status(403).json({ message: "Your account has been disabled. Please contact admin." });
}

console.log("Comparing passwords for:", admin.username);
console.log("Stored Hashed Password:", admin.password);
console.log("Entered Password:", password);
const isPasswordValid = bcrypt.compareSync(password, admin.password);
console.log("Password Match Result:", isPasswordValid);
if (!isPasswordValid) {
  console.log("Incorrect password for user:", admin.username);
  return res.status(401).json({ message: "Invalid Username or Password!" });
}

2. By adding the above code snippet, you are explicitly checking if the password provided by the user matches the hashed password stored in the database. If the passwords do not match, the function will return a 401 status code with the message "Invalid Username or Password!".

By making these adjustments, you can ensure that Postman displays the correct error message when an invalid password is entered during the sign-in process.
What if hashed password does not match that is stored in database what will I do to fix it?
 
What if hashed password does not match that is stored in database what will I do to fix it?
If the hashed password provided by the user does not match the hashed password stored in the database during the sign-in process, you can handle this situation by returning an appropriate error message to the user. Here's how you can modify your code to handle this scenario:

JavaScript:
console.log("Comparing passwords for:", admin.username);
console.log("Stored Hashed Password:", admin.password);
console.log("Entered Password:", password);
const isPasswordValid = bcrypt.compareSync(password, admin.password);

if (!isPasswordValid) {
  console.log("Incorrect password for user:", admin.username);
  return res.status(401).json({ message: "Invalid Password" });
}

By including the code snippet above, you are explicitly checking if the hashed password provided by the user matches the hashed password stored in the database. If they do not match, the function will return a 401 status code with the message "Invalid Password". This will inform the user that the password they entered is incorrect.

Additionally, you may want to consider enhancing the security of your application by implementing measures such as rate limiting login attempts, locking the account after a certain number of failed attempts, and enforcing strong password policies. These measures can help prevent unauthorized access to user accounts.
 

About this Thread

  • 3
    Replies
  • 370
    Views
  • 1
    Participants
Last reply from:
Unknown user

Trending Topics

Online now

Members online
937
Guests online
1,541
Total visitors
2,478

Forum statistics

Threads
2,272,873
Posts
28,946,022
Members
1,236,448
Latest member
woww989
Back
Top