126 Commits

Author SHA1 Message Date
1e831acfe2 fix: E-mandate validation api 2025-12-04 15:09:05 +05:30
bf06706b29 Merge branch 'fetch-from-cbs' of https://git.7o9o.net/md.asif5/yume_js into fetch-from-cbs 2025-11-14 13:08:50 +05:30
7e162e741d fix: 404 error for atm branch 2025-11-14 13:08:25 +05:30
a04830cdb2 Merge branch 'fetch-from-cbs' of https://git.7o9o.net/md.asif5/yume_js into fetch-from-cbs 2025-11-14 13:04:01 +05:30
12f0881c9b feat: branch and atm api 2025-11-14 13:03:56 +05:30
b0c9cb8038 fix: 404 error in branch route 2025-11-14 13:02:58 +05:30
a8a576f5c1 feat: api for branch and atm 2025-11-14 11:42:09 +05:30
4c63ccf3ae Resolve merge conflicts from E_mandate 2025-11-12 13:09:38 +05:30
759869b0e3 feat : Add api for E-mandate Validation 2025-11-12 13:00:53 +05:30
60cb0076f1 Merge branch 'fetch-from-cbs' of https://git.7o9o.net/md.asif5/yume_js into fetch-from-cbs
merging changes from kangra visit
2025-11-11 01:52:38 +05:30
b68c8a08c2 added npci as client type header 2025-11-11 01:52:26 +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
edbeca3fd2 feat: add message template for e-mandate 2025-09-25 12:07:02 +05:30
ffbbea27d7 fix: ifsc details 404 on wrong IFSC 2025-09-22 15:04:04 +05:30
a706fd8c21 fix: removed unnecessary requestLogger import in app.js 2025-09-22 11:17:55 +05:30
184a760cd5 fix: changed url for NEFT on CBS end 2025-09-19 11:53:37 +05:30
a81e26fa9f remarks changed to narration 2025-09-18 16:44:45 +05:30
051e86b1ff added remarks in RTGS transactions 2025-09-18 13:13:07 +05:30
cf94a3b425 added remarks for IMPS transactions 2025-09-18 13:08:53 +05:30
d38681613b added remarks in NEFT transaction 2025-09-18 13:05:35 +05:30
3d3a8f629c added remarks in normal branch transfer 2025-09-18 11:03:19 +05:30
b285c94aa2 removed the request logging from app.js 2025-09-16 12:46:25 +05:30
752b725fa6 changed SAVING to SAVINGS as transaction type for IMPS 2025-09-16 12:26:41 +05:30
00a839a6d8 wip: Change in otp controller for send correct message template 2025-09-15 16:04:45 +05:30
2c6b56e47d added a logger in npci response file 2025-09-11 22:52:50 +05:30
2a0ef55725 fix: added production url for initiating IMPS 2025-09-11 22:52:09 +05:30
f1a1ffa817 fix: removed the temp phone number that was added for testing 2025-09-11 22:51:31 +05:30
64e3cf3182 fix: added feature to validate beneficiaries from NPCI for real 2025-09-11 22:50:36 +05:30
a122882764 added setting password feature fo migrated users 2025-09-11 12:07:44 +05:30
asif
cb3b34899b increaed token period to 9 days 2025-09-10 20:15:21 +05:30
asif
d492c43427 added migrated user message in auth controller 2025-09-10 20:14:32 +05:30
3f90a793fe added helmet 2025-09-10 20:03:13 +05:30
3cbb1e9c39 Merge branch 'otp_binding' into fetch-from-cbs 2025-09-10 16:13:33 +05:30
0d8371e3df added ifsc code validation for internal transfers 2025-09-10 16:13:03 +05:30
50c375f0ba feat : onboarding new CIF by giving rights through admin portal.
feat : View the user rights and update in admin portal.
chore : Add some template message for OTP
2025-09-09 11:15:28 +05:30
445a0f434d Merge branch 'fetch-from-cbs' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/yume_js into admin_api 2025-09-09 11:10:46 +05:30
asif
2516ff5f4c added helmet for security 2025-09-09 02:11:43 +05:30
3da77cf97a feat: added account balance in statement 2025-09-08 20:32:19 +05:30
f675f1561a feat: added transactions record keeping feature 2025-09-08 20:04:55 +05:30
05068634fe added empty string as default narration value in transfer 2025-09-08 16:33:03 +05:30
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
50753295b4 changed the directory of log directory 2025-08-29 15:49:35 +05:30
454553adbb added log files in .gitignore 2025-08-29 15:40:36 +05:30
077d48c7f0 added logger for logging all kinds of requests with headers, body, ip and other data 2025-08-29 15:40:11 +05:30
c8efe8d75a fix: check if password is not null on login req 2025-08-29 13:40:57 +05:30
484a0dd51a added beneficiary deletion feature 2025-08-27 12:32:25 +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
53 changed files with 2423 additions and 73 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,6 +1,12 @@
{
"cSpell.words": [
"emandate",
"MPIN",
"occured",
"otpgenerator",
"TLIMIT",
"tpassword",
"tpin"
"tpin",
"TPWORD"
]
}

