Compare commits
20 Commits
fetch-from
...
otp_bindin
Author | SHA1 | Date | |
---|---|---|---|
aaa11287a1 | |||
4857ef6cab | |||
f60329672c | |||
9f6c2f9cc1 | |||
cb22b926f8 | |||
b213259c7c | |||
90f60f7324 | |||
6533c5081c | |||
33aa50413c | |||
65519e6403 | |||
b1f2277c92 | |||
|
bb446f41d8 | ||
6e6690746a | |||
470d8e15f6 | |||
a02e58ebec | |||
e179d1b339 | |||
52225828d0 | |||
75a0e6e084 | |||
7ba9f878f7 | |||
cd1193c746 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,2 +1,4 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
|
.vscode/
|
||||||
.env
|
.env
|
||||||
|
logs/requests.log
|
||||||
|
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
@@ -1,5 +1,6 @@
|
|||||||
{
|
{
|
||||||
"cSpell.words": [
|
"cSpell.words": [
|
||||||
|
"otpgenerator",
|
||||||
"tpassword",
|
"tpassword",
|
||||||
"tpin"
|
"tpin"
|
||||||
]
|
]
|
||||||
|
7
package-lock.json
generated
7
package-lock.json
generated
@@ -12,6 +12,7 @@
|
|||||||
"axios": "^1.9.0",
|
"axios": "^1.9.0",
|
||||||
"bcrypt": "^6.0.0",
|
"bcrypt": "^6.0.0",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
|
"dayjs": "^1.11.18",
|
||||||
"dotenv": "^16.5.0",
|
"dotenv": "^16.5.0",
|
||||||
"express": "^5.1.0",
|
"express": "^5.1.0",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
@@ -842,6 +843,12 @@
|
|||||||
"node": "*"
|
"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": {
|
"node_modules/debug": {
|
||||||
"version": "4.4.1",
|
"version": "4.4.1",
|
||||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
|
||||||
|
@@ -16,6 +16,7 @@
|
|||||||
"axios": "^1.9.0",
|
"axios": "^1.9.0",
|
||||||
"bcrypt": "^6.0.0",
|
"bcrypt": "^6.0.0",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
|
"dayjs": "^1.11.18",
|
||||||
"dotenv": "^16.5.0",
|
"dotenv": "^16.5.0",
|
||||||
"express": "^5.1.0",
|
"express": "^5.1.0",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
|
23
src/app.js
23
src/app.js
@@ -1,6 +1,6 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const cors = require('cors');
|
const cors = require('cors');
|
||||||
const { logger } = require('./util/logger');
|
const { logger, requestLogger } = require('./util/logger');
|
||||||
const routes = require('./routes');
|
const routes = require('./routes');
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
@@ -9,6 +9,26 @@ app.use(cors());
|
|||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
app.use(express.urlencoded({ extended: true }));
|
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.use('/api', routes);
|
||||||
app.get('/health', (_, res) => res.send('server is healthy'));
|
app.get('/health', (_, res) => res.send('server is healthy'));
|
||||||
app.use((err, _req, res, _next) => {
|
app.use((err, _req, res, _next) => {
|
||||||
@@ -17,3 +37,4 @@ app.use((err, _req, res, _next) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
module.exports = app;
|
module.exports = app;
|
||||||
|
|
||||||
|
123
src/controllers/admin_auth.controller.js
Normal file
123
src/controllers/admin_auth.controller.js
Normal 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};
|
@@ -2,6 +2,8 @@ const authService = require('../services/auth.service');
|
|||||||
const { generateToken } = require('../util/jwt');
|
const { generateToken } = require('../util/jwt');
|
||||||
const { logger } = require('../util/logger');
|
const { logger } = require('../util/logger');
|
||||||
const db = require('../config/db');
|
const db = require('../config/db');
|
||||||
|
const dayjs = require("dayjs");
|
||||||
|
const { comparePassword } = require('../util/hash');
|
||||||
|
|
||||||
async function login(req, res) {
|
async function login(req, res) {
|
||||||
const { customerNo, password } = req.body;
|
const { customerNo, password } = req.body;
|
||||||
@@ -14,14 +16,24 @@ async function login(req, res) {
|
|||||||
const currentTime = new Date().toISOString();
|
const currentTime = new Date().toISOString();
|
||||||
try {
|
try {
|
||||||
const user = await authService.validateUser(customerNo, password);
|
const user = await authService.validateUser(customerNo, password);
|
||||||
if (!user) return res.status(401).json({ error: 'invalid credentials' });
|
if (!user || !password)
|
||||||
const token = generateToken(user.customer_no, '1d');
|
return res.status(401).json({ error: 'invalid credentials' });
|
||||||
const FirstTimeLogin = await authService.CheckFirstTimeLogin(customerNo);
|
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', [
|
await db.query('UPDATE users SET last_login = $1 WHERE customer_no = $2', [
|
||||||
currentTime,
|
currentTime,
|
||||||
customerNo,
|
customerNo,
|
||||||
]);
|
]);
|
||||||
res.json({ token, FirstTimeLogin });
|
res.json({ token, FirstTimeLogin, loginPswExpiry, rights });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error(err, 'login failed');
|
logger.error(err, 'login failed');
|
||||||
res.status(500).json({ error: 'something went wrong' });
|
res.status(500).json({ error: 'something went wrong' });
|
||||||
@@ -34,7 +46,6 @@ async function fetchUserDetails(req, res) {
|
|||||||
const user = await authService.findUserByCustomerNo(customerNo);
|
const user = await authService.findUserByCustomerNo(customerNo);
|
||||||
if (!user) return res.status(404).json({ message: 'USER_NOT_FOUND' });
|
if (!user) return res.status(404).json({ message: 'USER_NOT_FOUND' });
|
||||||
return res.json(user);
|
return res.json(user);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error(err, 'error occured while fetching user details');
|
logger.error(err, 'error occured while fetching user details');
|
||||||
res.status(500).json({ error: 'something went wrong' });
|
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' });
|
return res.status(500).json({ error: 'SOMETHING_WENT_WRONG' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function setTransactionPassword(req, res) {
|
async function setTransactionPassword(req, res) {
|
||||||
const customerNo = req.user;
|
const customerNo = req.user;
|
||||||
try {
|
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,
|
||||||
|
};
|
||||||
|
@@ -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) {
|
async function getIfscDetails(req, res) {
|
||||||
const { ifscCode } = req.query;
|
const { ifscCode } = req.query;
|
||||||
if (!ifscCode) {
|
if (!ifscCode) {
|
||||||
@@ -127,4 +145,5 @@ module.exports = {
|
|||||||
addBeneficiary,
|
addBeneficiary,
|
||||||
getIfscDetails,
|
getIfscDetails,
|
||||||
getBeneficiary,
|
getBeneficiary,
|
||||||
|
deleteBeneficiary,
|
||||||
};
|
};
|
||||||
|
@@ -30,6 +30,8 @@ async function send(
|
|||||||
'API call failed: ' + (error.response?.data?.message || error.message)
|
'API call failed: ' + (error.response?.data?.message || error.message)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { send };
|
module.exports = { send };
|
||||||
|
102
src/controllers/otp.controller.js
Normal file
102
src/controllers/otp.controller.js
Normal 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 };
|
28
src/middlewares/admin.middleware.js
Normal file
28
src/middlewares/admin.middleware.js
Normal 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;
|
@@ -21,5 +21,4 @@ function auth(req, res, next) {
|
|||||||
return res.status(401).json({ error: 'invalid or expired token' });
|
return res.status(401).json({ error: 'invalid or expired token' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = auth;
|
module.exports = auth;
|
||||||
|
12
src/otpgenerator.js
Normal file
12
src/otpgenerator.js
Normal 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 };
|
11
src/routes/admin_auth.route.js
Normal file
11
src/routes/admin_auth.route.js
Normal 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;
|
@@ -9,10 +9,9 @@ router.get('/user_details', authenticate, authController.fetchUserDetails);
|
|||||||
router.get('/tpin', authenticate, authController.tpin);
|
router.get('/tpin', authenticate, authController.tpin);
|
||||||
router.post('/tpin', authenticate, authController.setTpin);
|
router.post('/tpin', authenticate, authController.setTpin);
|
||||||
router.post('/login_password', authenticate, authController.setLoginPassword);
|
router.post('/login_password', authenticate, authController.setLoginPassword);
|
||||||
router.post(
|
router.post('/transaction_password',authenticate,authController.setTransactionPassword);
|
||||||
'/transaction_password',
|
router.post('/change/login_password',authenticate,authController.changeLoginPassword);
|
||||||
authenticate,
|
router.post('/change/transaction_password',authenticate,authController.changeTransPassword);
|
||||||
authController.setTransactionPassword
|
|
||||||
);
|
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
@@ -9,5 +9,9 @@ router.get('/validate/outside-bank', beneficiaryController.validateOutsideBank);
|
|||||||
router.get('/ifsc-details', beneficiaryController.getIfscDetails);
|
router.get('/ifsc-details', beneficiaryController.getIfscDetails);
|
||||||
router.get('/', beneficiaryController.getBeneficiary);
|
router.get('/', beneficiaryController.getBeneficiary);
|
||||||
router.post('/', newBeneficiaryValidator, beneficiaryController.addBeneficiary);
|
router.post('/', newBeneficiaryValidator, beneficiaryController.addBeneficiary);
|
||||||
|
router.delete(
|
||||||
|
'/:beneficiaryAccountNo',
|
||||||
|
beneficiaryController.deleteBeneficiary
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
@@ -1,5 +1,6 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const authRoute = require('./auth.route');
|
const authRoute = require('./auth.route');
|
||||||
|
const adminAuthRoute =require('./admin_auth.route');
|
||||||
const detailsRoute = require('./customer_details.route');
|
const detailsRoute = require('./customer_details.route');
|
||||||
const transactionRoute = require('./transactions.route');
|
const transactionRoute = require('./transactions.route');
|
||||||
const authenticate = require('../middlewares/auth.middleware');
|
const authenticate = require('../middlewares/auth.middleware');
|
||||||
@@ -9,10 +10,12 @@ const neftRoute = require('./neft.route');
|
|||||||
const rtgsRoute = require('./rtgs.route');
|
const rtgsRoute = require('./rtgs.route');
|
||||||
const impsRoute = require('./imps.route');
|
const impsRoute = require('./imps.route');
|
||||||
const { npciResponse } = require('../controllers/npci.controller');
|
const { npciResponse } = require('../controllers/npci.controller');
|
||||||
|
const otp = require('./otp.route');
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
router.use('/auth', authRoute);
|
router.use('/auth', authRoute);
|
||||||
|
router.use('/auth/admin',adminAuthRoute);
|
||||||
router.use('/customer', authenticate, detailsRoute);
|
router.use('/customer', authenticate, detailsRoute);
|
||||||
router.use('/transactions/account/:accountNo', authenticate, transactionRoute);
|
router.use('/transactions/account/:accountNo', authenticate, transactionRoute);
|
||||||
router.use('/payment/transfer', authenticate, transferRoute);
|
router.use('/payment/transfer', authenticate, transferRoute);
|
||||||
@@ -21,5 +24,7 @@ router.use('/payment/rtgs', authenticate, rtgsRoute);
|
|||||||
router.use('/payment/imps', authenticate, impsRoute);
|
router.use('/payment/imps', authenticate, impsRoute);
|
||||||
router.use('/beneficiary', authenticate, beneficiaryRoute);
|
router.use('/beneficiary', authenticate, beneficiaryRoute);
|
||||||
router.use('/npci/beneficiary-response', npciResponse);
|
router.use('/npci/beneficiary-response', npciResponse);
|
||||||
|
router.use('/otp', otp);
|
||||||
|
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
13
src/routes/otp.route.js
Normal file
13
src/routes/otp.route.js
Normal 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;
|
40
src/services/admin.auth.service.js
Normal file
40
src/services/admin.auth.service.js
Normal 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 };
|
@@ -1,5 +1,6 @@
|
|||||||
const db = require('../config/db');
|
const db = require('../config/db');
|
||||||
const { comparePassword, hashPassword } = require('../util/hash');
|
const { comparePassword, hashPassword } = require('../util/hash');
|
||||||
|
const dayjs =require("dayjs");
|
||||||
|
|
||||||
async function findUserByCustomerNo(customerNo) {
|
async function findUserByCustomerNo(customerNo) {
|
||||||
const result = await db.query('SELECT * FROM users WHERE customer_no = $1', [
|
const result = await db.query('SELECT * FROM users WHERE customer_no = $1', [
|
||||||
@@ -47,14 +48,16 @@ async function setTpin(customerNo, tpin) {
|
|||||||
// Set login password
|
// Set login password
|
||||||
async function setLoginPassword(customerNo, login_psw) {
|
async function setLoginPassword(customerNo, login_psw) {
|
||||||
const hashedLoginPassword = await hashPassword(login_psw);
|
const hashedLoginPassword = await hashPassword(login_psw);
|
||||||
|
const currentTime = dayjs().toISOString();
|
||||||
|
const password_expiry = dayjs().add(90,"day").toISOString();
|
||||||
try {
|
try {
|
||||||
await db.query(
|
await db.query(
|
||||||
'UPDATE users SET password_hash = $1 ,is_first_login = false WHERE customer_no = $2',
|
'UPDATE users SET password_hash = $1 ,is_first_login = false,updated_at = $3,password_hash_expiry =$4 WHERE customer_no = $2',
|
||||||
[hashedLoginPassword, customerNo]
|
[hashedLoginPassword, customerNo ,currentTime ,password_expiry]
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new 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
|
// Set transaction password
|
||||||
async function setTransactionPassword(customerNo, trans_psw) {
|
async function setTransactionPassword(customerNo, trans_psw) {
|
||||||
const hashedTransPassword = await hashPassword(trans_psw);
|
const hashedTransPassword = await hashPassword(trans_psw);
|
||||||
|
const currentTime = dayjs().toISOString();
|
||||||
|
const password_expiry = dayjs().add(90,"day").toISOString();
|
||||||
try {
|
try {
|
||||||
await db.query(
|
await db.query(
|
||||||
'UPDATE users SET transaction_password = $1 WHERE customer_no = $2',
|
'UPDATE users SET transaction_password = $1 ,updated_at = $3,transaction_password_expiry =$4 WHERE customer_no = $2',
|
||||||
[hashedTransPassword, customerNo]
|
[hashedTransPassword, customerNo , currentTime ,password_expiry]
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new 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,
|
setLoginPassword,
|
||||||
validateTransactionPassword,
|
validateTransactionPassword,
|
||||||
setTransactionPassword,
|
setTransactionPassword,
|
||||||
|
changeLoginPassword,
|
||||||
|
changeTransPassword,
|
||||||
};
|
};
|
||||||
|
@@ -44,6 +44,16 @@ async function getSingleBeneficiary(customerNo, accountNo) {
|
|||||||
return result.rows[0];
|
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) {
|
async function getAllBeneficiaries(customerNo) {
|
||||||
const queryStr =
|
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';
|
'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,
|
validateOutsideBank,
|
||||||
getAllBeneficiaries,
|
getAllBeneficiaries,
|
||||||
getSingleBeneficiary,
|
getSingleBeneficiary,
|
||||||
|
deleteBeneficiary,
|
||||||
};
|
};
|
||||||
|
@@ -2,9 +2,9 @@ const jwt = require('jsonwebtoken');
|
|||||||
const { jwtSecret } = require('../config/config');
|
const { jwtSecret } = require('../config/config');
|
||||||
const { logger } = require('./logger');
|
const { logger } = require('./logger');
|
||||||
|
|
||||||
function generateToken(customerNo, expiresIn = '10d') {
|
function generateToken(customerNo, role = 'user', expiresIn = '10d') {
|
||||||
logger.info({ customerNo }, 'payload to encode');
|
logger.info({ customerNo, role }, 'payload to encode');
|
||||||
return jwt.sign({ customerNo }, jwtSecret, { expiresIn });
|
return jwt.sign({ customerNo, role }, jwtSecret, { expiresIn });
|
||||||
}
|
}
|
||||||
|
|
||||||
function verifyToken(token) {
|
function verifyToken(token) {
|
||||||
|
@@ -1,6 +1,19 @@
|
|||||||
const pino = require('pino');
|
const pino = require('pino');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
const isDev = process.env.NODE_ENV !== 'production';
|
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({
|
const logger = pino({
|
||||||
transport: isDev
|
transport: isDev
|
||||||
? {
|
? {
|
||||||
@@ -15,8 +28,12 @@ const logger = pino({
|
|||||||
level: isDev ? 'debug' : 'info',
|
level: isDev ? 'debug' : 'info',
|
||||||
});
|
});
|
||||||
|
|
||||||
const requestLogger = (req, _res, next) => {
|
const requestLogger = pino(
|
||||||
logger.info(`${req.method} ${req.url}`);
|
{
|
||||||
next();
|
level: 'info',
|
||||||
};
|
base: null,
|
||||||
|
},
|
||||||
|
requestLoggerStream
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = { logger, requestLogger };
|
module.exports = { logger, requestLogger };
|
||||||
|
26
src/util/sms_template.js
Normal file
26
src/util/sms_template.js
Normal 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;
|
Reference in New Issue
Block a user