54 Commits

Author SHA1 Message Date
aaa11287a1 feat : admin user rights updated.
feat : update for otp sent for registration.
feat: login Api updated passes "rights" in response
2025-09-05 13:54:25 +05:30
4857ef6cab feat: Change login Password 2025-09-02 16:05:11 +05:30
f60329672c feat : Change login password feature update 2025-09-02 12:52:13 +05:30
9f6c2f9cc1 feat: user can change login password
feat: user can change transaction password
wip : Admin feature rights -InProgress
2025-09-02 12:41:39 +05:30
cb22b926f8 Merge branch 'otp_binding' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/yume_js into admin_api 2025-09-01 13:45:39 +05:30
b213259c7c changed the directory of log directory 2025-09-01 13:38:28 +05:30
90f60f7324 added log files in .gitignore 2025-09-01 13:38:28 +05:30
6533c5081c added logger for logging all kinds of requests with headers, body, ip and other data 2025-09-01 13:38:28 +05:30
33aa50413c fix: check if password is not null on login req 2025-09-01 13:38:28 +05:30
65519e6403 added beneficiary deletion feature 2025-09-01 13:38:28 +05:30
b1f2277c92 fixed a bug where data and pin validations were not called 2025-09-01 13:38:28 +05:30
asif
bb446f41d8 formatted auth route 2025-09-01 13:38:28 +05:30
6e6690746a added imps transactions payment feature 2025-09-01 13:38:28 +05:30
470d8e15f6 fixed typo in rtgs.route.js 2025-09-01 13:38:28 +05:30
a02e58ebec Merge branch 'fetch-from-cbs' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/yume_js into admin_api 2025-08-27 11:55:24 +05:30
780eb39c18 fixed a bug where data and pin validations were not called 2025-08-26 19:24:37 +05:30
asif
3cfcb8e5bc formatted auth route 2025-08-26 19:21:48 +05:30
e179d1b339 Merge branch 'fetch-from-cbs' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/yume_js into admin_api 2025-08-26 12:19:50 +05:30
52225828d0 OTP binding 2025-08-25 11:45:23 +05:30
0d2cea8902 added imps transactions payment feature 2025-08-22 15:31:13 +05:30
1e32b4a5a6 fixed typo in rtgs.route.js 2025-08-20 12:14:40 +05:30
75a0e6e084 Merge branch 'fetch-from-cbs' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/yume_js into admin_api 2025-08-11 12:32:22 +05:30
4ff437319e fixed typo in beneficiary.service 2025-08-11 00:04:36 +05:30
d6a750092c fixed typo in neft.route 2025-08-10 23:29:17 +05:30
de90be86a7 return random names instead of John Doe in beneficiary validation 2025-08-10 23:28:48 +05:30
asif
cbfd1d6d09 integrated acct statement with date range filter 2025-08-10 18:14:46 +05:30
asif
98ab9954bf code formatting in auth.service 2025-08-10 15:38:38 +05:30
asif
2000ec3e4e implemented RTGS payment feature 2025-08-10 15:29:09 +05:30
asif
bfd062be80 removed logger from neft controller 2025-08-10 15:28:37 +05:30
asif
33ef65de32 implemented neft transaction feature 2025-08-10 15:17:44 +05:30
asif
6f07e9beb9 extracted payment password validator from transfer route to its own validator 2025-08-10 15:16:26 +05:30
asif
dbdc1c7829 removed unnecessary async keyword from validators 2025-08-09 21:43:59 +05:30
asif
1bd618b4fd implemented neft.validator.js 2025-08-09 21:41:29 +05:30
asif
6b6b5679bf reformatted transfer.validator.js 2025-08-09 21:41:04 +05:30
asif
7e0c9d251e fixed an error on redis js of undefined err 2025-08-09 20:51:07 +05:30
asif
6e8eccd767 returning a valid response after creating a beneficiary
also throw 409 status code if account already exists in beneficiaries table against that customer
2025-08-09 15:51:28 +05:30
asif
20af204304 changed the beneficiary routes to follow standards
/beneficiary send GET AND POST request for retrieving or adding beneficiaries
2025-08-09 15:50:16 +05:30
asif
9316a41646 made the function validateOutsideBank return beneficiary name rather than refNo
Also removed the now redundant checkBeneficiaryName controller and paths
2025-08-09 13:49:25 +05:30
2d39e1e66d added routes for validating beneficiary outside bank, checking beneficiary name after successful validation and getting beneficiary list of the customer 2025-08-08 20:46:32 +05:30
90cbddd248 added functions for validate outside bank, check beneficiary name and get beneficiary 2025-08-08 20:45:13 +05:30
29d0949039 modified handle NPCI success method to only put the beneficiary name in redis 2025-08-08 20:43:42 +05:30
c331ba5505 changed ifsc_code_bank table name to ifsc_details 2025-08-08 20:42:39 +05:30
123d5c9f1d added two methods to get registered beneficiaries for a customer 2025-08-08 20:40:10 +05:30
7ba9f878f7 Merge branch 'fetch-from-cbs' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/yume_js into admin_api 2025-08-08 13:15:04 +05:30
cd1193c746 feat : admin feature 2025-08-08 13:06:08 +05:30
e75ff4d658 added authentication for all beneficiary routes
added npci routes for receiving responses from NPCI for beneficiary validation requests
2025-08-07 02:02:25 +05:30
ecb9b14629 implemented a controller for processing all the responses we will get from NPCI for beneficiary validation 2025-08-07 02:01:03 +05:30
35bd668116 implemented validator to validate beneficiary details 2025-08-07 01:59:27 +05:30
ae14968739 added service for sending beneficiary details to NPCI interface 2025-08-07 01:58:37 +05:30
6d675ad81c added controllers for beneficiary addition, checking and fetching ifsc details 2025-08-07 01:57:50 +05:30
df68fc4a29 added routes for beneficiary addition, checking and fetching ifsc details 2025-08-07 01:57:02 +05:30
e9a001ecf6 added redis configuration 2025-08-07 01:55:21 +05:30
9093da6bc9 changed port number for development 2025-08-04 15:11:07 +05:30
b88e00f758 added beneficiary routes, controllers and services 2025-07-31 12:28:26 +05:30
42 changed files with 1445 additions and 60 deletions

3
.env
View File

@@ -1,3 +0,0 @@
PORT=8080
DATABASE_URL=postgresql://kmobile_app_rw:kmobile@localhost:5431/kmobile_banking
JWT_SECRET=supersecret

3
.gitignore vendored
View File

@@ -1 +1,4 @@
node_modules/
.vscode/
.env
logs/requests.log

View File

