63 lines
2.0 KiB
JavaScript
63 lines
2.0 KiB
JavaScript
const adminAuthService = require('../services/admin.auth.service');
|
|
const { generateToken } = require('../util/jwt');
|
|
const { logger } = require('../util/logger');
|
|
const db = require('../config/db');
|
|
// const authenticate = require('../middlewares/auth.middleware');
|
|
|
|
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'});
|
|
}
|
|
}
|
|
module.exports = { login, fetchAdminDetails, getUserDetails };
|