API authentifiée

This commit is contained in:
2024-12-07 13:06:15 +01:00
parent 376c297eda
commit 45a1cebcf9
23 changed files with 783 additions and 41 deletions

View File

@ -0,0 +1,27 @@
import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common'
import { PrismaService } from './../prisma/prisma.service'
import { JwtService } from '@nestjs/jwt'
import { AuthEntity } from './entity/auth.entity'
import * as bcrypt from 'bcrypt'
@Injectable()
export class AuthService {
constructor(private prisma: PrismaService, private jwtService: JwtService) {}
async login(name: string, password: string): Promise<AuthEntity> {
const user = await this.prisma.user.findUnique({ where: { name: name } })
if (!user) {
throw new NotFoundException(`Aucun⋅e utilisateur⋅rice avec pour nom ${name}`)
}
const isPasswordValid = await bcrypt.compare(password, user.password)
if (!isPasswordValid) {
throw new UnauthorizedException('Mot de passe incorrect')
}
return {
accessToken: this.jwtService.sign({ userId: user.id }),
}
}
}