110
package-lock.json generated
View File

@@ -12,12 +12,16 @@
"axios": "^1.9.0",
"bcrypt": "^6.0.0",
"cors": "^2.8.5",
"dayjs": "^1.11.18",
"dotenv": "^16.5.0",
"express": "^5.1.0",
"helmet": "^8.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 +269,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 +703,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 +844,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",
@@ -1599,6 +1672,14 @@
"node": ">= 0.4"
}
},
"node_modules/helmet": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/helmet/-/helmet-8.1.0.tgz",
"integrity": "sha512-jOiHyAZsmnr8LqoPGmCjYAaiuWwjAPLgY8ZX2XrmHawt99/u1y6RgrZMTeoPfpUbV96HOalYgz1qzkRbw54Pmg==",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/help-me": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz",
@@ -2894,6 +2975,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 +3495,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,16 @@
"axios": "^1.9.0",
"bcrypt": "^6.0.0",
"cors": "^2.8.5",
"dayjs": "^1.11.18",
"dotenv": "^16.5.0",
"express": "^5.1.0",
"helmet": "^8.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

@@ -2,14 +2,17 @@ const express = require('express');
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();
app.use(cors());
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,
};

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,122 @@
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');
const dayjs = require("dayjs");
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',
});
}
const userDetails = await adminAuthService.getCustomerDetailsFromDB(CIF);
if (!userDetails)
return res.status(401).json({ error: 'invalid CIF number or No rights is present for the user.' });
return res.json(userDetails);
}
async function UserRights(req, res) {
try {
const { CIF, ib_access_level, mb_access_level } = req.body;
if (!CIF) {
return res.status(400).json({ error: 'CIF number is required' });
}
const currentTime = new Date().toISOString();
const user = await authService.findUserByCustomerNo(CIF);
const first_time_pass = generateOTP(6);
const password = await hashPassword(first_time_pass);
if (user) {
const FirstTimeLogin = await authService.CheckFirstTimeLogin(CIF);
// if user did not login within 7 days
if (FirstTimeLogin && dayjs(currentTime).diff(dayjs(user.created_at), 'day') > 8) {
// Password expired, resend
await db.query(
'UPDATE users SET 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]
);
return res.json({ otp: first_time_pass });
}
// Just update access levels and timestamp
await db.query(
'UPDATE users SET updated_at=$4, ib_access_level=$2, mb_access_level=$3 WHERE customer_no=$1',
[CIF, ib_access_level, mb_access_level, currentTime]
);
return res.json({ message: "User updated successfully." });
} else {
// User does not exist, insert
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]
);
return res.json({ otp: first_time_pass });
}
} catch (err) {
console.error(err);
logger.error(err, 'UserRights failed');
return res.status(500).json({ error: 'Something went wrong' });
}
}
module.exports = { login, fetchAdminDetails, getUserDetails, UserRights, getUserRights };

View File

@@ -2,29 +2,141 @@ 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');
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 {
// --- 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) return res.status(401).json({ error: 'invalid credentials' });
const token = generateToken(user.customer_no, '1d');
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);
if (FirstTimeLogin && dayjs(user.created_at).diff(currentTime, 'day') > 8)
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,
};
await db.query('UPDATE users SET last_login = $1 WHERE customer_no = $2', [
currentTime,
customerNo,
]);
res.json({ token, FirstTimeLogin });
logger.info(`Login successful | Type: ${loginType}`);
return res.json({ token, FirstTimeLogin, loginPswExpiry, rights, tnc });
} catch (err) {
logger.error(err, 'login failed');
res.status(500).json({ error: 'something went wrong' });
logger.error(err, `login failed | Type: ${loginType}`);
return res.status(500).json({ error: 'something went wrong' });
}
}
@@ -34,7 +146,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' });
@@ -67,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);
@@ -88,6 +220,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 +235,172 @@ 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' });
}
}
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

