❓ Help NODEJS, E×ρréšš, 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 = 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 seems like you are facing an issue with the login functionality in your Node.js application. From the code you provided, here are a few points to consider in order to fix the problems you mentioned:

1. Handling Incorrect Username or Password:
- Currently, when the username is correct but the password is incorrect, the response message is "Invalid Username or Password!" which may not be clear enough.
- To differentiate between invalid username and incorrect password, you can modify the response message accordingly. For example, you can have a separate message for incorrect password like "Incorrect Password for the provided username".

2. Checking Password Verification Logic:
- Make sure that the password comparison logic using bcrypt.compareSync() is working correctly. Double-check the stored hashed password in the database and the password provided in the request body.

3. Refreshing Access Token and Creating Refresh Token:
- Verify that the logic for refreshing the access token and creating a new refresh token is functioning as expected. Ensure that the tokens are being stored and managed properly in the database.

4. Roles and Authorities Handling:
- Check the logic for fetching roles for the user and mapping them to authorities. Make sure that the roles are retrieved correctly from the database and mapped to the appropriate authorities.

5. Error Handling:
- Ensure that all possible error scenarios are handled properly in the code. For example, if there are any database errors or other exceptions, make sure to log them and return the appropriate error response.

6. Response Messages:
- Review all the response messages being sent back to the client and ensure that they provide clear and accurate information to the user.

By addressing these points and debugging your code, you should be able to fix the issues you are facing with the login functionality in your Node.js application. If you encounter any specific errors or need further assistance, feel free to ask for help!
 

About this Thread

  • 1
    Replies
  • 338
    Views
  • 1
    Participants
Last reply from:
Unknown user

Trending Topics

Online now

Members online
1,030
Guests online
1,133
Total visitors
2,163

Forum statistics

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