29 Commits

Author SHA1 Message Date
759869b0e3 feat : Add api for E-mandate Validation 2025-11-12 13:00:53 +05:30
739f2737ba fix: migrated users default password 2025-11-11 01:50:42 +05:30
6b80ef83b4 feat: default password for migrated users 2025-11-10 20:35:41 +05:30
a28c08f8b2 fix: set tnc accepted api 2025-11-10 12:20:04 +05:30
f922179765 fix: change tpin match with hashing and not directly 2025-11-08 20:28:21 +05:30
b9c9d35f74 fix: added await in calling set tpin 2025-11-08 20:27:37 +05:30
c39492edde feat: implemented routes for getting and setting customer tnc flag 2025-11-08 18:39:39 +05:30
3f86697f6b feat: added mobile tnc flag in login response 2025-11-08 02:44:56 +05:30
c021d6033c refactor: added remaining time in beneficiary cooldown failure response 2025-11-08 02:22:26 +05:30
55c822487b feat: added change tpin route 2025-11-08 02:08:49 +05:30
0164aad402 added beneficiary payment middleware to neft, rtgs, imps and transfer routes 2025-11-08 02:07:45 +05:30
f7bc0f6785 added middleware to check if the transaction is within cooldown period 2025-11-08 02:06:17 +05:30
95fc26ef6b feat: added beneficiary creation date and time in the api response to manage cooldown at frontend 2025-11-08 02:04:48 +05:30
caef3bd690 fix: added beneficiary create date in beneficiary list payload 2025-11-07 16:01:07 +05:30
2c210f07c7 fix: add template 2025-11-04 12:11:01 +05:30
ea1d7dae85 feat: Limit of trasnaction 2025-11-04 11:12:55 +05:30
a53bca4a34 changed npci reponse body and added redis url to config 2025-11-03 13:27:51 +05:30
43cce9f04a feat : add x header for admin 2025-10-30 11:24:46 +05:30
05db88f409 fix: remove details from api 2025-10-29 15:57:21 +05:30
2cc1f3fcad feat: added details of customer 2025-10-29 15:41:17 +05:30
f807f62660 fix: Add X-header for EMandate.
wip: add message template
2025-10-29 15:34:54 +05:30
654b4ddaf7 added two routes for getting and setting the daily limit of users 2025-10-28 17:59:22 +05:30
7757b464b3 feat: added daily limit feature 2025-10-28 15:45:01 +05:30
9f2f557b03 fix: User Name always be unique
feat : customer can login with user name or customer number
2025-10-25 16:58:40 +05:30
08e47e2e92 feat : customer can set User Name
feat : customer can update username.
wip : update the SMS template for user name.
2025-10-24 13:04:58 +05:30
96af9ff264 fix : users are locked after three failed login attempts. 2025-10-21 16:41:54 +05:30
75ebcf8407 feat : users are locked after three failed login attempts. 2025-10-21 16:21:41 +05:30
b63860e22e fix: changed sms backend to use different server 2025-10-10 18:00:28 +05:30
2d434b9198 feat: login IB by two step verification
chore: add message template
2025-10-10 17:27:00 +05:30
26 changed files with 650 additions and 60 deletions

View File