@@ -1,5 +1,8 @@
const { logger } = require('../util/logger');
const beneficiaryService = require('../services/beneficiary.service');
const { getJson, setJson } = require('../config/redis');
const db = require('../config/db');
const randomName = require('../util/name.generator');
async function validateWithinBank(req, res) {
const { accountNumber } = req.query;
@@ -22,4 +25,150 @@ 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' });
const name = await pollRedisKey(refNo);
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;
}
try {
const query = 'SELECT * FROM ifsc_details WHERE ifsc_code = $1';
const result = await db.query(query, [ifscCode]);
if (result.rows?.length === 0) {
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));
}
async function pollRedisKey(key) {
const timeout = 2 * 60 * 1000;
const interval = 2000;
const startTime = Date.now();
return new Promise((resolve, reject) => {
const poll = async () => {
try {
const beneficiaryName = await getJson(key);
if (beneficiaryName !== null) {
logger.info(beneficiaryName, 'payload from redis');
return resolve(beneficiaryName);
}
if (Date.now() - startTime >= timeout) {
return resolve(null);
}
setTimeout(poll, interval);
} catch (error) {
reject(error);
}
};
poll();
});
}
module.exports = {
validateWithinBank,
validateOutsideBank,
addBeneficiary,
getIfscDetails,
getBeneficiary,
deleteBeneficiary,
};

View File

