9 Commits

29 changed files with 144 additions and 492 deletions

1
.gitignore vendored
View File

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

View File

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

7
package-lock.json generated
View File

@@ -12,7 +12,6 @@
"axios": "^1.9.0",
"bcrypt": "^6.0.0",
"cors": "^2.8.5",
"dayjs": "^1.11.18",
"dotenv": "^16.5.0",
"express": "^5.1.0",
"jsonwebtoken": "^9.0.2",
@@ -843,12 +842,6 @@
"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",

View File

@@ -16,7 +16,6 @@
"axios": "^1.9.0",
"bcrypt": "^6.0.0",
"cors": "^2.8.5",
"dayjs": "^1.11.18",
"dotenv": "^16.5.0",
"express": "^5.1.0",
"jsonwebtoken": "^9.0.2",

View File

@@ -2,10 +2,12 @@ const express = require('express');
const cors = require('cors');
const { logger, requestLogger } = require('./util/logger');
const routes = require('./routes');
const helmet = require('helmet');
const app = express();
app.use(cors());
app.use(helmet());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
@@ -37,4 +39,3 @@ app.use((err, _req, res, _next) => {
});
module.exports = app;

View File

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

View File

@@ -2,8 +2,6 @@ const authService = require('../services/auth.service');
const { generateToken } = require('../util/jwt');
const { logger } = require('../util/logger');
const db = require('../config/db');
const dayjs = require("dayjs");
const { comparePassword } = require('../util/hash');
async function login(req, res) {
const { customerNo, password } = req.body;
@@ -18,22 +16,13 @@ async function login(req, res) {
const user = await authService.validateUser(customerNo, password);
if (!user || !password)
return res.status(401).json({ error: 'invalid credentials' });
const FirstTimeLogin = await authService.CheckFirstTimeLogin(customerNo);
// For registration : if try to login first time after 7 days.
if (FirstTimeLogin && dayjs(user.created_at).diff(currentTime, "day") > 8)
return res.status(401).json({ error: 'Password Expired.Please Contact with Administrator' });
const token = generateToken(user.customer_no, '1d');
const loginPswExpiry = user.password_hash_expiry;
const rights = {
ibAccess: user.ib_access_level,
mbAccess: user.mb_access_level,
};
const FirstTimeLogin = await authService.CheckFirstTimeLogin(customerNo);
await db.query('UPDATE users SET last_login = $1 WHERE customer_no = $2', [
currentTime,
customerNo,
]);
res.json({ token, FirstTimeLogin, loginPswExpiry, rights });
res.json({ token, FirstTimeLogin });
} catch (err) {
logger.error(err, 'login failed');
res.status(500).json({ error: 'something went wrong' });
@@ -99,7 +88,6 @@ async function setLoginPassword(req, res) {
return res.status(500).json({ error: 'SOMETHING_WENT_WRONG' });
}
}
async function setTransactionPassword(req, res) {
const customerNo = req.user;
try {
@@ -114,50 +102,6 @@ async function setTransactionPassword(req, res) {
}
}
async function changeLoginPassword(req, res) {
const customerNo = req.user;
try {
const user = await authService.findUserByCustomerNo(customerNo);
if (!user) return res.status(404).json({ error: 'USER_NOT_FOUND' });
const { OldLPsw, newLPsw, confirmLPsw } = req.body;
const isMatch = await comparePassword(OldLPsw, user.password_hash);
if (!isMatch)
return res.status(500).json({ error: 'Please Enter Correct Old Login Password' });
if (newLPsw !== confirmLPsw)
return res.status(500).json({ error: 'New Password and Confirm Password not Match' })
const isMatchWithOldPassword = await comparePassword(newLPsw, user.password_hash);
if (isMatchWithOldPassword)
return res.status(500).json({ error: 'New Password will be different from Previous Password' })
authService.changeLoginPassword(customerNo, newLPsw);
return res.json({ message: 'New Login Password changed successfully' });
} catch (error) {
logger.error(error);
return res.status(500).json({ error: 'SOMETHING_WENT_WRONG' });
}
}
async function changeTransPassword(req, res) {
const customerNo = req.user;
try {
const user = await authService.findUserByCustomerNo(customerNo);
if (!user) return res.status(404).json({ error: 'USER_NOT_FOUND' });
const { OldTPsw, newTPsw, confirmTPsw } = req.body;
const isMatch = await comparePassword(OldTPsw, user.transaction_password);
if (!isMatch)
return res.status(500).json({ error: 'Please Enter Correct Old Transaction Password' });
if (newTPsw !== confirmTPsw)
return res.status(500).json({ error: 'New Transaction Password and Confirm Transaction Password not Match' })
const isMatchWithOldPassword = await comparePassword(newTPsw, user.transaction_password);
if (isMatchWithOldPassword)
return res.status(500).json({ error: 'New Transaction Password will be different from Previous Transaction Password' })
authService.changeTransPassword(customerNo, newTPsw);
return res.json({ message: 'New Transaction Password changed successfully' });
} catch (error) {
logger.error(error);
return res.status(500).json({ error: 'SOMETHING_WENT_WRONG' });
}
}
module.exports = {
login,
tpin,
@@ -165,6 +109,4 @@ module.exports = {
setLoginPassword,
setTransactionPassword,
fetchUserDetails,
changeLoginPassword,
changeTransPassword,
};

View File

@@ -1,7 +1,11 @@
const axios = require('axios');
const { logger } = require('../util/logger');
const {
recordInterBankTransaction,
} = require('../services/recordkeeping.service');
async function send(
customerNo,
fromAccount,
toAccount,
amount,
@@ -20,7 +24,6 @@ async function send(
stTransferAmount: amount,
stRemarks: remarks,
};
logger.info(reqData, 'request data to be sent to IMPS server');
const response = await axios.post(
'http://localhost:6768/kccb/api/IMPS/Producer',
reqData,
@@ -30,7 +33,17 @@ async function send(
},
}
);
logger.info(response, 'response from IMPS');
await recordInterBankTransaction(
customerNo,
'imps',
fromAccount,
toAccount,
ifscCode,
amount,
'',
'',
response.data
);
return response.data;
} catch (error) {
logger.error(error, 'error from IMPS');

View File

@@ -1,6 +1,10 @@
const axios = require('axios');
const {
recordInterBankTransaction,
} = require('../services/recordkeeping.service');
async function send(
customerNo,
fromAccount,
toAccount,
amount,
@@ -8,6 +12,7 @@ async function send(
beneficiaryName,
remitterName
) {
const commission = 0;
try {
const response = await axios.post(
'http://localhost:8690/kccb/Neftfundtransfer',
@@ -15,7 +20,7 @@ async function send(
stFromAcc: fromAccount,
stToAcc: toAccount,
stTranAmt: amount,
stCommission: 0,
stCommission: commission,
stIfscCode: ifscCode,
stFullName: remitterName,
stBeneName: beneficiaryName,
@@ -24,14 +29,24 @@ async function send(
stAddress3: '',
}
);
await recordInterBankTransaction(
customerNo,
'neft',
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
response.data.status
);
return response.data;
} catch (error) {
throw new Error(
'API call failed: ' + (error.response?.data?.message || error.message)
);
}
}
module.exports = { send };

View File

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

View File

@@ -1,6 +1,10 @@
const axios = require('axios');
const {
recordInterBankTransaction,
} = require('../services/recordkeeping.service');
async function send(
customerNo,
fromAccount,
toAccount,
amount,
@@ -8,6 +12,7 @@ async function send(
beneficiaryName,
remitterName
) {
const commission = 0;
try {
const response = await axios.post(
'http://localhost:8690/kccb/Rtgsfundtransfer',
@@ -15,7 +20,7 @@ async function send(
stFromAcc: fromAccount,
stToAcc: toAccount,
stTranAmt: amount,
stCommission: 0,
stCommission: commission,
stIfscCode: ifscCode,
stFullName: remitterName,
stBeneName: beneficiaryName,
@@ -24,6 +29,18 @@ async function send(
stAddress3: '',
}
);
await recordInterBankTransaction(
customerNo,
'rtgs',
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
response.data.status
);
return response.data;
} catch (error) {
throw new Error(

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) {
@@ -36,6 +38,8 @@ async function getFiltered(accountNumber, fromDate, toDate) {
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) {

View File

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

View File

@@ -1,28 +0,0 @@
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,4 +21,5 @@ function auth(req, res, next) {
return res.status(401).json({ error: 'invalid or expired token' });
}
}
module.exports = auth;

View File

@@ -1,12 +0,0 @@
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

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

View File

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

View File

@@ -13,6 +13,7 @@ const impsRoute = async (req, res) => {
try {
const result = await impsController.send(
req.user,
fromAccount,
toAccount,
amount,

View File

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

View File

@@ -19,6 +19,7 @@ const neftRoute = async (req, res) => {
try {
const result = await neftController.send(
req.user,
fromAccount,
toAccount,
amount,

View File

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

View File

@@ -19,6 +19,7 @@ const rtgsRoute = async (req, res) => {
try {
const result = await rtgsController.send(
req.user,
fromAccount,
toAccount,
amount,

View File

@@ -14,7 +14,8 @@ const transferRoute = async (req, res) => {
fromAccount,
toAccount,
toAccountType,
amount
amount,
req.user
);
if (result.status === 'O.K.') {

View File

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

View File

@@ -1,6 +1,5 @@
const db = require('../config/db');
const { comparePassword, hashPassword } = require('../util/hash');
const dayjs =require("dayjs");
async function findUserByCustomerNo(customerNo) {
const result = await db.query('SELECT * FROM users WHERE customer_no = $1', [
@@ -48,16 +47,14 @@ 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,updated_at = $3,password_hash_expiry =$4 WHERE customer_no = $2',
[hashedLoginPassword, customerNo ,currentTime ,password_expiry]
'UPDATE users SET password_hash = $1 ,is_first_login = false WHERE customer_no = $2',
[hashedLoginPassword, customerNo]
);
} catch (error) {
throw new Error(
`error occurred while while setting new Login Password ${error.message}`
`error occured while while setting new Login Password ${error.message}`
);
}
}
@@ -72,48 +69,14 @@ async function validateTransactionPassword(customerNo, tpassword) {
// 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 ,updated_at = $3,transaction_password_expiry =$4 WHERE customer_no = $2',
[hashedTransPassword, customerNo , currentTime ,password_expiry]
'UPDATE users SET transaction_password = $1 WHERE customer_no = $2',
[hashedTransPassword, customerNo]
);
} catch (error) {
throw new Error(
`error occurred while while setting new Transaction Password ${error.message}`
);
}
}
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}`
`error occured while while setting new Transaction Password ${error.message}`
);
}
}
@@ -127,6 +90,4 @@ module.exports = {
setLoginPassword,
validateTransactionPassword,
setTransactionPassword,
changeLoginPassword,
changeTransPassword,
};

View File

@@ -0,0 +1,52 @@
const db = require('../config/db');
const recordIntraBankTransaction = async (
customerNo,
fromAccount,
toAccount,
accountType,
amount,
status
) => {
const trxType = 'TRF';
const query =
'INSERT INTO transactions (customer_no, trx_type, from_account, to_account, to_account_type, amount, status) VALUES ($1, $2, $3, $4, $5, $6, $7)';
await db.query(query, [
customerNo,
trxType,
fromAccount,
toAccount,
accountType,
amount,
status,
]);
};
const recordInterBankTransaction = async (
customerNo,
trxType,
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
status
) => {
const query =
'INSERT INTO transactions (customer_no, trx_type, from_account, to_account, ifsc_code, amount, commission, beneficiary_name, remitter_name, status) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)';
await db.query(query, [
customerNo,
trxType,
fromAccount,
toAccount,
ifscCode,
amount,
commission,
beneficiaryName,
remitterName,
status,
]);
};
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, role = 'user', expiresIn = '10d') {
logger.info({ customerNo, role }, 'payload to encode');
return jwt.sign({ customerNo, role }, jwtSecret, { expiresIn });
function generateToken(customerNo, expiresIn = '10d') {
logger.info({ customerNo }, 'payload to encode');
return jwt.sign({ customerNo }, jwtSecret, { expiresIn });
}
function verifyToken(token) {

View File

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