@@ -1,7 +1,10 @@
{
"cSpell.words": [
"emandate",
"MPIN",
"occured",
"otpgenerator",
"TLIMIT",
"tpassword",
"tpin",
"TPWORD"

View File

@@ -3,6 +3,7 @@ const cors = require('cors');
const { logger } = require('./util/logger');
const routes = require('./routes');
const helmet = require('helmet');
const { verifyClient } = require('./middlewares/clientVerifier.middleware');
const app = express();
@@ -11,7 +12,7 @@ app.use(helmet());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/api', routes);
app.use('/api', verifyClient, routes);
app.get('/health', (_, res) => res.send('server is healthy'));
app.use((err, _req, res, _next) => {
logger.error(err, 'uncaught error');

View File

@@ -6,5 +6,6 @@ dotenv.config({ path: path.resolve(__dirname, '../../.env') });
module.exports = {
port: process.env.PORT || 8080,
dbUrl: process.env.DATABASE_URL,
redisUrl: process.env.REDIS_URL,
jwtSecret: process.env.JWT_SECRET,
};

View File

@@ -4,34 +4,126 @@ const { logger } = require('../util/logger');
const db = require('../config/db');
const dayjs = require('dayjs');
const { comparePassword } = require('../util/hash');
const customerController = require('../controllers/customer_details.controller.js');
const { setJson, getJson } = require('../config/redis');
async function login(req, res) {
const { customerNo, password } = 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();
const MAX_ATTEMPTS = 3; // Max invalid attempts before lock
const BLOCK_DURATION = 15 * 60 * 60; // 1 day
try {
const isMigratedUser = await authService.isMigratedUser(customerNo);
if (isMigratedUser)
// --- 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);
if (!userCheck) {
return res.status(404).json({ error: 'customer not found' });
}
if (loginType.toUpperCase() === 'IB') {
// 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.',
});
}
}
// --- Step 2: Check migration status
const migratedPassword = `${userCheck.customer_no}@KCCB`;
const isMigratedUser = userCheck.password_hash === migratedPassword;
if (isMigratedUser) {
if (password !== migratedPassword)
return res.status(401).json({ error: 'Invalid credentials.' });
return res.status(401).json({ error: 'MIGRATED_USER_HAS_NO_PASSWORD' });
}
// --- Step 3: Validate credentials ---
const user = await authService.validateUser(customerNo, password);
if (!user || !password)
return res.status(401).json({ error: 'INVALID_CREDENTIALS' });
if (!user) {
if (loginType.toUpperCase() === 'IB') {
let attempts = (await getJson(attemptsKey)) || 0;
attempts += 1;
if (attempts >= MAX_ATTEMPTS) {
await db.query(
'UPDATE users SET locked = true WHERE customer_no = $1',
[customerNo]
);
await setJson(blockedKey, true, BLOCK_DURATION);
await setJson(attemptsKey, 0);
return res.status(423).json({
error:
'Your account has been locked due to multiple failed login attempts. Please contact the administrator.',
});
} else {
await setJson(attemptsKey, attempts, BLOCK_DURATION);
return res.status(401).json({
error: `Invalid credentials. ${MAX_ATTEMPTS - attempts} attempt(s) remaining.`,
});
}
} else {
return res.status(401).json({ error: 'Invalid credentials.' });
}
}
// --- Step 4: If login successful, reset Redis attempts ---
await setJson(attemptsKey, 0); // reset counter
const FirstTimeLogin = await authService.CheckFirstTimeLogin(customerNo);
// For registration : if try to login first time after 7 days.
if (FirstTimeLogin && dayjs(user.created_at).diff(currentTime, 'day') > 8)
return res
.status(401)
.json({ error: 'Password Expired.Please Contact with Administrator' });
return res.status(401).json({
error: 'Password Expired.Please Contact with Administrator',
});
// --- Step 5: Get user details (for OTP logic) ---
const userDetails = await customerController.getDetails(customerNo);
const singleUserDetail = userDetails[0];
if (!singleUserDetail?.mobileno)
return res.status(400).json({ error: 'USER_PHONE_NOT_FOUND' });
const mobileNumber = singleUserDetail.mobileno;
// --- Step 6: OTP requirement for IB login ---
if (loginType.toUpperCase() === 'IB' && !otp) {
logger.info(`credential verified but otp required | Type: ${loginType}`);
return res.status(202).json({
status: 'OTP_REQUIRED',
mobile: mobileNumber,
});
}
// --- Step 7: Generate token and update last login ---
const token = generateToken(user.customer_no);
const loginPswExpiry = user.password_hash_expiry;
const mobileTncAccepted = user.tnc_mobile;
const tnc = { mobile: mobileTncAccepted };
const rights = {
ibAccess: user.ib_access_level,
mbAccess: user.mb_access_level,
@@ -41,10 +133,10 @@ async function login(req, res) {
customerNo,
]);
logger.info(`Login successful | Type: ${loginType}`);
res.json({ token, FirstTimeLogin, loginPswExpiry, rights });
return res.json({ token, FirstTimeLogin, loginPswExpiry, rights, tnc });
} catch (err) {
logger.error(err, `login failed | Type: ${loginType}`);
res.status(500).json({ error: 'something went wrong' });
logger.error(err, `login failed | Type: ${loginType}`);
return res.status(500).json({ error: 'something went wrong' });
}
}
@@ -86,7 +178,28 @@ async function setTpin(req, res) {
const { tpin } = req.body;
if (!/^\d{6}$/.test(tpin))
return res.status(400).json({ error: 'INVALID_TPIN_FORMAT' });
authService.setTpin(customerNo, tpin);
await authService.setTpin(customerNo, tpin);
return res.json({ message: 'TPIN_SET' });
} catch (error) {
logger.error(error);
return res.status(500).json({ error: 'SOMETHING_WENT_WRONG' });
}
}
async function changeTpin(req, res) {
const customerNo = req.user;
try {
const user = await authService.findUserByCustomerNo(customerNo);
if (!user) return res.status(404).json({ error: 'USER_NOT_FOUND' });
if (!user.tpin)
return res.status(400).json({ error: 'USER_DOESNT_HAVE_A_TPIN' });
const { oldTpin, newTpin } = req.body;
const isMatch = await comparePassword(oldTpin, user.tpin);
if (!isMatch) return res.status(400).json({ error: 'TPIN_DOESNT_MATCH' });
if (!/^\d{6}$/.test(newTpin))
return res.status(400).json({ error: 'INVALID_TPIN_FORMAT' });
await authService.setTpin(customerNo, newTpin);
return res.json({ message: 'TPIN_SET' });
} catch (error) {
logger.error(error);
@@ -188,13 +301,106 @@ async function changeTransPassword(req, res) {
}
}
async function isUserNameExits(req, res) {
try {
const customerNo = req.user;
const user = await authService.findUserByCustomerNo(customerNo);
if (!user) {
return res.status(404).json({ error: 'USER_NOT_FOUND' });
}
const userName = await authService.CheckUserName(customerNo);
return res.json({ user_name: userName });
} catch (error) {
console.error(error);
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
async function setUserName(req, res) {
const customerNo = req.user;
try {
const user = await authService.findUserByCustomerNo(customerNo);
if (!user) {
return res.status(404).json({ error: 'USER_NOT_FOUND' });
}
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.');
return res.json({ message: 'All set! Your username has been saved.' });
}
if (userNameIsExits) {
const historyRes = await db.query(
'SELECT preferred_name FROM preferred_name_history WHERE customer_no = $1 ORDER BY changed_at DESC LIMIT 5',
[customerNo]
);
// maximum 5 times can changed username
const history = historyRes.rows.map((r) =>
r.preferred_name.toLowerCase()
);
if (history.length >= 5) {
return res
.status(429)
.json({ error: 'Preferred name change limit reached -5 times' });
}
// 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',
});
}
await authService.setUserName(customerNo, user_name);
logger.info('User name has been updated.');
return res.json({ message: 'All set! Your username has been updated.' });
}
} catch (error) {
logger.error(error);
return res.status(500).json({ error: 'CANNOT UPDATE USER NAME' });
}
}
async function getTncAcceptanceFlag(req, res) {
try {
const flag = await authService.getTncFlag(req.user, req.client);
res.json({ tnc_accepted: flag });
} catch (error) {
logger.error(error, 'error occured while getting tnc flag');
res.status(500).json({ error: 'INTERNAL SERVER ERROR' });
}
}
async function setTncAcceptanceFlag(req, res) {
try {
const { flag } = req.body;
if (flag !== 'Y' && flag !== 'N')
res.status(400).json({ error: 'invalid value for flag' });
await authService.setTncFlag(req.user, req.client, flag);
return res.json({ message: 'SUCCESS' });
} catch (error) {
logger.error(error, 'error occured while updating tnc flag');
res.status(500).json({ error: 'INTERNAL SERVER ERROR' });
}
}
module.exports = {
login,
tpin,
setTpin,
changeTpin,
setLoginPassword,
setTransactionPassword,
fetchUserDetails,
changeLoginPassword,
changeTransPassword,
isUserNameExits,
setUserName,
getTncAcceptanceFlag,
setTncAcceptanceFlag,
};

