20 Commits

Author SHA1 Message Date
aaa11287a1 feat : admin user rights updated.
feat : update for otp sent for registration.
feat: login Api updated passes "rights" in response
2025-09-05 13:54:25 +05:30
4857ef6cab feat: Change login Password 2025-09-02 16:05:11 +05:30
f60329672c feat : Change login password feature update 2025-09-02 12:52:13 +05:30
9f6c2f9cc1 feat: user can change login password
feat: user can change transaction password
wip : Admin feature rights -InProgress
2025-09-02 12:41:39 +05:30
cb22b926f8 Merge branch 'otp_binding' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/yume_js into admin_api 2025-09-01 13:45:39 +05:30
b213259c7c changed the directory of log directory 2025-09-01 13:38:28 +05:30
90f60f7324 added log files in .gitignore 2025-09-01 13:38:28 +05:30
6533c5081c added logger for logging all kinds of requests with headers, body, ip and other data 2025-09-01 13:38:28 +05:30
33aa50413c fix: check if password is not null on login req 2025-09-01 13:38:28 +05:30
65519e6403 added beneficiary deletion feature 2025-09-01 13:38:28 +05:30
b1f2277c92 fixed a bug where data and pin validations were not called 2025-09-01 13:38:28 +05:30
asif
bb446f41d8 formatted auth route 2025-09-01 13:38:28 +05:30
6e6690746a added imps transactions payment feature 2025-09-01 13:38:28 +05:30
470d8e15f6 fixed typo in rtgs.route.js 2025-09-01 13:38:28 +05:30
a02e58ebec Merge branch 'fetch-from-cbs' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/yume_js into admin_api 2025-08-27 11:55:24 +05:30
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
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
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
24 changed files with 572 additions and 25 deletions

2
.gitignore vendored
View File

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

View File

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

7
package-lock.json generated
View File

@@ -12,6 +12,7 @@
"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",
@@ -842,6 +843,12 @@
"node": "*"
}
},
"node_modules/dayjs": {
"version": "1.11.18",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.18.tgz",
"integrity": "sha512-zFBQ7WFRvVRhKcWoUh+ZA1g2HVgUbsZm9sbddh8EC5iv93sui8DVVz1Npvz+r6meo9VKfa8NyLWBsQK1VvIKPA==",
"license": "MIT"
},
"node_modules/debug": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",

View File

@@ -16,6 +16,7 @@
"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

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

View File

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

View File

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

View File

@@ -95,6 +95,24 @@ async function getBeneficiary(req, res) {
}
}
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) {
@@ -127,4 +145,5 @@ module.exports = {
addBeneficiary,
getIfscDetails,
getBeneficiary,
deleteBeneficiary,
};

View File

@@ -30,6 +30,8 @@ async function send(
'API call failed: ' + (error.response?.data?.message || error.message)
);
}
}
module.exports = { send };

View File

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

View File

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

View File

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

12
src/otpgenerator.js Normal file
View File

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

View File

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

View File

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

View File

@@ -9,5 +9,9 @@ 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

@@ -1,5 +1,6 @@
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');
@@ -9,10 +10,12 @@ 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);
@@ -21,5 +24,7 @@ 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;

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

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

View File

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

View File

@@ -1,5 +1,6 @@
const db = require('../config/db');
const { comparePassword, hashPassword } = require('../util/hash');
const dayjs =require("dayjs");
async function findUserByCustomerNo(customerNo) {
const result = await db.query('SELECT * FROM users WHERE customer_no = $1', [
@@ -47,14 +48,16 @@ async function setTpin(customerNo, tpin) {
// Set login password
async function setLoginPassword(customerNo, login_psw) {
const hashedLoginPassword = await hashPassword(login_psw);
const currentTime = dayjs().toISOString();
const password_expiry = dayjs().add(90,"day").toISOString();
try {
await db.query(
'UPDATE users SET password_hash = $1 ,is_first_login = false WHERE customer_no = $2',
[hashedLoginPassword, customerNo]
'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}`
);
}
}
@@ -69,14 +72,48 @@ 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 WHERE customer_no = $2',
[hashedTransPassword, customerNo]
'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}`
);
}
}
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}`
);
}
}
@@ -90,4 +127,6 @@ module.exports = {
setLoginPassword,
validateTransactionPassword,
setTransactionPassword,
changeLoginPassword,
changeTransPassword,
};

View File

@@ -44,6 +44,16 @@ async function getSingleBeneficiary(customerNo, accountNo) {
return result.rows[0];
}
async function deleteBeneficiary(customerNo, beneficiaryAccountNo) {
const queryStr =
'DELETE FROM beneficiaries WHERE customer_no = $1 AND account_no = $2';
const result = await db.query(queryStr, [customerNo, beneficiaryAccountNo]);
if (result.rowCount == 0) {
throw new Error('ACCOUNT_NOT_FOUND');
}
return;
}
async function getAllBeneficiaries(customerNo) {
const queryStr =
'SELECT b.account_no, b.name, b.account_type, b.ifsc_code, i.bank_name, i.branch_name FROM beneficiaries b JOIN ifsc_details i ON b.ifsc_code = i.ifsc_code WHERE customer_no = $1';
@@ -66,4 +76,5 @@ module.exports = {
validateOutsideBank,
getAllBeneficiaries,
getSingleBeneficiary,
deleteBeneficiary,
};

View File

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

View File

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

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

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