❓ Help Nodejs, E×ρréšš, and mysql

Bearmy

Established
may error sa signin kapag maling username nalabas ang invalid password or usename sa postman kaya tama ito pero pagmali ang password nakakapag login kaya dapat nalabas din ang invalid password or usename sa postman pero kapag nilagay ko parehas ang tamang password at username Invalid Username or Password pa rin ang nalabas. 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 = await bcrypt.compare(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 seems like you are encountering an issue with the behavior of the signin functionality in your Node.js application when handling invalid username/password combinations. Let's address the problems you mentioned and provide some suggestions for improvement:

1. Issue 1: Incorrect Error Response for Invalid Password
- Currently, when the user enters an incorrect password, the response returned is "Invalid Username or Password!" instead of specifically indicating that the password is incorrect.
- To fix this, you should modify the error message to differentiate between invalid username and incorrect password cases. You can update the error message to be more specific, like "Incorrect Password for the User".

2. Issue 2: Incorrect Response for Correct Username and Password
- Even when the correct username and password are provided, the response returned is still "Invalid Username or Password!".
- This issue may arise due to the comparison logic or the way the query results are handled.

3. Suggested Improvements:
- After checking for an invalid username, you should proceed to validate the password only if a user with the provided username exists.
- Ensure that the comparison of the hashed password is done correctly using bcrypt.compare.
- When the username and password are valid, generate the access token and refresh token only once both credentials are verified.

Here's a modified snippet of your signin function with the suggested improvements:

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

const admin = admins[0];
const isPasswordValid = await bcrypt.compare(password, admin.password);

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

// Generate tokens only if both username and password are valid
console.log("Generating access token...");
const accessToken = jwt.sign({ id: admin.id }, config.secret, {
    algorithm: "HS256",
    expiresIn: config.jwtExpiration,
});

// Remaining token generation logic...

console.log("Signin successful for:", admin.username);
res.status(200).json({
    id: admin.id,
    username: admin.username,
    role: authorities,
    status: admin.status,
    accessToken,
    refreshToken,
});

By implementing these changes, you should have a more accurate error handling mechanism for invalid usernames and passwords, as well as improved logic for successful sign-ins.
 
Eto ang result

Signin request received: { username: 'Donnel', password: '#ABCrty#' }
Admin Query Result: [
{
id: 56,
username: 'Donnel',
password: '$2b$08$ou.7I6/L39CkieZW9ITsleUkTZLNdsSOjbOzu2ceVEB',
role: 'Admin',
status: 'Active',
createdOn: 2025-05-02T08:12:49.000Z,
updatedOn: 2025-05-02T08:12:49.000Z
}
]
Comparing passwords for: Donnel
Stored Hashed Password: $2b$08$ou.7I6/L39CkieZW9ITsleUkTZLNdsSOjbOzu2ceVEB
Entered Password: #ABCrty#
Password Match Result: false
Invalid Username or Password!
 

About this Thread

  • 2
    Replies
  • 238
    Views
  • 1
    Participants
Last reply from:
Bearmy

Trending Topics

Online now

Members online
1,024
Guests online
1,131
Total visitors
2,155

Forum statistics

Threads
2,272,806
Posts
28,945,415
Members
1,236,418
Latest member
yesitsme
Back
Top