Spaces:
Sleeping
Sleeping
| import { Request, Response } from 'express'; | |
| import bcrypt from 'bcryptjs'; | |
| import jwt from 'jsonwebtoken'; | |
| import { PrismaClient } from '@prisma/client'; | |
| const prisma = new PrismaClient(); | |
| const JWT_SECRET = process.env.JWT_SECRET || 'kodelyx-super-secret-key-123'; | |
| export const signup = async (req: Request, res: Response) => { | |
| try { | |
| const { firstName, lastName, email, phone, password } = req.body; | |
| if (!firstName || !lastName || !email || !phone || !password) { | |
| return res.status(400).json({ message: 'All fields are required.' }); | |
| } | |
| const existingUser = await prisma.user.findUnique({ where: { email } }); | |
| if (existingUser) { | |
| return res.status(400).json({ message: 'Email address already registered.' }); | |
| } | |
| const hashedPassword = await bcrypt.hash(password, 10); | |
| const user = await prisma.user.create({ | |
| data: { | |
| firstName, | |
| lastName, | |
| email, | |
| phone, | |
| password: hashedPassword | |
| } | |
| }); | |
| return res.status(201).json({ | |
| message: 'Account created successfully.', | |
| user: { id: user.id, email: user.email, firstName: user.firstName, lastName: user.lastName } | |
| }); | |
| } catch (error: any) { | |
| console.error('Signup error:', error); | |
| return res.status(500).json({ message: 'Internal server error during registration.' }); | |
| } | |
| }; | |
| export const signin = async (req: Request, res: Response) => { | |
| try { | |
| const { email, password } = req.body; | |
| if (!email || !password) { | |
| return res.status(400).json({ message: 'Email and password are required.' }); | |
| } | |
| const user = await prisma.user.findUnique({ where: { email } }); | |
| if (!user) { | |
| return res.status(401).json({ message: 'Invalid credentials.' }); | |
| } | |
| const isMatch = await bcrypt.compare(password, user.password); | |
| if (!isMatch) { | |
| return res.status(401).json({ message: 'Invalid credentials.' }); | |
| } | |
| const token = jwt.sign( | |
| { userId: user.id, email: user.email }, | |
| JWT_SECRET, | |
| { expiresIn: '7d' } | |
| ); | |
| return res.json({ | |
| message: 'Logged in successfully.', | |
| token, | |
| user: { | |
| id: user.id, | |
| email: user.email, | |
| firstName: user.firstName, | |
| lastName: user.lastName, | |
| phone: user.phone | |
| } | |
| }); | |
| } catch (error: any) { | |
| console.error('Signin error:', error); | |
| return res.status(500).json({ message: 'Internal server error during login.' }); | |
| } | |
| }; | |