| import { Router, Request, Response } from 'express';
|
| import jwt from 'jsonwebtoken';
|
| import { User } from '../models';
|
| import { config } from '../config';
|
| import { logger } from '../utils/logger';
|
|
|
| const router = Router();
|
|
|
|
|
| router.post('/register', async (req: Request, res: Response) => {
|
| try {
|
| const { email, password } = req.body;
|
|
|
| if (!email || !password) {
|
| res.status(400).json({ error: 'Email and password are required.' });
|
| return;
|
| }
|
|
|
| if (password.length < 8) {
|
| res.status(400).json({ error: 'Password must be at least 8 characters.' });
|
| return;
|
| }
|
|
|
| const existing = await User.findOne({ email: email.toLowerCase() });
|
| if (existing) {
|
| res.status(409).json({ error: 'Email already registered.' });
|
| return;
|
| }
|
|
|
| const user = new User({ email, password });
|
| await user.save();
|
|
|
| const token = jwt.sign(
|
| { userId: user._id, role: user.role },
|
| config.jwt.secret,
|
| { expiresIn: config.jwt.expiresIn }
|
| );
|
|
|
| logger.info(`User registered: ${email}`);
|
|
|
| res.status(201).json({
|
| token,
|
| user: {
|
| id: user._id,
|
| email: user.email,
|
| subscription: user.subscription,
|
| role: user.role,
|
| },
|
| });
|
| } catch (error: any) {
|
| logger.error('Registration error:', error);
|
| res.status(500).json({ error: 'Registration failed.' });
|
| }
|
| });
|
|
|
|
|
| router.post('/login', async (req: Request, res: Response) => {
|
| try {
|
| const { email, password } = req.body;
|
|
|
| if (!email || !password) {
|
| res.status(400).json({ error: 'Email and password are required.' });
|
| return;
|
| }
|
|
|
| const user = await User.findOne({ email: email.toLowerCase() });
|
| if (!user) {
|
| res.status(401).json({ error: 'Invalid credentials.' });
|
| return;
|
| }
|
|
|
| const isMatch = await user.comparePassword(password);
|
| if (!isMatch) {
|
| res.status(401).json({ error: 'Invalid credentials.' });
|
| return;
|
| }
|
|
|
| const token = jwt.sign(
|
| { userId: user._id, role: user.role },
|
| config.jwt.secret,
|
| { expiresIn: config.jwt.expiresIn }
|
| );
|
|
|
| logger.info(`User logged in: ${email}`);
|
|
|
| res.json({
|
| token,
|
| user: {
|
| id: user._id,
|
| email: user.email,
|
| subscription: user.subscription,
|
| role: user.role,
|
| videosGenerated: user.videosGenerated,
|
| },
|
| });
|
| } catch (error: any) {
|
| logger.error('Login error:', error);
|
| res.status(500).json({ error: 'Login failed.' });
|
| }
|
| });
|
|
|
| export default router;
|
|
|