Building a REST API with NestJS and Prisma: Authentication https://www.prisma.io/blog/nestjs-prisma-rest-api-7D056s1BmOL0
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

33 lines
1.2 KiB

import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { JwtService } from '@nestjs/jwt'
import { AuthEntity } from './entities/auth.entity';
import * as bcrypt from 'bcrypt'
@Injectable()
export class AuthService {
constructor(private prisma: PrismaService, private jwtService: JwtService) { }
async login(email: string, password: string): Promise<AuthEntity> {
// Step 1: Fetch a user with the given email
const user = await this.prisma.user.findUnique({ where: { email: email } });
// If no user is found, throw an error
if (!user) {
throw new NotFoundException(`No user found for email: ${email}`);
}
// Step 2: Check if the password is correct
const isPasswordValid = await bcrypt.compare(password, user.password);
// If password does not match, throw an error
if (!isPasswordValid) {
throw new UnauthorizedException('Invalid password');
}
// Step 3: Generate a JWT containing the user's ID and return it
return {
accessToken: this.jwtService.sign({ userId: user.id }),
};
}
}