@@ -1,5 +1,6 @@
{
"cSpell.words": [
"otpgenerator",
"tpassword",
"tpin"
]

101
package-lock.json generated
View File

@@ -12,12 +12,15 @@
"axios": "^1.9.0",
"bcrypt": "^6.0.0",
"cors": "^2.8.5",
"dayjs": "^1.11.18",
"dotenv": "^16.5.0",
"express": "^5.1.0",
"jsonwebtoken": "^9.0.2",
"pg": "^8.16.0",
"pino": "^9.7.0",
"pino-http": "^10.4.0"
"pino-http": "^10.4.0",
"redis": "^5.7.0",
"uuid": "^11.1.0"
},
"devDependencies": {
"@eslint/js": "^9.28.0",
@@ -265,6 +268,61 @@
"url": "https://opencollective.com/pkgr"
}
},
"node_modules/@redis/bloom": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-5.7.0.tgz",
"integrity": "sha512-KtBHDH2Aw1BxYDQd87PJsdEmZcpMbD4oPzdBwB4IvSRmMovukO2NNGi5vpCHhCoicS83zu7cjX1fw79uFBZFJA==",
"engines": {
"node": ">= 18"
},
"peerDependencies": {
"@redis/client": "^5.7.0"
}
},
"node_modules/@redis/client": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/@redis/client/-/client-5.7.0.tgz",
"integrity": "sha512-YV3Knspdj9k6H6s4v8QRcj1WBxHt40vtPmszLKGwRUOUpUOLWSlI9oCUjprMDcQNzgSCXGXYdL/Aj6nT2+Ub0w==",
"dependencies": {
"cluster-key-slot": "1.1.2"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/@redis/json": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/@redis/json/-/json-5.7.0.tgz",
"integrity": "sha512-VP3wtse1PSB/UjZAV1lWyDrWrrZcwi/cjb3L0lIarcIJ+EbHliB2QPml0Bvjz8F8F0eDJRtChJVXFc+jhGxCtA==",
"engines": {
"node": ">= 18"
},
"peerDependencies": {
"@redis/client": "^5.7.0"
}
},
"node_modules/@redis/search": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/@redis/search/-/search-5.7.0.tgz",
"integrity": "sha512-dDZIq8pZJnT+kZ9xRlLLi2Rvkd792z9eh31QRIwPr5wXjAXeaQ+Nf65em6dLpsxZ60MmhwDwLrBPJpYVjKPBPQ==",
"engines": {
"node": ">= 18"
},
"peerDependencies": {
"@redis/client": "^5.7.0"
}
},
"node_modules/@redis/time-series": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-5.7.0.tgz",
"integrity": "sha512-AJTF9sz3y1MJAukgQW4Jw8zt8qGOE3+1d87pufOP35zsFBlHipGscpctoXiNMebfy0114y/FjSprr65LjbJQSQ==",
"engines": {
"node": ">= 18"
},
"peerDependencies": {
"@redis/client": "^5.7.0"
}
},
"node_modules/@types/estree": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz",
@@ -644,6 +702,14 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/cluster-key-slot": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz",
"integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -777,6 +843,12 @@
"node": "*"
}
},
"node_modules/dayjs": {
"version": "1.11.18",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.18.tgz",
"integrity": "sha512-zFBQ7WFRvVRhKcWoUh+ZA1g2HVgUbsZm9sbddh8EC5iv93sui8DVVz1Npvz+r6meo9VKfa8NyLWBsQK1VvIKPA==",
"license": "MIT"
},
"node_modules/debug": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
@@ -2894,6 +2966,21 @@
"node": ">= 12.13.0"
}
},
"node_modules/redis": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/redis/-/redis-5.7.0.tgz",
"integrity": "sha512-ZRbiWYBUYdDTopodRjCVwwCLThrkciPW3bOrkdMCW3nYEelBwUGN6SovmACDsiLUB7mnU3mXnaI5f0W7bDcwng==",
"dependencies": {
"@redis/bloom": "5.7.0",
"@redis/client": "5.7.0",
"@redis/json": "5.7.0",
"@redis/search": "5.7.0",
"@redis/time-series": "5.7.0"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/resolve-from": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
@@ -3399,6 +3486,18 @@
"punycode": "^2.1.0"
}
},
"node_modules/uuid": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",
"integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"bin": {
"uuid": "dist/esm/bin/uuid"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",

View File

