import { Request, Response, NextFunction } from 'express'; import userRepository from '../repositories/userRepository'; import { NotFoundError } from '../utils/helpers'; import bcrypt from 'bcrypt'; export class UserController { async getProfile(req: Request, res: Response, next: NextFunction) { try { const user = await userRepository.findById(req.user!.userId); if (!user) throw new NotFoundError('User not found'); res.json({ success: true, data: { id: user.id, email: user.email, name: user.name, role: user.role, isEmailVerified: user.isEmailVerified, lastLoginAt: user.lastLoginAt, createdAt: user.createdAt, }, }); } catch (error) { next(error); } } async updateProfile(req: Request, res: Response, next: NextFunction) { try { const { name } = req.body; const user = await userRepository.update(req.user!.userId, { name }); res.json({ success: true, data: { id: user.id, email: user.email, name: user.name }, }); } catch (error) { next(error); } } async changePassword(req: Request, res: Response, next: NextFunction) { try { const { currentPassword, newPassword } = req.body; const user = await userRepository.findById(req.user!.userId); if (!user) throw new NotFoundError('User not found'); const isValid = await bcrypt.compare(currentPassword, user.password); if (!isValid) { return res.status(400).json({ success: false, message: 'Current password incorrect' }); } const hashedPassword = await bcrypt.hash(newPassword, 12); await userRepository.update(user.id, { password: hashedPassword }); res.json({ success: true, message: 'Password changed successfully' }); } catch (error) { next(error); } } } export default new UserController();