99 lines
2.4 KiB
JavaScript
99 lines
2.4 KiB
JavaScript
import express from 'express';
|
|
import jwt from 'jsonwebtoken';
|
|
import bcrypt from 'bcryptjs';
|
|
|
|
const router = express.Router();
|
|
|
|
// Mock database - replace with real DB in production
|
|
const users = [
|
|
{
|
|
id: 1,
|
|
username: 'Hr_admin',
|
|
email: 'hr@7823cpmindia.com',
|
|
password:'Hr@12345',
|
|
// password: '$2a$10$u0F8fM.6qz.2D0X0Z7.D6O9K2n0F8fM.6qz.2D0X0Z7.D6O9K2n0F8', // password123
|
|
role: 'HR'
|
|
},
|
|
{
|
|
id: 2,
|
|
username: 'slip_admin',
|
|
email: 'slip@company.com',
|
|
// password: '$2a$10$u0F8fM.6qz.2D0X0Z7.D6O9K2n0F8fM.6qz.2D0X0Z7.D6O9K2n0F8', // password123
|
|
password:'Hr@12345',
|
|
role: 'SLIP'
|
|
}
|
|
];
|
|
|
|
// Signup
|
|
router.post('/signup', async (req, res) => {
|
|
try {
|
|
const { username, email, password, role } = req.body;
|
|
|
|
if (!['HR', 'SLIP'].includes(role)) {
|
|
return res.status(400).json({ error: 'Invalid role' });
|
|
}
|
|
|
|
const hashedPassword = await bcrypt.hash(password, 10);
|
|
|
|
const newUser = {
|
|
id: users.length + 1,
|
|
username,
|
|
email,
|
|
password: hashedPassword,
|
|
role
|
|
};
|
|
|
|
users.push(newUser);
|
|
|
|
const token = jwt.sign(
|
|
{ id: newUser.id, username, role },
|
|
process.env.JWT_SECRET,
|
|
{ expiresIn: process.env.JWT_EXPIRE }
|
|
);
|
|
|
|
res.status(201).json({
|
|
token,
|
|
user: { id: newUser.id, username, email, role }
|
|
});
|
|
} catch (err) {
|
|
res.status(500).json({ error: err.message });
|
|
}
|
|
});
|
|
|
|
// Login
|
|
router.post('/login', async (req, res) => {
|
|
try {
|
|
const { email, password } = req.body;
|
|
|
|
const user = users.find(u => u.email === email);
|
|
if (!user) {
|
|
return res.status(400).json({ error: 'Invalid credentials' });
|
|
}
|
|
|
|
const password1 = users.find(u => u.password === password);
|
|
if (!password1) {
|
|
return res.status(400).json({ error: 'Invalid credentials' });
|
|
}
|
|
|
|
// const isPasswordValid = await bcrypt.compare(password, user.password);
|
|
// if (!isPasswordValid) {
|
|
// return res.status(400).json({ error: 'Invalid credentials' });
|
|
// }
|
|
|
|
const token = jwt.sign(
|
|
{ id: user.id, username: user.username, role: user.role },
|
|
process.env.JWT_SECRET,
|
|
{ expiresIn: process.env.JWT_EXPIRE }
|
|
);
|
|
|
|
res.json({
|
|
token,
|
|
user: { id: user.id, username: user.username, email: user.email, role: user.role }
|
|
});
|
|
} catch (err) {
|
|
res.status(500).json({ error: err.message });
|
|
}
|
|
});
|
|
|
|
export default router;
|