Files
yume_js/src/controllers/admin_auth.controller.js
tomosa.sarkar 56c69e54de feat : Admin can unlocked users
feat : admin can update and create users.
2025-11-04 13:02:18 +05:30

153 lines
5.4 KiB
JavaScript

const adminAuthService = require('../services/admin.auth.service');
const authService = require('../services/auth.service');
const { generateToken } = require('../util/jwt');
const { logger } = require('../util/logger');
const { hashPassword } = require('../util/hash');
const db = require('../config/db');
const { generateOTP } = require('../otpgenerator');
const dayjs = require("dayjs");
async function login(req, res) {
const { userName, password } = req.body;
if (!userName || !password) {
return res
.status(400)
.json({ error: 'UserName and Password are required' });
}
const currentTime = new Date().toISOString();
try {
const admin = await adminAuthService.validateAdmin(userName, password);
if (!admin) return res.status(401).json({ error: 'invalid credentials' });
const token = generateToken(admin.username, 'admin', '1d');
await db.query('UPDATE admin SET last_login = $1 WHERE username = $2', [
currentTime,
userName,
]);
res.json({ token });
} catch (err) {
logger.error(err, 'login failed');
res.status(500).json({ error: 'something went wrong' });
}
}
async function fetchAdminDetails(req, res) {
const customerNo = req.admin;
try {
const admin = await adminAuthService.findAdminByUserName(customerNo);
if (!admin) return res.status(404).json({ message: 'ADMIN_USER_NOT_FOUND' });
return res.json(admin);
} catch (err) {
logger.error(err, 'error occurred while fetching admin details');
res.status(500).json({ error: 'something went wrong' });
}
}
async function getUserDetails(req, res) {
const { CIF } = req.query;
if (!CIF) {
res.status(400).json({
error: 'CIF number is required',
});
}
try {
const userDetails = await adminAuthService.getCustomerDetails(CIF);
if (!userDetails)
return res.status(401).json({ error: 'invalid CIF number' });
return res.json(userDetails);
} catch (error) {
logger.error('while fetching customer details', error);
res.status(500).json({ error: 'invalid CIF number' });
}
}
async function getUserRights(req, res) {
const { CIF } = req.query;
if (!CIF) {
res.status(400).json({
error: 'CIF number is required',
});
}
const userDetails = await adminAuthService.getCustomerDetailsFromDB(CIF);
if (!userDetails)
return res.status(404).json({ error: 'invalid CIF number or No rights is present for the user.' });
return res.json(userDetails);
}
async function UserRights(req, res) {
try {
const { CIF, ib_access_level, mb_access_level, ib_limit, mb_limit } = req.body;
if (!CIF) {
return res.status(400).json({ error: 'CIF number is required' });
}
const currentTime = new Date().toISOString();
const user = await authService.findUserByCustomerNo(CIF);
const first_time_pass = generateOTP(6);
const password = await hashPassword(first_time_pass);
if (user) {
const FirstTimeLogin = await authService.CheckFirstTimeLogin(CIF);
// if user did not login within 7 days
if (FirstTimeLogin && dayjs(currentTime).diff(dayjs(user.created_at), 'day') > 8) {
// Password expired, resend
await db.query(
'UPDATE users SET password_hash=$2, updated_at=$5, ib_access_level=$3, mb_access_level=$4 ,inb_limit_amount=$6,mobile_limit_amount=$7 WHERE customer_no=$1',
[CIF, password, ib_access_level, mb_access_level, currentTime, ib_limit, mb_limit]
);
logger.info("Admin sended the OTP");
return res.json({ otp: first_time_pass });
}
// Just update access levels and timestamp
await db.query(
'UPDATE users SET updated_at=$4, ib_access_level=$2, mb_access_level=$3 ,inb_limit_amount=$5,mobile_limit_amount=$6 WHERE customer_no=$1',
[CIF, ib_access_level, mb_access_level, currentTime, ib_limit, mb_limit]
);
logger.info("Admin Updated the user.");
return res.json({ message: "User updated successfully." });
} else {
// User does not exist, insert
await db.query(
'INSERT INTO users (customer_no, password_hash, ib_access_level, mb_access_level ,inb_limit_amount,mobile_limit_amount) VALUES ($1, $2, $3, $4 ,$5 ,$6)',
[CIF, password, ib_access_level, mb_access_level, ib_limit, mb_limit]
);
logger.info("New user enroll by admin.");
return res.json({ otp: first_time_pass });
}
} catch (err) {
console.error(err);
logger.error(err, 'UserRights failed');
return res.status(500).json({ error: 'Something went wrong' });
}
}
async function handleUnlockUser(req, res) {
try {
const { user, action } = req.body;
const adminUserName = req.admin;
if (!user) {
return res.status(400).json({ error: "CIF or username is required" });
}
const userDetails = await adminAuthService.getCustomerDetailsFromDB(user);
if (!userDetails) {
return res
.status(404)
.json({ error: "Invalid CIF number or username" });
}
await adminAuthService.updateUserLockStatus(user, action,adminUserName);
const statusText = action ? "locked" : "unlocked";
logger.info(`User ${user} has been successfully ${statusText}.`);
return res.json({
message: `User ${user} has been successfully ${statusText}.`,
});
} catch (error) {
console.error("Unlock user error:", error);
return res.status(500).json({ error: "Internal server error" });
}
}
module.exports = { login, fetchAdminDetails, getUserDetails, UserRights, getUserRights, handleUnlockUser };