@@ -16,12 +16,15 @@
"axios": "^1.9.0",
"bcrypt": "^6.0.0",
"cors": "^2.8.5",
"dayjs": "^1.11.18",
"dotenv": "^16.5.0",
"express": "^5.1.0",
"jsonwebtoken": "^9.0.2",
"pg": "^8.16.0",
"pino": "^9.7.0",
"pino-http": "^10.4.0"
"pino-http": "^10.4.0",
"redis": "^5.7.0",
"uuid": "^11.1.0"
},
"devDependencies": {
"@eslint/js": "^9.28.0",

View File

@@ -1,6 +1,6 @@
const express = require('express');
const cors = require('cors');
const { logger } = require('./util/logger');
const { logger, requestLogger } = require('./util/logger');
const routes = require('./routes');
const app = express();
@@ -9,6 +9,26 @@ app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
requestLogger.info(
{
ip: req.ip || req.connection.remoteAddress,
method: req.method,
url: req.originalUrl,
headers: req.headers,
body: req.body,
status: res.statusCode,
responseTime: `${Date.now() - start}ms`,
},
'Incoming request'
);
});
next();
});
app.use('/api', routes);
app.get('/health', (_, res) => res.send('server is healthy'));
app.use((err, _req, res, _next) => {
@@ -17,3 +37,4 @@ app.use((err, _req, res, _next) => {
});
module.exports = app;

58
src/config/redis.js Normal file
View File

@@ -0,0 +1,58 @@
const { createClient } = require('redis');
const { redisUrl } = require('./config');
const { logger } = require('../util/logger');
const client = createClient({
url: redisUrl,
socket: {
reconnectStrategy: (retries) => {
const delay = Math.min(retries * 100, 5000);
logger.info(`Redis reconnecting attempt ${retries}, delay ${delay}ms`);
return delay;
},
},
});
client.on('connect', () => logger.info('Connected to redis'));
client.on('error', (err) => logger.error(err, 'Redis error'));
client.on('ready', () => logger.info('Redis client ready'));
client.on('end', () => logger.info('Redis connection closed'));
client
.connect()
.catch((err) => logger.error(err, 'Failed to connect to Redis'));
// Helper functions
async function setJson(key, value, ttl = null) {
try {
const jsonValue = JSON.stringify(value);
if (ttl) {
return await client.set(key, jsonValue, { EX: ttl });
}
return await client.set(key, jsonValue);
} catch (err) {
logger.error(err, 'Redis setJson error');
throw err;
}
}
async function getJson(key) {
try {
const value = await client.get(key);
return value ? JSON.parse(value) : null;
} catch (err) {
logger.error(err, 'Redis getJson error');
throw err;
}
}
process.on('SIGTERM', async () => {
logger.info('SIGTERM received - closing Redis connection');
await client.quit();
});
module.exports = {
client,
getJson,
setJson,
};

View File

@@ -0,0 +1,123 @@
const adminAuthService = require('../services/admin.auth.service');
const authService = require('../services/auth.service');
const { generateToken } = require('../util/jwt');
const { logger } = require('../util/logger');
const { hashPassword } = require('../util/hash');
const db = require('../config/db');
const { generateOTP } = require('../otpgenerator');
async function login(req, res) {
const { userName, password } = req.body;
if (!userName || !password) {
return res
.status(400)
.json({ error: 'UserName and Password are required' });
}
const currentTime = new Date().toISOString();
try {
const admin = await adminAuthService.validateAdmin(userName, password);
if (!admin) return res.status(401).json({ error: 'invalid credentials' });
const token = generateToken(admin.username, 'admin', '1d');
await db.query('UPDATE admin SET last_login = $1 WHERE username = $2', [
currentTime,
userName,
]);
res.json({ token });
} catch (err) {
logger.error(err, 'login failed');
res.status(500).json({ error: 'something went wrong' });
}
}
async function fetchAdminDetails(req, res) {
const customerNo = req.admin;
try {
const admin = await adminAuthService.findAdminByUserName(customerNo);
if (!admin) return res.status(404).json({ message: 'ADMIN_USER_NOT_FOUND' });
return res.json(admin);
} catch (err) {
logger.error(err, 'error occurred while fetching admin details');
res.status(500).json({ error: 'something went wrong' });
}
}
async function getUserDetails(req, res) {
const { CIF } = req.query;
if (!CIF) {
res.status(400).json({
error: 'CIF number is required',
});
}
try {
const userDetails = await adminAuthService.getCustomerDetails(CIF);
if (!userDetails)
return res.status(401).json({ error: 'invalid CIF number' });
return res.json(userDetails);
} catch (error) {
logger.error('while fetching customer details', error);
res.status(500).json({ error: 'invalid CIF number' });
}
}
async function getUserRights(req, res) {
// const { CIF } = req.query;
// if (!CIF) {
// res.status(400).json({
// error: 'CIF number is required',
// });
// }
// try {
// const userDetails = await adminAuthService.getCustomerDetails(CIF);
// if (!userDetails)
// return res.status(401).json({ error: 'invalid CIF number' });
// return res.json(userDetails);
// } catch (error) {
// logger.error('while fetching customer details', error);
// res.status(500).json({ error: 'invalid CIF number'});
// }
}
async function UserRights(req, res) {
const { CIF, ib_access_level, mb_access_level } = req.body;
const first_time_pass = generateOTP(6);
if (!CIF) {
res.status(400).json({
error: 'CIF number is required',
});
}
const currentTime = new Date().toISOString();
const user = await authService.findUserByCustomerNo(CIF);
const password = await hashPassword(first_time_pass);
if (user) {
try {
await db.query('UPDATE users SET customer_no = $1,password_hash=$2,updated_at=$5,ib_access_level=$3,mb_access_level=$4 WHERE customer_no = $1', [
CIF,
password,
ib_access_level,
mb_access_level,
currentTime,
]);
res.json({otp:`${first_time_pass}`});
} catch (err) {
console.log(err);
logger.error(err, 'Right Update failed');
res.status(500).json({ error: 'something went wrong' });
}
}
if (!user) {
try {
await db.query('INSERT INTO users (customer_no, password_hash,ib_access_level,mb_access_level) VALUES ($1, $2, $3, $4)',
[CIF, password, ib_access_level, mb_access_level]
);
res.json({otp:`${first_time_pass}`});
} catch (err) {
console.log(err);
logger.error(err, 'Right Update failed');
res.status(500).json({ error: 'something went wrong' });
}
}
}
module.exports = { login, fetchAdminDetails, getUserDetails,UserRights};

View File

@@ -2,6 +2,8 @@ const authService = require('../services/auth.service');
const { generateToken } = require('../util/jwt');
const { logger } = require('../util/logger');
const db = require('../config/db');
const dayjs = require("dayjs");
const { comparePassword } = require('../util/hash');
async function login(req, res) {
const { customerNo, password } = req.body;
@@ -14,14 +16,24 @@ async function login(req, res) {
const currentTime = new Date().toISOString();
try {
const user = await authService.validateUser(customerNo, password);
if (!user) return res.status(401).json({ error: 'invalid credentials' });
const token = generateToken(user.customer_no, '1d');
if (!user || !password)
return res.status(401).json({ error: 'invalid credentials' });
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' });
const token = generateToken(user.customer_no, '1d');
const loginPswExpiry = user.password_hash_expiry;
const rights = {
ibAccess: user.ib_access_level,
mbAccess: user.mb_access_level,
};
await db.query('UPDATE users SET last_login = $1 WHERE customer_no = $2', [
currentTime,
customerNo,
]);
res.json({ token, FirstTimeLogin });
res.json({ token, FirstTimeLogin, loginPswExpiry, rights });
} catch (err) {
logger.error(err, 'login failed');
res.status(500).json({ error: 'something went wrong' });
@@ -34,7 +46,6 @@ async function fetchUserDetails(req, res) {
const user = await authService.findUserByCustomerNo(customerNo);
if (!user) return res.status(404).json({ message: 'USER_NOT_FOUND' });
return res.json(user);
} catch (err) {
logger.error(err, 'error occured while fetching user details');
res.status(500).json({ error: 'something went wrong' });
@@ -88,6 +99,7 @@ async function setLoginPassword(req, res) {
return res.status(500).json({ error: 'SOMETHING_WENT_WRONG' });
}
}
async function setTransactionPassword(req, res) {
const customerNo = req.user;
try {
@@ -102,4 +114,57 @@ async function setTransactionPassword(req, res) {
}
}
module.exports = { login, tpin, setTpin, setLoginPassword, setTransactionPassword,fetchUserDetails };
async function changeLoginPassword(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 { OldLPsw, newLPsw, confirmLPsw } = req.body;
const isMatch = await comparePassword(OldLPsw, user.password_hash);
if (!isMatch)
return res.status(500).json({ error: 'Please Enter Correct Old Login Password' });
if (newLPsw !== confirmLPsw)
return res.status(500).json({ error: 'New Password and Confirm Password not Match' })
const isMatchWithOldPassword = await comparePassword(newLPsw, user.password_hash);
if (isMatchWithOldPassword)
return res.status(500).json({ error: 'New Password will be different from Previous Password' })
authService.changeLoginPassword(customerNo, newLPsw);
return res.json({ message: 'New Login Password changed successfully' });
} catch (error) {
logger.error(error);
return res.status(500).json({ error: 'SOMETHING_WENT_WRONG' });
}
}
async function changeTransPassword(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 { OldTPsw, newTPsw, confirmTPsw } = req.body;
const isMatch = await comparePassword(OldTPsw, user.transaction_password);
if (!isMatch)
return res.status(500).json({ error: 'Please Enter Correct Old Transaction Password' });
if (newTPsw !== confirmTPsw)
return res.status(500).json({ error: 'New Transaction Password and Confirm Transaction Password not Match' })
const isMatchWithOldPassword = await comparePassword(newTPsw, user.transaction_password);
if (isMatchWithOldPassword)
return res.status(500).json({ error: 'New Transaction Password will be different from Previous Transaction Password' })
authService.changeTransPassword(customerNo, newTPsw);
return res.json({ message: 'New Transaction Password changed successfully' });
} catch (error) {
logger.error(error);
return res.status(500).json({ error: 'SOMETHING_WENT_WRONG' });
}
}
module.exports = {
login,
tpin,
setTpin,
setLoginPassword,
setTransactionPassword,
fetchUserDetails,
changeLoginPassword,
changeTransPassword,
};

View File

@@ -1,5 +1,7 @@
const { logger } = require('../util/logger');
const beneficiaryService = require('../services/beneficiary.service');
const db = require('../config/db');
const randomName = require('../util/name.generator');
async function validateWithinBank(req, res) {
const { accountNumber } = req.query;
@@ -22,4 +24,126 @@ async function validateWithinBank(req, res) {
}
}
module.exports = { validateWithinBank };
async function validateOutsideBank(req, res) {
const { accountNo, ifscCode, remitterName } = req.query;
if (!accountNo || !ifscCode || !remitterName) {
res.status(401).json({ error: 'BAD_REQUEST' });
return;
}
try {
const refNo = await beneficiaryService.validateOutsideBank(
accountNo,
ifscCode,
remitterName
);
if (!refNo)
return res.status(401).json({ error: 'invalid account number' });
//**IN PRODUCTION** poll the redis server continuously giving the refNo since the response from NPCI will be stored there
await delay(3000);
const name = randomName();
return res.json({ name });
} catch (err) {
logger.error(err, 'beneficiary validation within bank failed');
res.status(500).json({ error: 'invalid account number' });
}
}
async function addBeneficiary(req, res) {
try {
const { accountNo, ifscCode, accountType, name } = req.body;
const customerNo = req.user;
const query =
'INSERT INTO beneficiaries (customer_no, account_no, account_type, ifsc_code, name) VALUES ($1, $2, $3, $4, $5)';
await db.query(query, [customerNo, accountNo, accountType, ifscCode, name]);
res.json({ message: 'SUCCESS' });
} catch (error) {
logger.error(error, 'Error adding beneficiary');
if (
error.message ==
'duplicate key value violates unique constraint "beneficiaries_pkey"'
) {
res.status(409).json({ error: 'BENEFICIARY_ALREADY_EXITS' });
}
res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
async function getBeneficiary(req, res) {
const { accountNo } = req.query;
let beneficiaryDetails;
try {
if (accountNo) {
beneficiaryDetails = await beneficiaryService.getSingleBeneficiary(
req.user,
accountNo
);
} else {
beneficiaryDetails = await beneficiaryService.getAllBeneficiaries(
req.user
);
}
if (!beneficiaryDetails) {
res.status(404).json({ error: 'NO_BENEFICIARY_FOUND' });
return;
}
res.json(beneficiaryDetails);
} catch (error) {
logger.error(error, 'error fetching beneficiaries');
res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
async function deleteBeneficiary(req, res) {
const { beneficiaryAccountNo } = req.params;
try {
await beneficiaryService.deleteBeneficiary(req.user, beneficiaryAccountNo);
res.status(204).send();
} catch (error) {
if (error.message === 'ACCOUNT_NOT_FOUND') {
logger.warn(
`beneficiary ${beneficiaryAccountNo} does not exist for the customer ${req.user}`
);
return res.status(400).json({ error: 'INVALID_BENEFICIARY_ACCOUNT_NO' });
} else {
logger.error(error, 'error deleting beneficiary');
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
}
async function getIfscDetails(req, res) {
const { ifscCode } = req.query;
if (!ifscCode) {
res.status(403).json({ error: 'BAD_REQUEST' });
return;
}
console.log(ifscCode);
try {
const query = 'SELECT * FROM ifsc_details WHERE ifsc_code = $1';
const result = await db.query(query, [ifscCode]);
console.log(result.rows);
if (!result.rows) {
res.status(404).json({ error: 'NOT_FOUND' });
return;
}
res.json(result.rows[0]);
} catch (error) {
logger.error(error, 'error fetching ifsc code');
res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
module.exports = {
validateWithinBank,
validateOutsideBank,
addBeneficiary,
getIfscDetails,
getBeneficiary,
deleteBeneficiary,
};

View File

@@ -0,0 +1,43 @@
const axios = require('axios');
const { logger } = require('../util/logger');
async function send(
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
beneficiaryAcctType = 'SAVING',
remarks = ''
) {
try {
const reqData = {
stBenAccNo: toAccount,
stBeneName: beneficiaryName,
stBenAccType: beneficiaryAcctType,
stBenIFSC: ifscCode,
stFromAccDetails: fromAccount,
stTransferAmount: amount,
stRemarks: remarks,
};
logger.info(reqData, 'request data to be sent to IMPS server');
const response = await axios.post(
'http://localhost:6768/kccb/api/IMPS/Producer',
reqData,
{
headers: {
'Content-Type': 'application/json',
},
}
);
logger.info(response, 'response from IMPS');
return response.data;
} catch (error) {
logger.error(error, 'error from IMPS');
throw new Error(
'API call failed: ' + (error.response?.data?.message || error.message)
);
}
}
module.exports = { send };

View File

@@ -0,0 +1,37 @@
const axios = require('axios');
async function send(
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
remitterName
) {
try {
const response = await axios.post(
'http://localhost:8690/kccb/Neftfundtransfer',
{
stFromAcc: fromAccount,
stToAcc: toAccount,
stTranAmt: amount,
stCommission: 0,
stIfscCode: ifscCode,
stFullName: remitterName,
stBeneName: beneficiaryName,
stAddress1: '',
stAddress2: '',
stAddress3: '',
}
);
return response.data;
} catch (error) {
throw new Error(
'API call failed: ' + (error.response?.data?.message || error.message)
);
}
}
module.exports = { send };

View File

@@ -0,0 +1,28 @@
const db = require('../config/db');
const { getJson, setJson } = require('../config/redis');
const { logger } = require('../util/logger');
async function npciResponse(req, res) {
const { resp } = req.body;
if (resp.status === 'Success') {
await handleNPCISuccess(resp);
} else {
await handleNPCIFailure(resp);
}
res.send('ok');
}
async function handleNPCISuccess(response) {
const { txnid, benename } = response;
try {
await setJson(txnid, benename);
} catch (error) {
logger.error(error, 'error processing npci response');
}
}
async function handleNPCIFailure(response) {
console.log(response);
}
module.exports = { npciResponse };

View File

@@ -0,0 +1,102 @@
const { setJson, getJson } = require('../config/redis');
const { generateOTP } = require('../otpgenerator');
const { logger } = require('../util/logger');
const axios = require('axios');
const templates = require('../util/sms_template');
// Send OTP
async function SendOtp(req, res) {
const { mobileNumber, type, amount, beneficiary, ifsc, acctFrom, acctTo, ref, date,userOtp } = req.body;
if (!mobileNumber || !type) {
return res.status(400).json({ error: 'Mobile number and type are required' });
}
try {
// const otp = generateOTP(6);
const otp = type === 'REGISTRATION' && userOtp ? userOtp : generateOTP(6);
let message;
// Pick template based on type
switch (type) {
case 'IMPS':
message = templates.IMPS(otp);
break;
case 'NEFT':
message = templates.NEFT(otp, amount, beneficiary);
break;
case 'RTGS':
message = templates.RTGS(otp, amount, beneficiary);
break;
case 'BENEFICIARY_ADD':
message = templates.BENEFICIARY_ADD(otp, beneficiary, ifsc);
break;
case 'BENEFICIARY_SUCCESS':
message = templates.BENEFICIARY_SUCCESS(beneficiary);
break;
case 'NOTIFICATION':
message = templates.NOTIFICATION(acctFrom, acctTo, amount, ref, date);
break;
case 'FORGOT_PASSWORD':
message = templates.FORGOT_PASSWORD(otp);
break;
case 'REGISTRATION':
message = templates.REGISTRATION(otp);
break;
default:
return res.status(400).json({ error: 'Invalid OTP type' });
}
// Call SMS API
const response = await axios.post('http://localhost:9999/api/SendtoMessage', {
mobileNumber,
stMessage: message,
});
if (response.data) {
// Save OTP only if it's OTP based (skip notifications without OTP)
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');
return res.status(500).json({ error: 'Internal server error' });
}
}
// Verify OTP
async function VerifyOtp(req, res) {
const { mobileNumber } = req.query;
const { otp } = req.body
if (!mobileNumber || !otp) {
return res.status(400).json({ error: 'Phone number and OTP are required' });
}
try {
const storedOtp = await getJson(`otp:${mobileNumber}`);
if (!storedOtp) {
return res.status(400).json({ error: 'OTP expired or not found' });
}
if (parseInt(otp, 10) !== parseInt(storedOtp, 10)) {
return res.status(400).json({ error: 'Invalid OTP' });
}
return res.status(200).json({ message: 'OTP verified successfully' });
} catch (err) {
logger.error(err, 'Error verifying OTP');
return res.status(500).json({ error: 'Internal server error' });
}
}
module.exports = { SendOtp, VerifyOtp };

View File

@@ -0,0 +1,36 @@
const axios = require('axios');
async function send(
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
remitterName
) {
try {
const response = await axios.post(
'http://localhost:8690/kccb/Rtgsfundtransfer',
{
stFromAcc: fromAccount,
stToAcc: toAccount,
stTranAmt: amount,
stCommission: 0,
stIfscCode: ifscCode,
stFullName: remitterName,
stBeneName: beneficiaryName,
stAddress1: '',
stAddress2: '',
stAddress3: '',
}
);
return response.data;
} catch (error) {
throw new Error(
'API call to CBS failed' +
(error.response?.data?.message || error.message)
);
}
}
module.exports = { send };

View File

@@ -21,5 +21,27 @@ async function getLastTen(accountNumber) {
);
}
}
module.exports = { getLastTen };
async function getFiltered(accountNumber, fromDate, toDate) {
try {
const response = await axios.get(
`http://localhost:8688/kccb/cbs/montlyacctstmt/details`,
{
params: { stacctno: accountNumber, fromdate: fromDate, todate: toDate },
}
);
const transactions = response.data;
const processedTransactions = transactions.map((tx) => ({
id: tx.stTransactionNumber,
name: tx.stTransactionDesc,
date: tx.stTransactionDate,
amount: tx.stTransactionAmount.slice(0, -3),
type: tx.stTransactionAmount.slice(-2),
}));
return processedTransactions;
} catch (error) {
throw new Error(
'API call failde: ' + (error.response?.data?.message || error.message)
);
}
}
module.exports = { getLastTen, getFiltered };

View File

@@ -0,0 +1,28 @@
const { verifyToken } = require('../util/jwt');
const { logger } = require('../util/logger');
function checkAdmin (req,res,next){
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res
.status(401)
.json({ error: 'missing or malformed authorization header' });
}
const token = authHeader.split(' ')[1];
try {
const payload = verifyToken(token);
// console.log("hi",payload);
if(payload.customerNo && payload.role === 'admin'){
req.admin = payload.customerNo;
next();
}
else
return res.status(403).json({error :'Only admin can access'})
} catch (err) {
logger.error(err, 'error verifying token');
return res.status(401).json({ error: 'invalid or expired token' });
}
}
module.exports = checkAdmin;

View File

@@ -21,5 +21,4 @@ function auth(req, res, next) {
return res.status(401).json({ error: 'invalid or expired token' });
}
}
module.exports = auth;

12
src/otpgenerator.js Normal file
View File

@@ -0,0 +1,12 @@
function generateOTP(length) {
const digits = '0123456789';
let otp = '';
otp += digits[Math.floor(Math.random() * 9) + 1]; // first digit cannot be zero
for (let i = 1; i < length; i++) {
otp += digits[Math.floor(Math.random() * digits.length)];
}
return otp;
}
module.exports = { generateOTP };

View File

@@ -0,0 +1,11 @@
const adminAuthController = require('../controllers/admin_auth.controller');
const adminAuthenticate = require('../middlewares/admin.middleware');
const express = require('express');
const router = express.Router();
router.post('/login', adminAuthController.login);
router.get('/admin_details', adminAuthenticate, adminAuthController.fetchAdminDetails);
router.get('/fetch/customer_details',adminAuthenticate,adminAuthController.getUserDetails);
router.post('/user/rights',adminAuthenticate,adminAuthController.UserRights);
module.exports = router;

View File

@@ -9,6 +9,9 @@ router.get('/user_details', authenticate, authController.fetchUserDetails);
router.get('/tpin', authenticate, authController.tpin);
router.post('/tpin', authenticate, authController.setTpin);
router.post('/login_password', authenticate, authController.setLoginPassword);
router.post('/transaction_password', authenticate, authController.setTransactionPassword);
router.post('/transaction_password',authenticate,authController.setTransactionPassword);
router.post('/change/login_password',authenticate,authController.changeLoginPassword);
router.post('/change/transaction_password',authenticate,authController.changeTransPassword);
module.exports = router;

View File

@@ -1,8 +1,17 @@
const express = require('express');
const beneficiaryController = require('../controllers/beneficiary.controller');
const newBeneficiaryValidator = require('../validators/beneficiary.validator');
const router = express.Router();
router.get('/validate/within-bank', beneficiaryController.validateWithinBank);
router.get('/validate/outside-bank', beneficiaryController.validateOutsideBank);
router.get('/ifsc-details', beneficiaryController.getIfscDetails);
router.get('/', beneficiaryController.getBeneficiary);
router.post('/', newBeneficiaryValidator, beneficiaryController.addBeneficiary);
router.delete(
'/:beneficiaryAccountNo',
beneficiaryController.deleteBeneficiary
);
module.exports = router;

37
src/routes/imps.route.js Normal file
View File

@@ -0,0 +1,37 @@
const express = require('express');
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 router = express.Router();
router.use(impsValidator, paymentSecretValidator);
const impsRoute = async (req, res) => {
const { fromAccount, toAccount, ifscCode, amount, beneficiaryName } =
req.body;
try {
const result = await impsController.send(
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
'SAVING',
'check'
);
if (result.startsWith('Message produced successfully')) {
return res.json({ message: 'SUCCESS' });
} else {
return res.json({ error: 'INVALID_REQUEST' });
}
} catch (error) {
logger.error(error, 'error occured while doing IMPS');
return res.json({ error: 'INTERVAL_SERVER_ERROR' });
}
};
router.post('/', impsRoute);
module.exports = router;

View File

@@ -1,17 +1,30 @@
const express = require('express');
const authRoute = require('./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');
const transferRoute = require('./transfer.route');
const beneficiaryRoute = require('./beneficiary.route');
const neftRoute = require('./neft.route');
const rtgsRoute = require('./rtgs.route');
const impsRoute = require('./imps.route');
const { npciResponse } = require('../controllers/npci.controller');
const otp = require('./otp.route');
const router = express.Router();
router.use('/auth', authRoute);
router.use('/auth/admin',adminAuthRoute);
router.use('/customer', authenticate, detailsRoute);
router.use('/transactions/account/:accountNo', authenticate, transactionRoute);
router.use('/payment/transfer', authenticate, transferRoute);
router.use('/beneficiary', beneficiaryRoute);
router.use('/payment/neft', authenticate, neftRoute);
router.use('/payment/rtgs', authenticate, rtgsRoute);
router.use('/payment/imps', authenticate, impsRoute);
router.use('/beneficiary', authenticate, beneficiaryRoute);
router.use('/npci/beneficiary-response', npciResponse);
router.use('/otp', otp);
module.exports = router;

49
src/routes/neft.route.js Normal file
View File

@@ -0,0 +1,49 @@
const express = require('express');
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 router = express.Router();
router.use(neftValidator, paymentSecretValidator);
const neftRoute = async (req, res) => {
const {
fromAccount,
toAccount,
ifscCode,
amount,
beneficiaryName,
remitterName,
} = req.body;
try {
const result = await neftController.send(
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
remitterName
);
logger.info(result);
if (result.status.startsWith('O.K.')) {
const utr = result.status.slice(9, 25);
return res.json({ message: 'SUCCESS', utr });
} else if (result.status.includes('INSUFFICIENT FUNDS')) {
return res.status(422).json({ error: 'INSUFFICIENT_FUNDS' });
} else if (result.status.includes('INVALID CHECK DIGIT')) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER' });
} else {
return res.status(400).json({ error: 'PROBLEM_TRANSFERRING_FUNDS' });
}
} catch (error) {
logger.error(error, 'error occured while doing NEFT transaction');
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
};
router.post('/', neftRoute);
module.exports = router;

13
src/routes/otp.route.js Normal file
View File

@@ -0,0 +1,13 @@
const express = require('express');
const otpController = require('../controllers/otp.controller');
const router = express.Router();
// Send OTP (POST request with body)
router.post('/send', otpController.SendOtp);
// Verify OTP (GET request with query params ?mobileNumber=xxx&otp=123456)
router.post('/verify', otpController.VerifyOtp);
module.exports = router;

48
src/routes/rtgs.route.js Normal file
View File

@@ -0,0 +1,48 @@
const express = require('express');
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 router = express.Router();
router.use(rtgsValidator, paymentSecretValidator);
const rtgsRoute = async (req, res) => {
const {
fromAccount,
toAccount,
ifscCode,
amount,
beneficiaryName,
remitterName,
} = req.body;
try {
const result = await rtgsController.send(
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
remitterName
);
if (result.status.startsWith('O.K.')) {
const utr = result.status.slice(9, 25);
return res.json({ message: 'SUCCESS', utr });
} else if (result.status.includes('INSUFFICIENT FUNDS')) {
return res.status(422).json({ error: 'INSUFFICIENT_FUNDS' });
} else if (result.status.includes('INVALID CHECK DIGIT')) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER' });
} else {
return res.status(400).json({ error: 'PROBLEM_TRANSFERRING_FUNDS' });
}
} catch (error) {
logger.error(error, 'error occured while doing NEFT transaction');
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
};
router.post('/', rtgsRoute);
module.exports = router;

View File

@@ -3,15 +3,44 @@ const { logger } = require('../util/logger');
const transactionsRoute = async (req, res) => {
const accountNo = req.params.accountNo;
const { fromDate, toDate } = req.query;
let data;
try {
const data = await transactionsController.getLastTen(accountNo);
if (fromDate && toDate) {
if (!isValidDDMMYYYY(fromDate) || !isValidDDMMYYYY(toDate)) {
return res.status(400).json({ error: 'INVALID_DATE_FORMAT' });
}
data = await transactionsController.getFiltered(
accountNo,
fromDate,
toDate
);
} else {
data = await transactionsController.getLastTen(accountNo);
}
return res.json(data);
} catch (error) {
logger.error('error retriving last 10 txns', error);
logger.error('error retriving transaction history', error);
return res
.status(500)
.json({ message: 'error occured while fetching transactions' });
}
};
function isValidDDMMYYYY(dateStr) {
if (!/^\d{8}$/.test(dateStr)) return false;
const day = parseInt(dateStr.slice(0, 2), 10);
const month = parseInt(dateStr.slice(2, 4), 10);
const year = parseInt(dateStr.slice(4), 10);
const date = new Date(year, month - 1, day);
return (
date.getFullYear() === year &&
date.getMonth() === month - 1 &&
date.getDate() === day
);
}
module.exports = transactionsRoute;

View File

@@ -1,24 +1,10 @@
const transferController = require('../controllers/transfer.controller');
const { logger } = require('../util/logger');
const express = require('express');
const tpinValidator = require('../validators/tpin.validator');
const tpasswordValidator = require('../validators/tpassword.validator');
const transferValidator = require('../validators/transfer.validator');
const passwordValidator = require('../validators/payment.secret.validator.js');
const router = express.Router();
// Added for tpassword
const passwordValidator=async(req,res,next)=>{
const{tpin,tpassword} =req.body;
if(tpin){
return tpinValidator(req,res,next);
}
else if(tpassword){
return tpasswordValidator(req,res,next);
}
else{
return res.status(400).json({error:"tpin or tpassword is required"})
}
}
router.use(passwordValidator, transferValidator);
const transferRoute = async (req, res) => {

View File

@@ -0,0 +1,40 @@
const db = require('../config/db');
const { comparePassword, hashPassword } = require('../util/hash');
const axios = require('axios');
async function findAdminByUserName(customerNo) {
const result = await db.query('SELECT * FROM admin WHERE username = $1', [
customerNo,
]);
return result.rows[0];
}
async function validateAdmin(customerNo, password) {
const user = await findAdminByUserName(customerNo);
if (!user) return null;
const isMatch = await comparePassword(password, user.password);
return isMatch ? user : null;
}
async function getCustomerDetails(customerNo) {
try {
const response = await axios.get(
'http://localhost:8686/kccb/cbs/custInfo/details',
{ params: { stcustno: customerNo } }
);
const details = response.data;
const processedDetails = details.map((acc) => ({
...acc,
activeAccounts: details.length,
cifNumber: customerNo,
}));
return processedDetails;
} catch (error) {
logger.error('while fetching customer details', error);
throw new Error(
'API call failed: ' + (error.response?.data?.message || error.message)
);
}
}
module.exports = { validateAdmin, findAdminByUserName,getCustomerDetails };

View File

@@ -1,5 +1,6 @@
const db = require('../config/db');
const { comparePassword, hashPassword } = require('../util/hash');
const dayjs =require("dayjs");
async function findUserByCustomerNo(customerNo) {
const result = await db.query('SELECT * FROM users WHERE customer_no = $1', [
@@ -47,14 +48,16 @@ async function setTpin(customerNo, tpin) {
// Set login password
async function setLoginPassword(customerNo, login_psw) {
const hashedLoginPassword = await hashPassword(login_psw);
const currentTime = dayjs().toISOString();
const password_expiry = dayjs().add(90,"day").toISOString();
try {
await db.query('UPDATE users SET password_hash = $1 ,is_first_login = false WHERE customer_no = $2', [
hashedLoginPassword,
customerNo,
]);
await db.query(
'UPDATE users SET password_hash = $1 ,is_first_login = false,updated_at = $3,password_hash_expiry =$4 WHERE customer_no = $2',
[hashedLoginPassword, customerNo ,currentTime ,password_expiry]
);
} catch (error) {
throw new Error(
`error occured while while setting new Login Password ${error.message}`
`error occurred while while setting new Login Password ${error.message}`
);
}
}
@@ -62,24 +65,68 @@ async function setLoginPassword(customerNo, login_psw) {
async function validateTransactionPassword(customerNo, tpassword) {
const user = await findUserByCustomerNo(customerNo);
if (!user?.transaction_password) return null;
const isMatch = await comparePassword(tpassword, user.transaction_password );
const isMatch = await comparePassword(tpassword, user.transaction_password);
return isMatch;
}
// Set transaction password
async function setTransactionPassword(customerNo, trans_psw) {
const hashedTransPassword = await hashPassword(trans_psw);
const currentTime = dayjs().toISOString();
const password_expiry = dayjs().add(90,"day").toISOString();
try {
await db.query('UPDATE users SET transaction_password = $1 WHERE customer_no = $2', [
hashedTransPassword,
customerNo,
]);
await db.query(
'UPDATE users SET transaction_password = $1 ,updated_at = $3,transaction_password_expiry =$4 WHERE customer_no = $2',
[hashedTransPassword, customerNo , currentTime ,password_expiry]
);
} catch (error) {
throw new Error(
`error occured while while setting new Transaction Password ${error.message}`
`error occurred while while setting new Transaction Password ${error.message}`
);
}
}
module.exports = { validateUser, findUserByCustomerNo, setTpin, validateTpin,
CheckFirstTimeLogin, setLoginPassword, validateTransactionPassword,setTransactionPassword };
async function changeLoginPassword(customerNo, login_psw) {
const hashedLoginPassword = await hashPassword(login_psw);
const currentTime = dayjs().toISOString();
const password_expiry = dayjs().add(90,"day").toISOString();
try {
await db.query(
'UPDATE users SET password_hash = $1 ,updated_at = $3,password_hash_expiry =$4 WHERE customer_no = $2',
[hashedLoginPassword, customerNo , currentTime ,password_expiry]
);
} catch (error) {
throw new Error(
`error occured while while setting new Login Password ${error.message}`
);
}
}
async function changeTransPassword(customerNo, trans_psw) {
const hashedTransPassword = await hashPassword(trans_psw);
const currentTime = dayjs().toISOString();
const password_expiry = dayjs().add(90,"day").toISOString();
try {
await db.query(
'UPDATE users SET transaction_password = $1 ,updated_at = $3,transaction_password_expiry =$4 WHERE customer_no = $2',
[hashedTransPassword, customerNo , currentTime ,password_expiry]
);
} catch (error) {
throw new Error(
`error occurred while while setting new Login Password ${error.message}`
);
}
}
module.exports = {
validateUser,
findUserByCustomerNo,
setTpin,
validateTpin,
CheckFirstTimeLogin,
setLoginPassword,
validateTransactionPassword,
setTransactionPassword,
changeLoginPassword,
changeTransPassword,
};

View File

@@ -1,10 +1,15 @@
const axios = require('axios');
const { logger } = require('../util/logger');
const { v4: uuidv4 } = require('uuid');
const db = require('../config/db');
async function validateWithinBank(accountNo) {
const url = `http://localhost:8687/kccb/cbs/acctInfo/details?stacctno=${accountNo}`;
const url = 'http://localhost:8687/kccb/cbs/acctInfo/details';
try {
const response = await fetch(url);
const data = await response.json();
const response = await axios.get(url, {
params: { stacctno: accountNo },
});
const data = response.data;
const customerName = data.customername;
return customerName;
} catch (error) {
@@ -13,4 +18,63 @@ async function validateWithinBank(accountNo) {
}
}
module.exports = { validateWithinBank };
async function validateOutsideBank(accountNo, ifscCode, name) {
const uuid = `KCC${uuidv4().replace(/-/g, '')}`;
const url = `http://localhost:9091/kccb/benenamelookup/ReqBeneDetails/${uuid}`;
try {
const response = await axios.post(url, {
acctNo: accountNo,
ifsccode: ifscCode,
remittername: name,
});
if (response.data) {
console.log(response.data);
return uuid;
}
} catch (error) {
logger.error(error, 'error while validating customer from NPCI');
throw new Error('error in beneficiary validation');
}
}
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';
const result = await db.query(queryStr, [customerNo, accountNo]);
return result.rows[0];
}
async function deleteBeneficiary(customerNo, beneficiaryAccountNo) {
const queryStr =
'DELETE FROM beneficiaries WHERE customer_no = $1 AND account_no = $2';
const result = await db.query(queryStr, [customerNo, beneficiaryAccountNo]);
if (result.rowCount == 0) {
throw new Error('ACCOUNT_NOT_FOUND');
}
return;
}
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 ifsc_details i ON b.ifsc_code = i.ifsc_code WHERE customer_no = $1';
const result = await db.query(queryStr, [customerNo]);
const list = result.rows.map((row) => {
return {
accountNo: row['account_no'],
name: row['name'],
accountType: row['account_type'],
ifscCode: row['ifsc_code'],
bankName: row['bank_name'],
branchName: row['branch_name'],
};
});
return list;
}
module.exports = {
validateWithinBank,
validateOutsideBank,
getAllBeneficiaries,
getSingleBeneficiary,
deleteBeneficiary,
};

View File

@@ -2,9 +2,9 @@ const jwt = require('jsonwebtoken');
const { jwtSecret } = require('../config/config');
const { logger } = require('./logger');
function generateToken(customerNo, expiresIn = '10d') {
logger.info({ customerNo }, 'payload to encode');
return jwt.sign({ customerNo }, jwtSecret, { expiresIn });
function generateToken(customerNo, role = 'user', expiresIn = '10d') {
logger.info({ customerNo, role }, 'payload to encode');
return jwt.sign({ customerNo, role }, jwtSecret, { expiresIn });
}
function verifyToken(token) {

View File

@@ -1,6 +1,19 @@
const pino = require('pino');
const fs = require('fs');
const path = require('path');
const isDev = process.env.NODE_ENV !== 'production';
const logDir = path.join(__dirname, '../..', 'logs');
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const requestLoggerStream = pino.destination({
dest: path.join(logDir, 'requests.log'),
sync: false,
});
const logger = pino({
transport: isDev
? {
@@ -15,8 +28,12 @@ const logger = pino({
level: isDev ? 'debug' : 'info',
});
const requestLogger = (req, _res, next) => {
logger.info(`${req.method} ${req.url}`);
next();
};
const requestLogger = pino(
{
level: 'info',
base: null,
},
requestLoggerStream
);
module.exports = { logger, requestLogger };

View File

@@ -0,0 +1,36 @@
const indianFirstNames = [
'Aarav',
'Vivaan',
'Aditya',
'Vihaan',
'Krishna',
'Ishaan',
'Rohan',
'Ananya',
'Diya',
'Aisha',
'Priya',
'Sneha',
];
const indianLastNames = [
'Sharma',
'Verma',
'Iyer',
'Reddy',
'Patel',
'Mehta',
'Choudhary',
'Kumar',
'Das',
'Rao',
];
function getRandomIndianName() {
const firstName =
indianFirstNames[Math.floor(Math.random() * indianFirstNames.length)];
const lastName =
indianLastNames[Math.floor(Math.random() * indianLastNames.length)];
return `${firstName} ${lastName}`;
}
module.exports = getRandomIndianName;

26
src/util/sms_template.js Normal file
View File

@@ -0,0 +1,26 @@
const templates = {
IMPS: (otp) => `Dear Customer, Please complete the fund transfer with OTP ${otp} -KCCB`,
NEFT: (otp, amount, beneficiary) =>
`Dear Customer, Please complete the NEFT of Rs.${amount} to ${beneficiary} with OTP:${otp} -KCCB`,
RTGS: (otp, amount, beneficiary) =>
`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`,
BENEFICIARY_SUCCESS: (beneficiary) =>
`Dear Customer, Your Beneficiary: ${beneficiary} for Net Banking is added successfully -KCCB`,
NOTIFICATION: (acctFrom, acctTo, amount, ref, date) =>
`Your A/c ${acctFrom} is debited for Rs. ${amount} to the credit of A/c ${acctTo} thru Net Banking - ref: ${ref} - ${date} - Kangra Central Co-Operative Bank -KCCB`,
FORGOT_PASSWORD: (otp) =>
`Dear Customer, Forgot Password OTP is ${otp} -KCCB`,
REGISTRATION: (otp) =>
`Dear Customer, Your CIF is enable.First time login password: ${otp} (valid for 7 days).Please login and change your password -KCCB`,
};
module.exports = templates;

View File

@@ -0,0 +1,33 @@
const db = require('../config/db');
const newBeneficiaryValidator = async (req, res, next) => {
const { accountNo, name, ifscCode, accountType } = req.body;
if (!accountNo || !/^[0-9]{7,20}$/.test(accountNo)) {
res.status(400).json({ error: 'INVALID_ACCOUNT_NO' });
return;
}
if (!name || !accountType) {
res.status(400).json({ error: 'BAD_REQUEST' });
return;
}
if (!ifscCode || !/^[A-Z]{4}0[0-9]{6}$/.test(ifscCode)) {
res.status(400).json({ error: 'INVALID_IFSC' });
return;
}
const query_str =
'SELECT EXISTS(SELECT 1 FROM ifsc_details WHERE ifsc_code = $1)';
const result = await db.query(query_str, [ifscCode]);
const exists = result.rows[0].exists;
if (!exists) {
res.status(400).json({ error: 'INVALID_IFSC_CODE' });
return;
}
// if everthing is ok then move forward
next();
};
module.exports = newBeneficiaryValidator;

View File

@@ -0,0 +1,36 @@
const impsValidator = (req, res, next) => {
const {
fromAccount,
toAccount,
amount,
remitterName,
beneficiaryName,
ifscCode,
} = req.body;
if (!isAccountNumbersValid(fromAccount, toAccount)) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER_FORMAT' });
}
if (amount < 1) {
return res.status(400).json({ error: 'INVALID_AMOUNT' });
}
if (!remitterName || !beneficiaryName) {
return res
.status(400)
.json({ error: 'REMITTER_NAME AND BENEFICIARY_NAME REQUIRED' });
}
if (!ifscCode || !/^[A-Z]{4}0[0-9]{6}$/.test(ifscCode)) {
return res.status(400).json({ error: 'INVALID_IFSC_CODE' });
}
next();
};
const isAccountNumbersValid = (fromAcct, toAcct) => {
return !(!fromAcct || !toAcct || fromAcct.length != 11 || toAcct.length < 7);
};
module.exports = impsValidator;

View File

@@ -0,0 +1,36 @@
const neftValidator = (req, res, next) => {
const {
fromAccount,
toAccount,
amount,
remitterName,
beneficiaryName,
ifscCode,
} = req.body;
if (!isAccountNumbersValid(fromAccount, toAccount)) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER_FORMAT' });
}
if (amount < 1) {
return res.status(400).json({ error: 'INVALID_AMOUNT' });
}
if (!remitterName || !beneficiaryName) {
return res
.status(400)
.json({ error: 'REMITTER_NAME AND BENEFICIARY_NAME REQUIRED' });
}
if (!ifscCode || !/^[A-Z]{4}0[0-9]{6}$/.test(ifscCode)) {
return res.status(400).json({ error: 'INVALID_IFSC_CODE' });
}
next();
};
const isAccountNumbersValid = (fromAcct, toAcct) => {
return !(!fromAcct || !toAcct || fromAcct.length != 11 || toAcct.length < 7);
};
module.exports = neftValidator;

View File

@@ -0,0 +1,15 @@
const tpasswordValidator = require('./tpassword.validator.js');
const tpinValidator = require('./tpin.validator.js');
const paymentSecretValidator = async (req, res, next) => {
const { tpin, tpassword } = req.body;
if (tpin) {
return tpinValidator(req, res, next);
} else if (tpassword) {
return tpasswordValidator(req, res, next);
} else {
return res.status(400).json({ error: 'tpin or tpassword is required' });
}
};
module.exports = paymentSecretValidator;

View File

@@ -0,0 +1,36 @@
const rtgsValidator = (req, res, next) => {
const {
fromAccount,
toAccount,
amount,
remitterName,
beneficiaryName,
ifscCode,
} = req.body;
if (!isAccountNumbersValid(fromAccount, toAccount)) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER_FORMAT' });
}
if (amount < 200000) {
return res.status(400).json({ error: 'AMOUNT_SHOULD_BE_MORE_THAN_200000' });
}
if (!remitterName || !beneficiaryName) {
return res
.status(400)
.json({ error: 'REMITTER_NAME AND BENEFICIARY_NAME REQUIRED' });
}
if (!ifscCode || !/^[A-Z]{4}0[0-9]{6}$/.test(ifscCode)) {
return res.status(400).json({ error: 'INVALID_IFSC_CODE' });
}
next();
};
const isAccountNumbersValid = (fromAcct, toAcct) => {
return !(!fromAcct || !toAcct || fromAcct.length != 11 || toAcct.length < 7);
};
module.exports = rtgsValidator;

View File

@@ -1,7 +1,7 @@
const transferValidator = async (req, res, next) => {
const transferValidator = (req, res, next) => {
const { fromAccount, toAccount, toAccountType, amount } = req.body;
const accountTypes = ['SB', 'LN','Savings','Current'];
const accountTypes = ['SB', 'LN', 'Savings', 'Current'];
if (!fromAccount || fromAccount.length != 11) {
return res.status(400).json({ error: 'INVALID_ACCOUNT_NUMBER_FORMAT' });
}