@@ -0,0 +1,58 @@
const axios = require('axios');
const { logger } = require('../util/logger');
const {
recordInterBankTransaction,
} = require('../services/recordkeeping.service');
async function send(
customerNo,
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
beneficiaryAcctType = 'SAVINGS',
remarks = '',
client
) {
try {
const reqData = {
stBenAccNo: toAccount,
stBeneName: beneficiaryName,
stBenAccType: beneficiaryAcctType,
stBenIFSC: ifscCode,
stFromAccDetails: fromAccount,
stTransferAmount: amount,
stRemarks: remarks,
};
const response = await axios.post(
'http://192.168.1.39:6768/kccb/api/IMPS/Producer',
reqData,
{
headers: {
'Content-Type': 'application/json',
},
}
);
await recordInterBankTransaction(
customerNo,
'imps',
fromAccount,
toAccount,
ifscCode,
amount,
'',
'',
response.data,
client
);
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,56 @@
const axios = require('axios');
const {
recordInterBankTransaction,
} = require('../services/recordkeeping.service');
async function send(
customerNo,
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
remitterName,
remarks,
client
) {
const commission = 0;
try {
const response = await axios.post(
'http://localhost:8690/kccb/api/Neftfundtransfer',
{
stFromAcc: fromAccount,
stToAcc: toAccount,
stTranAmt: amount,
stCommission: commission,
stIfscCode: ifscCode,
stFullName: remitterName,
stBeneName: beneficiaryName,
stAddress1: '',
stAddress2: '',
stAddress3: '',
narration: remarks,
}
);
await recordInterBankTransaction(
customerNo,
'neft',
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
response.data.status,
client
);
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,29 @@
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;
logger.info(req.body, 'received response from NPCI');
if (resp === 'SUCCESS') {
await handleNPCISuccess(req.body);
} else {
await handleNPCIFailure(req.body);
}
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,244 @@
const { setJson, getJson } = require('../config/redis');
const { generateOTP } = require('../otpgenerator');
const { generateToken } = require('../util/jwt');
const authService = require('../services/auth.service.js');
const customerController = require('../controllers/customer_details.controller.js');
const { logger } = require('../util/logger');
const axios = require('axios');
const templates = require('../util/sms_template');
// Send OTP
async function SendOtp(req, res) {
const {
username,
mobileNumber,
type,
amount,
beneficiary,
ifsc,
acctFrom,
acctTo,
ref,
date,
userOtp,
PreferName,
} = req.body;
if (!mobileNumber || !type) {
return res
.status(400)
.json({ error: 'Mobile number and type are required' });
}
try {
let message;
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);
break;
case 'NEFT':
otp = generateOTP(6);
message = templates.NEFT(otp, amount, beneficiary);
break;
case 'RTGS':
otp = generateOTP(6);
message = templates.RTGS(otp, amount, beneficiary);
break;
case 'BENEFICIARY_ADD':
otp = generateOTP(6);
message = templates.BENEFICIARY_ADD(otp, beneficiary, ifsc);
break;
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;
case 'FORGOT_PASSWORD':
otp = generateOTP(6);
message = templates.FORGOT_PASSWORD(otp);
break;
case 'CHANGE_LPWORD':
otp = generateOTP(6);
message = templates.CHANGE_LPWORD(otp);
break;
case 'CHANGE_TPIN':
otp = generateOTP(6);
message = templates.CHANGE_TPIN(otp);
break;
case 'CHANGE_TPWORD':
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);
break;
case 'REGISTRATION':
otp = userOtp ? userOtp : generateOTP(6);
message = templates.REGISTRATION(otp);
break;
case 'RIGHT_UPDATE':
message = templates.RIGHT_UPDATE;
break;
case 'EMandate':
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' });
}
// 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' });
}
}
async function sendForSetPassword(req, res) {
try {
const { customerNo } = req.query;
if (!customerNo)
return res.status(400).json({ error: 'CUSTOMER_NO_REQUIRED' });
// check if user is registered for in mobile banking data
const user = await authService.findUserByCustomerNo(customerNo);
if (!user) return res.status(404).json({ error: 'USER_NOT_FOUND' });
// if present then get his phone number from CBS
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;
const otp = generateOTP(6);
const message = templates.CHANGE_LPWORD(otp);
const response = await axios.post(
'http://localhost:9999/api/SendtoMessage',
{
mobileNumber,
stMessage: message,
}
);
await setJson(`otp:${mobileNumber}`, otp, 300);
return res.status(200).json({ message: 'OTP_SENT' });
} catch (err) {
logger.error(err, 'Error sending OTP');
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
async function verifyForSetPassword(req, res) {
try {
const { customerNo, otp } = req.query;
if (!customerNo || !otp)
return res.status(400).json({ error: 'CUSTOMER_NO_REQUIRED' });
// check if user is registered for mobile banking database
const user = await authService.findUserByCustomerNo(customerNo);
if (!user) return res.status(404).json({ error: 'USER_NOT_FOUND' });
// if present then get his phone number from CBS
const userDetails = await customerController.getDetails(customerNo);
// temp check
const singleUserDetail = userDetails[0];
if (!singleUserDetail?.mobileno)
return res.status(400).json({ error: 'USER_PHONE_NOT_FOUND' });
const mobileNumber = singleUserDetail.mobileno;
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' });
}
const token = generateToken(customerNo, 'user', '5m');
return res
.status(200)
.json({ message: 'OTP verified successfully', token: token });
} catch (err) {
logger.error(err, 'Error sending OTP');
return res.status(500).json({ error: 'INTERNAL_SERVER_ERROR' });
}
}
module.exports = {
SendOtp,
VerifyOtp,
sendForSetPassword,
verifyForSetPassword,
};

View File

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

View File

@@ -13,6 +13,8 @@ async function getLastTen(accountNumber) {
date: tx.stTransactionDate,
amount: tx.stTransactionAmount.slice(0, -3),
type: tx.stTransactionAmount.slice(-2),
balance: tx.stAccountBalance.slice(0, -3),
balanceType: tx.stAccountBalance.slice(-2),
}));
return processedTransactions;
} catch (error) {
@@ -21,5 +23,29 @@ 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),
balance: tx.stAccountBalance.slice(0, -3),
balanceType: tx.stAccountBalance.slice(-2),
}));
return processedTransactions;
} catch (error) {
throw new Error(
'API call failde: ' + (error.response?.data?.message || error.message)
);
}
}
module.exports = { getLastTen, getFiltered };

View File

