fix: User Name always be unique

feat : customer can login with user name or customer number
This commit is contained in:
2025-10-25 16:58:40 +05:30
parent 08e47e2e92
commit 9f2f557b03
2 changed files with 23 additions and 3 deletions

View File

@@ -9,10 +9,10 @@ const { setJson, getJson } = require('../config/redis');
async function login(req, res) {
const { customerNo, password, otp } = req.body;
let { customerNo, userName, password, otp } = req.body;
const loginType = req.headers['x-login-type'] || 'standard';
if (!customerNo || !password) {
if ((!customerNo && !userName) || !password) {
return res.status(400).json({ error: 'customerNo and password are required' });
}
const currentTime = new Date().toISOString();
@@ -22,6 +22,17 @@ async function login(req, res) {
// --- Step 1: Check if user is already locked ---
const blockedKey = `login:blocked:${customerNo}`;
const attemptsKey = `login:attempts:${customerNo}`;
if (!customerNo && userName) {
const result = await db.query('SELECT * FROM users WHERE preferred_name = $1', [
userName,
]);
if (result.rows.length === 0) {
logger.error("Customer not found with this user name.");
return res.status(404).json({ error: 'No user found with this username.' });
}
logger.info("Customer found with user name.");
customerNo = result.rows[0].customer_no;
}
const userCheck = await authService.findUserByCustomerNo(customerNo);
@@ -29,6 +40,7 @@ async function login(req, res) {
// check DB locked flag
if (userCheck && userCheck.locked) {
await setJson(blockedKey, true, BLOCK_DURATION);
logger.error("USER Account Locked");
return res.status(423).json({
error: 'Your account is locked. Please contact the administrator.',
});
@@ -275,6 +287,11 @@ async function setUserName(req, res) {
}
const userNameIsExits = await authService.CheckUserName(customerNo);
const { user_name } = req.body;
if (!user_name) {
return res.status(400).json({ error: 'Username is required' });
}
if (!userNameIsExits) {
await authService.setUserName(customerNo, user_name);
logger.info('User name has been set for first time.');
@@ -292,7 +309,7 @@ async function setUserName(req, res) {
// Cannot match last 2
const lastTwo = history.slice(0, 2);
if (lastTwo.includes(user_name.toLowerCase())) {
return res.status(409).json({ error: "Preferred name cannot match last 2 preferred names"});
return res.status(409).json({ error: "Preferred name cannot match last 2 preferred names" });
}
await authService.setUserName(customerNo, user_name);
logger.info('User name has been updated.');

View File

@@ -157,6 +157,9 @@ async function setUserName(customerNo, username) {
);
logger.info("preferred_name_history table updated");
} catch (error) {
if (error.code === '23505') {
throw new Error('PREFERRED_NAME_ALREADY_EXISTS');
}
throw new Error(
`error occured while setting new preferred name ${error.message}`
);