View File

@@ -12,7 +12,8 @@ async function send(
ifscCode,
beneficiaryName,
beneficiaryAcctType = 'SAVINGS',
remarks = ''
remarks = '',
client
) {
try {
const reqData = {
@@ -42,7 +43,8 @@ async function send(
amount,
'',
'',
response.data
response.data,
client
);
return response.data;
} catch (error) {

View File

@@ -11,7 +11,8 @@ async function send(
ifscCode,
beneficiaryName,
remitterName,
remarks
remarks,
client
) {
const commission = 0;
try {
@@ -28,7 +29,7 @@ async function send(
stAddress1: '',
stAddress2: '',
stAddress3: '',
narration: remarks
narration: remarks,
}
);
await recordInterBankTransaction(
@@ -41,7 +42,8 @@ async function send(
commission,
beneficiaryName,
remitterName,
response.data.status
response.data.status,
client
);
return response.data;
} catch (error) {
@@ -49,8 +51,6 @@ async function send(
'API call failed: ' + (error.response?.data?.message || error.message)
);
}
}
module.exports = { send };

View File

@@ -4,11 +4,11 @@ const { logger } = require('../util/logger');
async function npciResponse(req, res) {
const { resp } = req.body;
logger.info(resp, 'received from NPCI');
if (resp.status === 'Success') {
await handleNPCISuccess(resp);
logger.info(req.body, 'received response from NPCI');
if (resp === 'SUCCESS') {
await handleNPCISuccess(req.body);
} else {
await handleNPCIFailure(resp);
await handleNPCIFailure(req.body);
}
res.send('ok');
}

View File

@@ -10,6 +10,7 @@ const templates = require('../util/sms_template');
// Send OTP
async function SendOtp(req, res) {
const {
username,
mobileNumber,
type,
amount,
@@ -20,6 +21,7 @@ async function SendOtp(req, res) {
ref,
date,
userOtp,
PreferName,
} = req.body;
if (!mobileNumber || !type) {
@@ -33,6 +35,10 @@ async function SendOtp(req, res) {
let otp = null;
// Pick template based on type
switch (type) {
case 'LOGIN_OTP':
otp = generateOTP(6);
message = templates.LOGIN_OTP(otp, username);
break;
case 'IMPS':
otp = generateOTP(6);
message = templates.IMPS(otp);
@@ -52,6 +58,10 @@ async function SendOtp(req, res) {
case 'BENEFICIARY_SUCCESS':
message = templates.BENEFICIARY_SUCCESS(beneficiary);
break;
case 'BENEFICIARY_DELETE':
otp = generateOTP(6);
message = templates.BENEFICIARY_DELETE(otp, beneficiary);
break;
case 'NOTIFICATION':
message = templates.NOTIFICATION(acctFrom, acctTo, amount, ref, date);
break;
@@ -71,6 +81,10 @@ async function SendOtp(req, res) {
otp = generateOTP(6);
message = templates.CHANGE_TPWORD(otp);
break;
case 'SET_TPWORD':
otp = generateOTP(6);
message = templates.SET_TPWORD(otp);
break;
case 'CHANGE_MPIN':
otp = generateOTP(6);
message = templates.CHANGE_MPIN(otp);
@@ -86,6 +100,20 @@ async function SendOtp(req, res) {
otp = generateOTP(6);
message = templates.EMandate(otp);
break;
case 'USERNAME_UPDATED':
otp = generateOTP(6);
message = templates.USERNAME_UPDATED(otp);
break;
case 'USERNAME_SAVED':
message = templates.USERNAME_SAVED(PreferName);
break;
case 'TLIMIT':
otp = generateOTP(6);
message = templates.TLIMIT(otp);
break;
case 'TLIMIT_SET':
message = templates.TLIMIT_SET(amount);
break;
default:
return res.status(400).json({ error: 'Invalid OTP type' });
}
@@ -104,10 +132,8 @@ async function SendOtp(req, res) {
if (message.includes('OTP')) {
await setJson(`otp:${mobileNumber}`, otp, 300);
}
logger.info(`Sent OTP [${otp}] for type [${type}] to ${mobileNumber}`);
}
return res.status(200).json({ message: 'Message sent successfully' });
} catch (err) {
logger.error(err, 'Error sending OTP');

View File

@@ -11,7 +11,8 @@ async function send(
ifscCode,
beneficiaryName,
remitterName,
remarks
remarks,
client
) {
const commission = 0;
try {
@@ -28,7 +29,8 @@ async function send(
stAddress1: '',
stAddress2: '',
stAddress3: '',
narration: remarks
narration: remarks,
client,
}
);
await recordInterBankTransaction(
@@ -41,7 +43,8 @@ async function send(
commission,
beneficiaryName,
remitterName,
response.data.status
response.data.status,
client
);
return response.data;
} catch (error) {

View File

@@ -9,7 +9,8 @@ async function transfer(
toAccountType,
amount,
customerNo,
narration = ''
narration = '',
client
) {
try {
const response = await axios.post(
@@ -28,7 +29,8 @@ async function transfer(
toAccountNo,
toAccountType,
amount,
response.data.status
response.data.status,
client
);
return response.data;
} catch (error) {

View File

@@ -0,0 +1,20 @@
const { logger } = require('../util/logger');
function verifyClient(req, res, next) {
const clientHeader = req.headers['x-login-type'];
if (!clientHeader || (clientHeader !== 'MB' && clientHeader !== 'IB' && clientHeader !== 'eMandate' && clientHeader !=='Admin')) {
logger.error(
`Invalid or missing client header. Expected 'MB' or 'IB'. Found ${clientHeader}`
);
return res
.status(401)
.json({ error: 'MISSING OR INVALID CLIENT TYPE HEADER' });
}
req.client = clientHeader;
next();
}
module.exports = { verifyClient };

View File

@@ -0,0 +1,29 @@
const { logger } = require('../util/logger');
const { getSingleBeneficiary } = require('../services/beneficiary.service');
async function checkBeneficiaryCooldown(req, res, next) {
const cooldownTime = parseInt(
process.env.BENEFICIARY_COOLDOWN_TIME || '60',
10
);
const customerNo = req.user;
const { toAccount } = req.body;
const beneficiary = await getSingleBeneficiary(customerNo, toAccount);
if (beneficiary) {
const now = new Date();
const cooldownPeriod = new Date(now.getTime() - cooldownTime * 60 * 1000);
const createdAt = new Date(beneficiary['created_at']);
if (createdAt > cooldownPeriod) {
const remaining = (now - createdAt) / (60 * 1000);
logger.warn('TRANSACTION_FAILED BENEFICIARY_COOLDOWN_ACTIVE');
return res.status(403).json({
remaining,
error: 'beneficiary cooldown period active',
});
}
}
next();
}
module.exports = { checkBeneficiaryCooldown };

View File

@@ -0,0 +1,28 @@
const { logger } = require('../util/logger');
const {
getDailyLimit,
getUsedLimit,
} = require('../services/paymentLimit.service');
async function checkLimit(req, res, next) {
const { amount } = req.body;
const { user, client } = req;
const dailyLimit = await getDailyLimit(user, client);
if (!dailyLimit) {
logger.info('NO LIMIT SET FOR CUSTOMER. ALLOWING TRANSACTIONS');
next();
}
const usedLimit = await getUsedLimit(user, client);
const remainingLimit = dailyLimit - usedLimit;
if (amount > remainingLimit) {
const midnight = new Date();
midnight.setHours(24, 0, 0, 0);
res.set('Retry-After', midnight.toUTCString());
return res.status(403).json({ error: 'Daily limit exhausted' });
}
next();
}
module.exports = { checkLimit };

View File

@@ -8,10 +8,27 @@ router.post('/login', authController.login);
router.get('/user_details', authenticate, authController.fetchUserDetails);
router.get('/tpin', authenticate, authController.tpin);
router.post('/tpin', authenticate, authController.setTpin);
router.post('/change/tpin', authenticate, authController.changeTpin);
router.post('/login_password', authenticate, authController.setLoginPassword);
router.post('/transaction_password',authenticate,authController.setTransactionPassword);
router.post('/change/login_password',authenticate,authController.changeLoginPassword);
router.post('/change/transaction_password',authenticate,authController.changeTransPassword);
router.post(
'/transaction_password',
authenticate,
authController.setTransactionPassword
);
router.post(
'/change/login_password',
authenticate,
authController.changeLoginPassword
);
router.post(
'/change/transaction_password',
authenticate,
authController.changeTransPassword
);
router.get('/user_name', authenticate, authController.isUserNameExits);
router.post('/user_name', authenticate, authController.setUserName);
router.get('/tnc', authenticate, authController.getTncAcceptanceFlag);
router.post('/tnc', authenticate, authController.setTncAcceptanceFlag);
module.exports = router;

View File

@@ -1,5 +1,13 @@
const customerController = require('../controllers/customer_details.controller');
const {
getDailyLimit,
getUsedLimit,
setDailyLimit,
} = require('../services/paymentLimit.service');
const { logger } = require('../util/logger');
const express = require('express');
const router = express.Router();
const customerRoute = async (req, res) => {
const customerNo = req.user;
@@ -12,4 +20,45 @@ const customerRoute = async (req, res) => {
}
};
module.exports = customerRoute;
const limitRoute = async (req, res) => {
const customerNo = req.user;
const client = req.client;
try {
const dailyLimit = await getDailyLimit(customerNo, client);
if (!dailyLimit) {
return res.status(400).json({ error: 'NO DAILY LIMIT SET FOR USER' });
}
const usedLimit = await getUsedLimit(customerNo, client);
res.json({ dailyLimit: dailyLimit, usedLimit: usedLimit });
} catch (err) {
logger.error(err, 'Unknown error encountered while checking daily limit');
res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
};
const limitChangeRoute = async (req, res) => {
const customerNo = req.user;
const client = req.client;
const { amount } = req.body;
const numericLimit = Number(amount);
if (!Number.isFinite(numericLimit)) {
logger.error(`Invalid new Limit, found: ${newLimit}`);
return res
.status(400)
.json({ error: 'NEW LIMIT AMOUNT IS REQUIRED WHEN SETTING LIMIT' });
}
try {
await setDailyLimit(customerNo, client, numericLimit);
return res.status(200).json({ message: 'LIMIT SET' });
} catch (err) {
logger.error(err, 'Unexpected error while setting limit amount');
res.status(500).json({ error: 'INTERNAL SERVER ERROR' });
}
};
router.get('/', customerRoute);
router.get('/daily-limit', limitRoute);
router.post('/daily-limit', limitChangeRoute);
module.exports = router;

View File

@@ -0,0 +1,24 @@
const express = require('express');
const axios = require('axios');
const { logger } = require('../util/logger');
const router = express.Router();
const emandateData = async (req, res) => {
const { data, mandateRequest, mandateType } = req.body;
if (!data || !mandateRequest | !mandateType)
return res.status(404).json({ error: 'DATA NOT FOUND FROM CLIENT' })
try {
const reqData = { data, mandateRequest, mandateType };
const response = await axios.post('http://192.168.1.166:9992/kccb/validation', reqData,
{
headers: { 'Content-Type': 'application/json', },
}
);
logger.info("Data validate");
return response.data;
} catch (error) {
logger.error(error, 'error occured while E-Mandate validation');
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
};
router.post('/validation', emandateData);
module.exports = router;

View File

@@ -3,13 +3,23 @@ const impsController = require('../controllers/imps.controller');
const { logger } = require('../util/logger');
const impsValidator = require('../validators/imps.validator');
const paymentSecretValidator = require('../validators/payment.secret.validator');
const { checkLimit } = require('../middlewares/limitCheck.middleware');
const {
checkBeneficiaryCooldown,
} = require('../middlewares/cooldown.middleware');
const router = express.Router();
router.use(impsValidator, paymentSecretValidator);
router.use(
impsValidator,
paymentSecretValidator,
checkLimit,
checkBeneficiaryCooldown
);
const impsRoute = async (req, res) => {
const { fromAccount, toAccount, ifscCode, amount, beneficiaryName, remarks } =
req.body;
const client = req.client;
try {
const result = await impsController.send(
@@ -20,7 +30,8 @@ const impsRoute = async (req, res) => {
ifscCode,
beneficiaryName,
'SAVINGS',
remarks
remarks,
client
);
if (result.startsWith('Message produced successfully')) {

View File

@@ -1,6 +1,6 @@
const express = require('express');
const authRoute = require('./auth.route');
const adminAuthRoute =require('./admin_auth.route');
const adminAuthRoute = require('./admin_auth.route');
const detailsRoute = require('./customer_details.route');
const transactionRoute = require('./transactions.route');
const authenticate = require('../middlewares/auth.middleware');
@@ -11,11 +11,11 @@ const rtgsRoute = require('./rtgs.route');
const impsRoute = require('./imps.route');
const { npciResponse } = require('../controllers/npci.controller');
const otp = require('./otp.route');
const eMandate = require('./emandate.route');
const router = express.Router();
router.use('/auth', authRoute);
router.use('/auth/admin',adminAuthRoute);
router.use('/auth/admin', adminAuthRoute);
router.use('/customer', authenticate, detailsRoute);
router.use('/transactions/account/:accountNo', authenticate, transactionRoute);
router.use('/payment/transfer', authenticate, transferRoute);
@@ -25,6 +25,6 @@ router.use('/payment/imps', authenticate, impsRoute);
router.use('/beneficiary', authenticate, beneficiaryRoute);
router.use('/npci/beneficiary-response', npciResponse);
router.use('/otp', otp);
router.use('/e-mandate',authenticate,eMandate);
module.exports = router;

View File

@@ -3,9 +3,18 @@ const neftController = require('../controllers/neft.controller');
const { logger } = require('../util/logger');
const neftValidator = require('../validators/neft.validator.js');
const paymentSecretValidator = require('../validators/payment.secret.validator');
const { checkLimit } = require('../middlewares/limitCheck.middleware');
const {
checkBeneficiaryCooldown,
} = require('../middlewares/cooldown.middleware');
const router = express.Router();
router.use(neftValidator, paymentSecretValidator);
router.use(
neftValidator,
paymentSecretValidator,
checkLimit,
checkBeneficiaryCooldown
);
const neftRoute = async (req, res) => {
const {
@@ -15,8 +24,9 @@ const neftRoute = async (req, res) => {
amount,
beneficiaryName,
remitterName,
remarks
remarks,
} = req.body;
const client = req.client;
try {
const result = await neftController.send(
@@ -27,7 +37,8 @@ const neftRoute = async (req, res) => {
ifscCode,
beneficiaryName,
remitterName,
remarks
remarks,
client
);
logger.info(result);

View File

@@ -3,9 +3,18 @@ const rtgsController = require('../controllers/rtgs.controller');
const { logger } = require('../util/logger');
const rtgsValidator = require('../validators/rtgs.validator.js');
const paymentSecretValidator = require('../validators/payment.secret.validator');
const { checkLimit } = require('../middlewares/limitCheck.middleware');
const {
checkBeneficiaryCooldown,
} = require('../middlewares/cooldown.middleware');
const router = express.Router();
router.use(rtgsValidator, paymentSecretValidator);
router.use(
rtgsValidator,
paymentSecretValidator,
checkLimit,
checkBeneficiaryCooldown
);
const rtgsRoute = async (req, res) => {
const {
@@ -15,8 +24,9 @@ const rtgsRoute = async (req, res) => {
amount,
beneficiaryName,
remitterName,
remarks
remarks,
} = req.body;
const client = req.client;
try {
const result = await rtgsController.send(
@@ -27,7 +37,8 @@ const rtgsRoute = async (req, res) => {
ifscCode,
beneficiaryName,
remitterName,
remarks
remarks,
client
);
if (result.status.startsWith('O.K.')) {

View File

@@ -3,12 +3,22 @@ const { logger } = require('../util/logger');
const express = require('express');
const transferValidator = require('../validators/transfer.validator');
const passwordValidator = require('../validators/payment.secret.validator.js');
const { checkLimit } = require('../middlewares/limitCheck.middleware');
const {
checkBeneficiaryCooldown,
} = require('../middlewares/cooldown.middleware');
const router = express.Router();
router.use(passwordValidator, transferValidator);
router.use(
passwordValidator,
transferValidator,
checkLimit,
checkBeneficiaryCooldown
);
const transferRoute = async (req, res) => {
const { fromAccount, toAccount, toAccountType, amount, remarks } = req.body;
const client = req.client;
try {
const result = await transferController.transfer(
fromAccount,
@@ -16,7 +26,8 @@ const transferRoute = async (req, res) => {
toAccountType,
amount,
req.user,
remarks
remarks,
client
);
if (result.status === 'O.K.') {

View File

@@ -1,6 +1,7 @@
const db = require('../config/db');
const { comparePassword, hashPassword } = require('../util/hash');
const dayjs = require('dayjs');
const { logger } = require('../util/logger');
async function findUserByCustomerNo(customerNo) {
const result = await db.query('SELECT * FROM users WHERE customer_no = $1', [
@@ -124,6 +125,73 @@ async function changeTransPassword(customerNo, trans_psw) {
}
}
async function CheckUserName(customerNo) {
try {
const result = await db.query(
'SELECT preferred_name from users WHERE customer_no = $1',
[customerNo]
);
if (result.rows.length > 0) {
return result.rows[0].preferred_name;
} else {
return null;
}
} catch (error) {
throw new Error(
`error occurred while fetch the preferred name ${error.message}`
);
}
}
async function setUserName(customerNo, username) {
const currentTime = dayjs().toISOString();
try {
await db.query(
'UPDATE users SET preferred_name = $1 ,updated_at = $2 WHERE customer_no = $3',
[username, currentTime, customerNo]
);
logger.info('user table updated');
await db.query(
'INSERT INTO preferred_name_history (customer_no, preferred_name) VALUES ($1, $2)',
[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}`
);
}
}
async function getTncFlag(customerNo, clientType) {
let query = '';
if (clientType === 'MB') {
query = 'SELECT tnc_mobile AS tnc_flag FROM users WHERE customer_no = $1';
} else if (clientType === 'IB') {
query = 'SELECT tnc_inb AS tnc_flag FROM users WHERE customer_no = $1';
} else {
throw new Error('UNKNOWN_CLIENT_TYPE. ONLY IB AND MB ALLOWED');
}
const result = await db.query(query, [customerNo]);
return result.rows[0]['tnc_flag'];
}
async function setTncFlag(customerNo, clientType, flag) {
let query = '';
if (clientType === 'MB') {
query = 'UPDATE users SET tnc_mobile = $1 WHERE customer_no = $2';
} else if (clientType === 'IB') {
query = 'UPDATE users SET tnc_inb = $1 WHERE customer_no = $2';
} else {
throw new Error('UNKNOWN_CLIENT_TYPE. ONLY IB AND MB ALLOWED');
}
await db.query(query, [flag, customerNo]);
}
module.exports = {
validateUser,
findUserByCustomerNo,
@@ -136,4 +204,8 @@ module.exports = {
changeLoginPassword,
changeTransPassword,
isMigratedUser,
CheckUserName,
setUserName,
getTncFlag,
setTncFlag,
};

View File

@@ -36,7 +36,7 @@ async function validateOutsideBank(accountNo, ifscCode, name) {
async function getSingleBeneficiary(customerNo, accountNo) {
const queryStr =
'SELECT b.account_no, b.name, b.account_type, b.ifsc_code, i.bank_name, i.branch_name FROM beneficiaries b JOIN ifsc_details i ON b.ifsc_code = i.ifsc_code WHERE customer_no = $1 AND account_no = $2';
'SELECT b.account_no, b.name, b.account_type, b.ifsc_code, b.created_at, i.bank_name, i.branch_name FROM beneficiaries b JOIN ifsc_details i ON b.ifsc_code = i.ifsc_code WHERE customer_no = $1 AND account_no = $2';
const result = await db.query(queryStr, [customerNo, accountNo]);
return result.rows[0];
}
@@ -53,13 +53,14 @@ async function deleteBeneficiary(customerNo, beneficiaryAccountNo) {
async function getAllBeneficiaries(customerNo) {
const queryStr =
'SELECT b.account_no, b.name, b.account_type, b.ifsc_code, i.bank_name, i.branch_name FROM beneficiaries b JOIN LATERAL( SELECT * FROM ifsc_details i WHERE i.ifsc_code = b.ifsc_code LIMIT 1 ) i ON true WHERE customer_no = $1';
'SELECT b.account_no, b.name, b.account_type, b.ifsc_code, b.created_at, i.bank_name, i.branch_name FROM beneficiaries b JOIN LATERAL( SELECT * FROM ifsc_details i WHERE i.ifsc_code = b.ifsc_code LIMIT 1 ) i ON true WHERE customer_no = $1';
const result = await db.query(queryStr, [customerNo]);
const list = result.rows.map((row) => {
const details = {
accountNo: row['account_no'],
name: row['name'],
accountType: row['account_type'],
createdAt: row['created_at'],
};
if (row['ifsc_code'] === '_') {
details['bankName'] = 'THE KANGRA CENTRAL COOPERATIVE BANK LIMITED';

View File

@@ -0,0 +1,38 @@
const db = require('../config/db');
const { logger } = require('../util/logger');
async function getDailyLimit(customerNo, clientType) {
let query = '';
if (clientType === 'IB') {
query = `SELECT inb_limit_amount AS daily_limit FROM users WHERE customer_no = $1`;
} else {
query = `SELECT mobile_limit_amount AS daily_limit FROM users WHERE customer_no = $1`;
}
const result = await db.query(query, [customerNo]);
return result.rows[0].daily_limit;
}
async function getUsedLimit(customerNo, clientType) {
let query = `SELECT SUM(amount::numeric) AS used_limit FROM transactions WHERE created_at BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '1 day') AND customer_no = $1 AND client = $2`;
const result = await db.query(query, [customerNo, clientType]);
const usedLimit = result.rows[0].used_limit;
return Number(usedLimit);
}
async function setDailyLimit(customerNo, clientType, amount) {
let query = '';
if (clientType === 'IB') {
query = `UPDATE users SET inb_limit_amount = $1 WHERE customer_no = $2`;
} else {
query = `UPDATE users SET mobile_limit_amount = $1 WHERE customer_no = $2`;
}
const result = await db.query(query, [amount, customerNo]);
if (result.rowCount === 0) {
throw new Error('No rows affected');
}
logger.info(`set new limit: ${result.rowCount} rows affected`);
}
module.exports = { getDailyLimit, getUsedLimit, setDailyLimit };

View File

@@ -6,11 +6,12 @@ const recordIntraBankTransaction = async (
toAccount,
accountType,
amount,
status
status,
clientType
) => {
const trxType = 'TRF';
const query =
'INSERT INTO transactions (customer_no, trx_type, from_account, to_account, to_account_type, amount, status) VALUES ($1, $2, $3, $4, $5, $6, $7)';
'INSERT INTO transactions (customer_no, trx_type, from_account, to_account, to_account_type, amount, status, client) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)';
await db.query(query, [
customerNo,
trxType,
@@ -19,6 +20,7 @@ const recordIntraBankTransaction = async (
accountType,
amount,
status,
clientType,
]);
};
const recordInterBankTransaction = async (
@@ -31,10 +33,11 @@ const recordInterBankTransaction = async (
commission,
beneficiaryName,
remitterName,
status
status,
clientType
) => {
const query =
'INSERT INTO transactions (customer_no, trx_type, from_account, to_account, ifsc_code, amount, commission, beneficiary_name, remitter_name, status) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)';
'INSERT INTO transactions (customer_no, trx_type, from_account, to_account, ifsc_code, amount, commission, beneficiary_name, remitter_name, status, client) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)';
await db.query(query, [
customerNo,
trxType,
@@ -46,6 +49,7 @@ const recordInterBankTransaction = async (
beneficiaryName,
remitterName,
status,
clientType,
]);
};

View File

@@ -1,4 +1,6 @@
const templates = {
LOGIN_OTP: (otp, username) => `Dear Customer, Your username ${username} have been verified. Please enter the OTP: ${otp} to complete your login. -KCCB `,
IMPS: (otp) => `Dear Customer, Please complete the fund transfer with OTP ${otp} -KCCB`,
NEFT: (otp, amount, beneficiary) =>
@@ -8,7 +10,10 @@ const templates = {
`Dear Customer, Please complete the RTGS of Rs.${amount} to ${beneficiary} with OTP:${otp} -KCCB`,
BENEFICIARY_ADD: (otp, beneficiary, ifsc) =>
`Dear Customer, You have added beneficiary ${beneficiary} ${ifsc} for NEFT/RTGS. Please endorse the beneficiary with OTP ${otp} -KCCB`,
`Dear Customer, You have added beneficiary ${beneficiary} ${ifsc} for IMPS/NEFT/RTGS. Please endorse the beneficiary with OTP ${otp} -KCCB`,
BENEFICIARY_DELETE: (otp, beneficiary) =>
`Dear Customer, you have deleted the beneficiary ${beneficiary} for IMPS/NEFT/RTGS. Please confirm the deletion using OTP ${otp}. - KCCB`,
BENEFICIARY_SUCCESS: (beneficiary) =>
`Dear Customer, Your Beneficiary: ${beneficiary} for Net Banking is added successfully -KCCB`,
@@ -28,7 +33,10 @@ const templates = {
CHANGE_TPWORD: (otp) =>
`Dear Customer, Change Transaction password OTP is ${otp} -KCCB`,
CHANGE_MPIN: (otp) =>
SET_TPWORD: (otp) =>
`Dear Customer, Your Set New Transaction password OTP is ${otp} -KCCB`,
CHANGE_MPIN: (otp) =>
`Dear Customer, Change M-PIN OTP is ${otp} -KCCB`,
REGISTRATION: (otp) =>
@@ -38,7 +46,19 @@ const templates = {
`Dear Customer, Your CIF rights have been updated. Please log in again to access the features. -KCCB`,
EMandate: (otp) =>
`Dear Customer, Your OTP for e-Mandate is ${otp}.It is valid for 1 minute.Do not share this OTP with anyone. -KCCB`
`Dear Customer, Your OTP for e-Mandate is ${otp}.It is valid for 1 minute.Do not share this OTP with anyone. -KCCB`,
USERNAME_UPDATED: (otp) =>
`Dear Customer, Your OTP for updating your Preferred Name is ${otp}. It is valid for 1 minute. Do not share this OTP with anyone. -KCCB`,
USERNAME_SAVED: (PreferName) =>
`Dear Customer, Your Preferred Name -${PreferName} has been updated successfully. If this change was not made by you, please contact our support team immediately.`,
TLIMIT :(otp) =>
`Dear Customer,Please complete the transaction limit set with OTP -${otp}. -KCCB`,
TLIMIT_SET :(amount) =>
`Dear Customer,Your transaction limit for Internet Banking is set to Rs ${amount}. -KCCB`,
};
module.exports = templates;