This commit is contained in:
romantarkin 2025-07-22 16:23:46 +05:00
parent e0076fab43
commit 0d22debf40
2 changed files with 26 additions and 2 deletions

View File

@ -1,9 +1,15 @@
import { User, Role } from '../models/index.js';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
dotenv.config();
export default {
async create(req, res) {
try {
const user = await User.create(req.body);
const { password, ...rest } = req.body;
const password_hash = await bcrypt.hash(password, 10);
const user = await User.create({ ...rest, password_hash });
res.status(201).json(user);
} catch (err) {
res.status(400).json({ error: err.message });
@ -30,7 +36,11 @@ export default {
try {
const user = await User.findByPk(req.params.id);
if (!user) return res.status(404).json({ error: 'User not found' });
await user.update(req.body);
const { password, ...rest } = req.body;
if (password) {
rest.password_hash = await bcrypt.hash(password, 10);
}
await user.update(rest);
res.json(user);
} catch (err) {
res.status(400).json({ error: err.message });
@ -46,4 +56,17 @@ export default {
res.status(500).json({ error: err.message });
}
},
async login(req, res) {
try {
const { email, password } = req.body;
const user = await User.findOne({ where: { email } });
if (!user) return res.status(401).json({ error: 'Invalid credentials' });
const valid = await bcrypt.compare(password, user.password_hash);
if (!valid) return res.status(401).json({ error: 'Invalid credentials' });
const token = jwt.sign({ id: user.id, role_id: user.role_id }, process.env.JWT_SECRET, { expiresIn: '1d' });
res.json({ token, user: { id: user.id, email: user.email, name: user.name, role_id: user.role_id } });
} catch (err) {
res.status(500).json({ error: err.message });
}
},
};

View File

@ -8,5 +8,6 @@ router.get('/', userController.getAll);
router.get('/:id', userController.getById);
router.put('/:id', userController.update);
router.delete('/:id', userController.delete);
router.post('/login', userController.login);
export default router;