@@ -1,12 +1,16 @@
const axios = require('axios');
const {
recordIntraBankTransaction,
} = require('../services/recordkeeping.service');
async function transfer(
fromAccountNo,
toAccountNo,
toAccountType,
amount,
// narration = 'transfer from mobile'
narration
customerNo,
narration = '',
client
) {
try {
const response = await axios.post(
@@ -19,6 +23,15 @@ async function transfer(
narration,
}
);
await recordIntraBankTransaction(
customerNo,
fromAccountNo,
toAccountNo,
toAccountType,
amount,
response.data.status,
client
);
return response.data;
} catch (error) {
throw new Error(

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;

View File

@@ -0,0 +1,22 @@
const { logger } = require('../util/logger');
function verifyClient(req, res, next) {
console.log('printing headers');
console.log(req.headers);
const clientHeader = req.headers['x-login-type'];
if (!clientHeader || (clientHeader !== 'MB' && clientHeader !== 'IB' && clientHeader !== 'NPCI' && 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 };

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,12 @@
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);
router.get('/user/rights',adminAuthenticate,adminAuthController.getUserRights);
module.exports = router;

19
src/routes/atm.route.js Normal file
View File

@@ -0,0 +1,19 @@
const express = require('express');
const { logger } = require('../util/logger');
const db = require('../config/db');
const router = express.Router();
const atmRoute = async (req, res) => {
try {
const query_str = 'SELECT * FROM atm_details';
const result = await db.query(query_str);
return res.json(result.rows);
} catch (error) {
logger.error(error);
res.status(500).json({ error: 'INTERNAL SERVER ERROR' });
}
};
router.get('/', atmRoute);
module.exports = router;

View File

@@ -8,7 +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(
'/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,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;

View File

@@ -0,0 +1,19 @@
const express = require('express');
const { logger } = require('../util/logger');
const db = require('../config/db');
const router = express.Router();
const branchRoute = async (req, res) => {
try {
const query_str = 'SELECT * FROM branches';
const result = await db.query(query_str);
return res.json(result.rows);
} catch (error) {
logger.error(error);
res.status(500).json({ error: 'INTERNAL SERVER ERROR' });
}
};
router.get('/', branchRoute);
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(response.data, "Data validate");
return res.json({data: 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;

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

@@ -0,0 +1,49 @@
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 { checkLimit } = require('../middlewares/limitCheck.middleware');
const {
checkBeneficiaryCooldown,
} = require('../middlewares/cooldown.middleware');
const router = express.Router();
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(
req.user,
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
'SAVINGS',
remarks,
client
);
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,34 @@
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 branchRoute = require('./branch.route');
const atmRoute = require('./atm.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('/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);
router.use('/e-mandate', authenticate, eMandate);
router.use('/branch', authenticate, branchRoute);
router.use('/atm', authenticate, atmRoute);
module.exports = router;

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

@@ -0,0 +1,63 @@
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 { checkLimit } = require('../middlewares/limitCheck.middleware');
const {
checkBeneficiaryCooldown,
} = require('../middlewares/cooldown.middleware');
const router = express.Router();
router.use(
neftValidator,
paymentSecretValidator,
checkLimit,
checkBeneficiaryCooldown
);
const neftRoute = async (req, res) => {
const {
fromAccount,
toAccount,
ifscCode,
amount,
beneficiaryName,
remitterName,
remarks,
} = req.body;
const client = req.client;
try {
const result = await neftController.send(
req.user,
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
remitterName,
remarks,
client
);
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;

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

@@ -0,0 +1,18 @@
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);
//send otp for setting password
router.get('/send/set-password', otpController.sendForSetPassword);
//verify otp for setting password
router.get('/verify/set-password', otpController.verifyForSetPassword);
module.exports = router;

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

@@ -0,0 +1,62 @@
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 { checkLimit } = require('../middlewares/limitCheck.middleware');
const {
checkBeneficiaryCooldown,
} = require('../middlewares/cooldown.middleware');
const router = express.Router();
router.use(
rtgsValidator,
paymentSecretValidator,
checkLimit,
checkBeneficiaryCooldown
);
const rtgsRoute = async (req, res) => {
const {
fromAccount,
toAccount,
ifscCode,
amount,
beneficiaryName,
remitterName,
remarks,
} = req.body;
const client = req.client;
try {
const result = await rtgsController.send(
req.user,
fromAccount,
toAccount,
amount,
ifscCode,
beneficiaryName,
remitterName,
remarks,
client
);
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,34 +1,33 @@
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 { checkLimit } = require('../middlewares/limitCheck.middleware');
const {
checkBeneficiaryCooldown,
} = require('../middlewares/cooldown.middleware');
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);
router.use(
passwordValidator,
transferValidator,
checkLimit,
checkBeneficiaryCooldown
);
const transferRoute = async (req, res) => {
const { fromAccount, toAccount, toAccountType, amount } = req.body;
const { fromAccount, toAccount, toAccountType, amount, remarks } = req.body;
const client = req.client;
try {
const result = await transferController.transfer(
fromAccount,
toAccount,
toAccountType,
amount
amount,
req.user,
remarks,
client
);
if (result.status === 'O.K.') {

View File

@@ -0,0 +1,47 @@
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)
);
}
}
async function getCustomerDetailsFromDB(customerNo) {
const result = await db.query('SELECT customer_no,created_at,last_login,is_first_login,ib_access_level,mb_access_level FROM users WHERE customer_no = $1', [
customerNo,
]);
return result.rows[0];
}
module.exports = { validateAdmin, findAdminByUserName, getCustomerDetails,getCustomerDetailsFromDB };

View File

@@ -1,5 +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', [
@@ -23,6 +25,12 @@ async function CheckFirstTimeLogin(customerNo) {
return is_first_time_login;
}
async function isMigratedUser(customerNo) {
const user = await findUserByCustomerNo(customerNo);
if (user?.password_hash === 'o') return true;
return false;
}
async function validateTpin(customerNo, tpin) {
const user = await findUserByCustomerNo(customerNo);
if (!user?.tpin) return null;
@@ -47,14 +55,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 +72,140 @@ 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}`
);
}
}
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,
setTpin,
validateTpin,
CheckFirstTimeLogin,
setLoginPassword,
validateTransactionPassword,
setTransactionPassword,
changeLoginPassword,
changeTransPassword,
isMigratedUser,
CheckUserName,
setUserName,
getTncFlag,
setTncFlag,
};

View File

@@ -1,10 +1,13 @@
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 +16,68 @@ async function validateWithinBank(accountNo) {
}
}
module.exports = { validateWithinBank };
async function validateOutsideBank(accountNo, ifscCode, name) {
const uuid = `KCC${uuidv4().replace(/-/g, '')}`;
const url = `http://192.168.1.39:9091/kccb/benenamelookup/ReqBeneDetails/${uuid}`;
try {
const response = await axios.post(url, {
acctNo: accountNo,
ifsccode: ifscCode,
remittername: name,
});
if (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, 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];
}
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, 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';
} else {
details['ifscCode'] = row['ifsc_code'];
details['bankName'] = row['bank_name'];
details['branchName'] = row['branch_name'];
}
return details;
});
return list;
}
module.exports = {
validateWithinBank,
validateOutsideBank,
getAllBeneficiaries,
getSingleBeneficiary,
deleteBeneficiary,
};

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

@@ -0,0 +1,56 @@
const db = require('../config/db');
const recordIntraBankTransaction = async (
customerNo,
fromAccount,
toAccount,
accountType,
amount,
status,
clientType
) => {
const trxType = 'TRF';
const query =
'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,
fromAccount,
toAccount,
accountType,
amount,
status,
clientType,
]);
};
const recordInterBankTransaction = async (
customerNo,
trxType,
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
status,
clientType
) => {
const query =
'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,
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
status,
clientType,
]);
};
module.exports = { recordIntraBankTransaction, recordInterBankTransaction };

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;

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

@@ -0,0 +1,64 @@
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) =>
`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 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`,
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`,
CHANGE_LPWORD: (otp) =>
`Dear Customer, Change Login Password OTP is ${otp} -KCCB`,
CHANGE_TPIN: (otp) =>
`Dear Customer, Change Transaction pin OTP is ${otp} -KCCB`,
CHANGE_TPWORD: (otp) =>
`Dear Customer, Change Transaction password OTP is ${otp} -KCCB`,
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) =>
`Dear Customer, Your CIF is enable.First time login password: ${otp} (valid for 7 days).Please login and change your password -KCCB`,
RIGHT_UPDATE:
`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`,
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;

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' });
}