kodelyx-backend / src /auth /auth.service.ts
kodelyx's picture
Deploy NestJS backend with Prisma SQLite support
bd9f61b
Raw
History Blame Contribute Delete
2.83 kB
import { Injectable, BadRequestException, UnauthorizedException, InternalServerErrorException } from '@nestjs/common';
import { PrismaService } from '../prisma.service';
import { SignupDto, SigninDto } from './dto';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
const JWT_SECRET = process.env.JWT_SECRET || 'kodelyx-super-secret-key-123';
@Injectable()
export class AuthService {
constructor(private readonly prisma: PrismaService) {}
async signup(dto: SignupDto) {
try {
const { firstName, lastName, email, phone, password } = dto;
if (!firstName || !lastName || !email || !phone || !password) {
throw new BadRequestException('All fields are required.');
}
const existingUser = await this.prisma.user.findUnique({ where: { email } });
if (existingUser) {
throw new BadRequestException('Email address already registered.');
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = await this.prisma.user.create({
data: {
firstName,
lastName,
email,
phone,
password: hashedPassword,
},
});
return {
message: 'Account created successfully.',
user: { id: user.id, email: user.email, firstName: user.firstName, lastName: user.lastName },
};
} catch (error: any) {
if (error instanceof BadRequestException) {
throw error;
}
console.error('Signup error:', error);
throw new InternalServerErrorException('Internal server error during registration.');
}
}
async signin(dto: SigninDto) {
try {
const { email, password } = dto;
if (!email || !password) {
throw new BadRequestException('Email and password are required.');
}
const user = await this.prisma.user.findUnique({ where: { email } });
if (!user) {
throw new UnauthorizedException('Invalid credentials.');
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
throw new UnauthorizedException('Invalid credentials.');
}
const token = jwt.sign(
{ userId: user.id, email: user.email },
JWT_SECRET,
{ expiresIn: '7d' }
);
return {
message: 'Logged in successfully.',
token,
user: {
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
phone: user.phone,
},
};
} catch (error: any) {
if (error instanceof BadRequestException || error instanceof UnauthorizedException) {
throw error;
}
console.error('Signin error:', error);
throw new InternalServerErrorException('Internal server error during login.');
}
}
}