What could be problem? even though i input the valid username and password it returns the message:"Invalid Username or Password".
THIS IS THE CODE:
const { validationResult } = require("express-validator"); //check for validation errors
const jwt = require("jsonwebtoken"); //used to create and verify JWTs for authentication
const bcrypt = require("bcryptjs"); //used to hash and compare passwords securely
const config = require("../config/auth.config");//import auth.config.js
const db = require("../models/index.js");//database configuration and models from index.js
const refreshTokenModel = require("../models/refreshToken.model");//imports a module
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 express-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]
);
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 =>
["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" });
}
};
exports.logout = async (req, res) => {
try {
console.log("Logout request received:", req.body);
const { refreshToken } = req.body;
//check if the refresh token is provided if not it will return an error message
if (!refreshToken) {
console.log("No refresh token provided.");
return res.status(400).json({ message: "Refresh token is required!" });
}
console.log("Checking if refresh token exists in database:", refreshToken);
const [tokens] = await db.query("SELECT * FROM refresh_tokens WHERE token = ?", [refreshToken]);
if (tokens.length === 0) {
console.log("Refresh token not found in database.");
return res.status(404).json({ message: "Refresh token not found or already logged out." });
}
console.log("Deleting refresh token:", refreshToken);
await db.query("DELETE FROM refresh_tokens WHERE token = ?", [refreshToken]);
console.log("User logged out successfully.");
res.status(200).json({ message: "User logged out successfully!" });
} catch (err) {
console.error("Logout Error:", err);
res.status(500).json({ message: "Internal server error" });
}
};
exports.refreshToken = async (req, res) => {
try {
console.log("Refresh token request received:", req.body);
const { refreshToken } = req.body;
if (!refreshToken) {
console.log("No refresh token provided.");
return res.status(403).json({ message: "Refresh Token is required!" });
}
console.log("Checking refresh token in database:", refreshToken);
const tokenRow = await refreshTokenModel.findByToken(refreshToken);
if (!tokenRow) {
console.log("Refresh token not found in database.");
return res.status(403).json({ message: "Refresh token is not in database!" });
}
// Check if the token is expired
if (refreshTokenModel.verifyExpiration(tokenRow)) {
console.log("Refresh token expired. Deleting and generating a new one.");
await refreshTokenModel.deleteExpiredTokens(tokenRow.id);
const newRefreshToken = await refreshTokenModel.createToken(tokenRow.adminId);
console.log("New refresh token generated:", newRefreshToken);
return res.status(200).json({
message: "Refresh token expired. A new one has been issued.",
refreshToken: newRefreshToken,
});
}
console.log("Fetching user associated with refresh token...");
const [admins] = await db.query(
"SELECT * FROM admin WHERE id = ?",
[tokenRow.adminId]
);
if (!admins.length) {
console.log("User not found for refresh token.");
return res.status(404).json({ message: "User not found" });
}
console.log("Generating new access token...");
const newAccessToken = jwt.sign({ id: admins[0].id }, config.secret, {
expiresIn: config.jwtExpiration,
});
console.log("New access token generated successfully.");
res.status(200).json({ accessToken: newAccessToken, refreshToken });
} catch (err) {
console.error("Refresh Token Error:", err);
res.status(500).json({ message: "Internal server error" });
}
};
THIS IS THE CODE:
const { validationResult } = require("express-validator"); //check for validation errors
const jwt = require("jsonwebtoken"); //used to create and verify JWTs for authentication
const bcrypt = require("bcryptjs"); //used to hash and compare passwords securely
const config = require("../config/auth.config");//import auth.config.js
const db = require("../models/index.js");//database configuration and models from index.js
const refreshTokenModel = require("../models/refreshToken.model");//imports a module
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 express-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]
);
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" });
}
};
exports.logout = async (req, res) => {
try {
console.log("Logout request received:", req.body);
const { refreshToken } = req.body;
//check if the refresh token is provided if not it will return an error message
if (!refreshToken) {
console.log("No refresh token provided.");
return res.status(400).json({ message: "Refresh token is required!" });
}
console.log("Checking if refresh token exists in database:", refreshToken);
const [tokens] = await db.query("SELECT * FROM refresh_tokens WHERE token = ?", [refreshToken]);
if (tokens.length === 0) {
console.log("Refresh token not found in database.");
return res.status(404).json({ message: "Refresh token not found or already logged out." });
}
console.log("Deleting refresh token:", refreshToken);
await db.query("DELETE FROM refresh_tokens WHERE token = ?", [refreshToken]);
console.log("User logged out successfully.");
res.status(200).json({ message: "User logged out successfully!" });
} catch (err) {
console.error("Logout Error:", err);
res.status(500).json({ message: "Internal server error" });
}
};
exports.refreshToken = async (req, res) => {
try {
console.log("Refresh token request received:", req.body);
const { refreshToken } = req.body;
if (!refreshToken) {
console.log("No refresh token provided.");
return res.status(403).json({ message: "Refresh Token is required!" });
}
console.log("Checking refresh token in database:", refreshToken);
const tokenRow = await refreshTokenModel.findByToken(refreshToken);
if (!tokenRow) {
console.log("Refresh token not found in database.");
return res.status(403).json({ message: "Refresh token is not in database!" });
}
// Check if the token is expired
if (refreshTokenModel.verifyExpiration(tokenRow)) {
console.log("Refresh token expired. Deleting and generating a new one.");
await refreshTokenModel.deleteExpiredTokens(tokenRow.id);
const newRefreshToken = await refreshTokenModel.createToken(tokenRow.adminId);
console.log("New refresh token generated:", newRefreshToken);
return res.status(200).json({
message: "Refresh token expired. A new one has been issued.",
refreshToken: newRefreshToken,
});
}
console.log("Fetching user associated with refresh token...");
const [admins] = await db.query(
"SELECT * FROM admin WHERE id = ?",
[tokenRow.adminId]
);
if (!admins.length) {
console.log("User not found for refresh token.");
return res.status(404).json({ message: "User not found" });
}
console.log("Generating new access token...");
const newAccessToken = jwt.sign({ id: admins[0].id }, config.secret, {
expiresIn: config.jwtExpiration,
});
console.log("New access token generated successfully.");
res.status(200).json({ accessToken: newAccessToken, refreshToken });
} catch (err) {
console.error("Refresh Token Error:", err);
res.status(500).json({ message: "Internal server error" });
}
};